forked from sqlitebrowser/sqlitebrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlitetypes.cpp
More file actions
700 lines (575 loc) · 17.9 KB
/
sqlitetypes.cpp
File metadata and controls
700 lines (575 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#include "sqlitetypes.h"
#include "ObjectIdentifier.h"
#include "parser/ParserDriver.h"
#include <iostream>
#include <iterator>
#include <numeric>
namespace sqlb {
StringVector escapeIdentifier(StringVector ids)
{
std::transform(ids.begin(), ids.end(), ids.begin(), [](const std::string& id) {
return escapeIdentifier(id);
});
return ids;
}
std::string joinStringVector(const StringVector& vec, const std::string& delim)
{
return std::accumulate(vec.begin(), vec.end(), std::string(), [delim](const std::string& so_far, const std::string& s) {
return so_far.empty() ? s : so_far + delim + s;
});
}
bool Object::operator==(const Object& rhs) const
{
if(m_name != rhs.m_name)
return false;
if(m_fullyParsed != rhs.m_fullyParsed) // We check for the fully parsed flag to make sure not to lose anything in some corner cases
return false;
// We don't care about the original SQL text
return true;
}
std::string Object::typeToString(Types type)
{
switch(type)
{
case Types::Table: return "table";
case Types::Index: return "index";
case Types::View: return "view";
case Types::Trigger: return "trigger";
}
return std::string();
}
ConstraintPtr Constraint::makeConstraint(ConstraintTypes type)
{
switch(type)
{
case PrimaryKeyConstraintType:
return std::make_shared<PrimaryKeyConstraint>();
case UniqueConstraintType:
return std::make_shared<UniqueConstraint>();
case ForeignKeyConstraintType:
return std::make_shared<ForeignKeyClause>();
case CheckConstraintType:
return std::make_shared<CheckConstraint>();
default:
return nullptr;
}
}
void Constraint::replaceInColumnList(const std::string& from, const std::string& to)
{
std::replace(column_list.begin(), column_list.end(), from, to);
}
void Constraint::removeFromColumnList(const std::string& key)
{
column_list.erase(std::remove(column_list.begin(), column_list.end(), key), column_list.end());
}
bool ForeignKeyClause::isSet() const
{
return m_override.size() || m_table.size();
}
std::string ForeignKeyClause::toString() const
{
if(!isSet())
return std::string();
if(m_override.size())
return m_override;
std::string result = escapeIdentifier(m_table);
if(m_columns.size())
result += "(" + joinStringVector(escapeIdentifier(m_columns), ",") + ")";
if(m_constraint.size())
result += " " + m_constraint;
return result;
}
void ForeignKeyClause::setFromString(const std::string& fk)
{
m_override = fk;
}
std::string ForeignKeyClause::toSql() const
{
std::string result;
if(!m_name.empty())
result = "CONSTRAINT " + escapeIdentifier(m_name) + " ";
result += "FOREIGN KEY(" + joinStringVector(escapeIdentifier(column_list), ",") + ") REFERENCES " + this->toString();
return result;
}
UniqueConstraint::UniqueConstraint(const IndexedColumnVector& columns) :
m_columns(columns)
{
// Extract column names and give them to the column list in the base class
for(const auto& c : columns)
column_list.push_back(c.name());
}
UniqueConstraint::UniqueConstraint(const StringVector& columns) :
Constraint(columns)
{
setColumnList(columns);
}
void UniqueConstraint::setColumnList(const StringVector& list)
{
Constraint::setColumnList(list);
// Create our own column list without sort orders etc
m_columns.clear();
for(const auto& c : list)
m_columns.push_back(IndexedColumn(c, false));
}
void UniqueConstraint::addToColumnList(const std::string& key)
{
Constraint::addToColumnList(key);
// Also add to our own column list
m_columns.push_back(IndexedColumn(key, false));
}
void UniqueConstraint::replaceInColumnList(const std::string& from, const std::string& to)
{
Constraint::replaceInColumnList(from, to);
for(auto& c : m_columns)
{
if(c.name() == from)
c.setName(to);
}
}
void UniqueConstraint::removeFromColumnList(const std::string& key)
{
Constraint::removeFromColumnList(key);
m_columns.erase(std::remove_if(m_columns.begin(), m_columns.end(), [key](const IndexedColumn& c) {
if(c.name() == key)
return true;
else
return false;
}), m_columns.end());
}
std::string UniqueConstraint::toSql() const
{
std::string result;
if(!m_name.empty())
result = "CONSTRAINT " + escapeIdentifier(m_name) + " ";
std::vector<std::string> u_columns;
for(const auto& c : m_columns)
u_columns.push_back(c.toString("", " "));
result += "UNIQUE(" + joinStringVector(u_columns, ",") + ")";
if(!m_conflictAction.empty())
result += " ON CONFLICT " + m_conflictAction;
return result;
}
PrimaryKeyConstraint::PrimaryKeyConstraint(const IndexedColumnVector& columns) :
UniqueConstraint(columns),
m_auto_increment(false)
{
}
PrimaryKeyConstraint::PrimaryKeyConstraint(const StringVector& columns) :
UniqueConstraint(columns),
m_auto_increment(false)
{
}
std::string PrimaryKeyConstraint::toSql() const
{
std::string result;
if(!m_name.empty())
result = "CONSTRAINT " + escapeIdentifier(m_name) + " ";
std::vector<std::string> pk_columns;
for(const auto& c : m_columns)
pk_columns.push_back(c.toString("", " "));
result += "PRIMARY KEY(" + joinStringVector(pk_columns, ",") + (m_auto_increment ? " AUTOINCREMENT" : "") + ")";
if(!m_conflictAction.empty())
result += " ON CONFLICT " + m_conflictAction;
return result;
}
std::string CheckConstraint::toSql() const
{
std::string result;
if(!m_name.empty())
result = "CONSTRAINT " + escapeIdentifier(m_name) + " ";
result += "CHECK(" + m_expression + ")";
return result;
}
bool Field::operator==(const Field& rhs) const
{
if(m_name != rhs.m_name)
return false;
if(m_type != rhs.m_type)
return false;
if(m_notnull != rhs.m_notnull)
return false;
if(m_check != rhs.m_check)
return false;
if(m_defaultvalue != rhs.m_defaultvalue)
return false;
if(m_unique != rhs.m_unique)
return false;
if(m_collation != rhs.m_collation)
return false;
return true;
}
std::string Field::toString(const std::string& indent, const std::string& sep) const
{
std::string str = indent + escapeIdentifier(m_name) + sep + m_type;
if(m_notnull)
str += " NOT NULL";
if(!m_defaultvalue.empty())
str += " DEFAULT " + m_defaultvalue;
if(!m_check.empty())
str += " CHECK(" + m_check + ")";
if(m_unique)
str += " UNIQUE";
if(!m_collation.empty())
str += " COLLATE " + m_collation;
return str;
}
bool Field::isText() const
{
if(starts_with_ci(m_type, "character")) return true;
if(starts_with_ci(m_type, "varchar")) return true;
if(starts_with_ci(m_type, "varying character")) return true;
if(starts_with_ci(m_type, "nchar")) return true;
if(starts_with_ci(m_type, "native character")) return true;
if(starts_with_ci(m_type, "nvarchar")) return true;
if(compare_ci(m_type, "text")) return true;
if(compare_ci(m_type, "clob")) return true;
return false;
}
bool Field::isInteger() const
{
if(compare_ci(m_type, "int")) return true;
if(compare_ci(m_type, "integer")) return true;
if(compare_ci(m_type, "tinyint")) return true;
if(compare_ci(m_type, "smallint")) return true;
if(compare_ci(m_type, "mediumint")) return true;
if(compare_ci(m_type, "bigint")) return true;
if(compare_ci(m_type, "unsigned big int")) return true;
if(compare_ci(m_type, "int2")) return true;
if(compare_ci(m_type, "int8")) return true;
return false;
}
bool Field::isReal() const
{
if(compare_ci(m_type, "real")) return true;
if(compare_ci(m_type, "double")) return true;
if(compare_ci(m_type, "double precision")) return true;
if(compare_ci(m_type, "float")) return true;
return false;
}
bool Field::isNumeric() const
{
if(starts_with_ci(m_type, "decimal")) return true;
if(compare_ci(m_type, "numeric")) return true;
if(compare_ci(m_type, "boolean")) return true;
if(compare_ci(m_type, "date")) return true;
if(compare_ci(m_type, "datetime")) return true;
return false;
}
bool Field::isBlob() const
{
if(m_type.empty()) return true;
if(compare_ci(m_type, "blob")) return true;
return false;
}
Field::Affinity Field::affinity() const
{
if (isInteger()) return IntegerAffinity;
if (isText()) return TextAffinity;
if (isBlob()) return BlobAffinity;
if (isReal() || isNumeric()) return FloatAffinity;
return BlobAffinity;
}
Table::Table(const Table& table)
: Object(table.name())
{
*this = table;
}
Table& Table::operator=(const Table& rhs)
{
// Base class
Object::operator=(rhs);
// Just assign the simple values
m_withoutRowid = rhs.m_withoutRowid;
m_virtual = rhs.m_virtual;
// Clear the fields and the constraints first in order to avoid duplicates and/or old data in the next step
fields.clear();
m_constraints.clear();
// Make copies of the fields and the constraints. This is necessary in order to avoid any unwanted changes to the application's main database
// schema representation just by modifying a reference to the fields or constraints and thinking it operates on a copy.
std::copy(rhs.fields.begin(), rhs.fields.end(), std::back_inserter(fields));
m_constraints = rhs.m_constraints;
return *this;
}
bool Table::operator==(const Table& rhs) const
{
if(!Object::operator==(rhs))
return false;
if(m_withoutRowid != rhs.m_withoutRowid)
return false;
if(m_virtual != rhs.m_virtual)
return false;
if(fields != rhs.fields)
return false;
if(m_constraints != rhs.m_constraints)
return false;
return true;
}
StringVector Table::fieldList() const
{
StringVector sl;
for(const Field& f : fields)
sl.push_back(f.toString());
return sl;
}
StringVector Table::fieldNames() const
{
StringVector sl;
for(const Field& f : fields)
sl.push_back(f.name());
return sl;
}
StringVector Table::rowidColumns() const
{
// For WITHOUT ROWID tables this function returns the names of the primary key column. For ordinary tables with a rowid column, it returns "_rowid_"
if(m_withoutRowid)
return const_cast<Table*>(this)->primaryKey()->columnList();
else
return {"_rowid_"};
}
FieldInfoList Table::fieldInformation() const
{
FieldInfoList result;
for(const Field& f : fields)
result.emplace_back(f.name(), f.type(), f.toString(" ", " "));
return result;
}
TablePtr Table::parseSQL(const std::string& sSQL)
{
parser::ParserDriver drv;
if(!drv.parse(sSQL))
{
TablePtr t = std::dynamic_pointer_cast<Table>(drv.result);
t->setOriginalSql(sSQL);
return t;
} else {
std::cerr << "Sqlite parse error: " << sSQL << std::endl;
return std::make_shared<Table>("");
}
}
std::string Table::sql(const std::string& schema, bool ifNotExists) const
{
// Special handling for virtual tables: just build an easy create statement and copy the using part in there
if(isVirtual())
return "CREATE VIRTUAL TABLE " + ObjectIdentifier(schema, m_name).toString(true) + " USING " + m_virtual + ";";
// This is a normal table, not a virtual one
std::string sql = "CREATE TABLE ";
if(ifNotExists)
sql += "IF NOT EXISTS ";
sql += ObjectIdentifier(schema, m_name).toString(true);
sql += " (\n";
sql += joinStringVector(fieldList(), ",\n");
// Constraints
for(const auto& it : m_constraints)
{
// Ignore all constraints without any fields, except for check constraints which don't rely on a field vector
if(!it->columnList().empty() || it->type() == Constraint::CheckConstraintType)
{
sql += ",\n\t";
sql += it->toSql();
}
}
sql += "\n)";
// without rowid
if(withoutRowidTable())
sql += " WITHOUT ROWID";
return sql + ";";
}
void Table::addConstraint(ConstraintPtr constraint)
{
m_constraints.insert(constraint);
}
void Table::setConstraint(ConstraintPtr constraint)
{
// Delete any old constraints of this type for these fields
removeConstraints(constraint->columnList(), constraint->type());
// Add the new constraint to the table, effectively overwriting all old constraints for that fields/type combination
addConstraint(constraint);
}
void Table::removeConstraint(ConstraintPtr constraint)
{
for(auto it = m_constraints.begin();it!=m_constraints.end();++it)
{
if((*it)->toSql() == constraint->toSql())
{
m_constraints.erase(it);
// Only remove the first constraint matching these criteria
return;
}
}
}
void Table::removeConstraints(const StringVector& vStrFields, Constraint::ConstraintTypes type)
{
for(auto it = m_constraints.begin();it!=m_constraints.end();)
{
if((*it)->columnList() == vStrFields && (*it)->type() == type)
m_constraints.erase(it++);
else
++it;
}
}
ConstraintPtr Table::constraint(const StringVector& vStrFields, Constraint::ConstraintTypes type) const
{
auto list = constraints(vStrFields, type);
if(list.size())
return list.at(0);
else
return ConstraintPtr(nullptr);
}
std::vector<ConstraintPtr> Table::constraints(const StringVector& vStrFields, Constraint::ConstraintTypes type) const
{
std::vector<ConstraintPtr> clist;
for(const auto& it : m_constraints)
{
if((type == Constraint::NoType || it->type() == type) && (vStrFields.empty() || it->columnList() == vStrFields))
clist.push_back(it);
}
return clist;
}
void Table::setConstraints(const ConstraintSet& constraints)
{
m_constraints = constraints;
}
void Table::replaceConstraint(ConstraintPtr from, ConstraintPtr to)
{
auto it = m_constraints.find(from);
if(it == m_constraints.end())
return;
m_constraints.erase(it); // Erase old constraint
m_constraints.insert(to); // Insert new constraint
}
std::shared_ptr<PrimaryKeyConstraint> Table::primaryKey()
{
const auto c = constraint({}, Constraint::PrimaryKeyConstraintType);
if(c)
return std::dynamic_pointer_cast<PrimaryKeyConstraint>(c);
else
return nullptr;
}
void Table::removeKeyFromAllConstraints(const std::string& key)
{
// Update all constraints
for(auto it=m_constraints.begin();it!=m_constraints.end();)
{
// Check if they contain the old key name
if(contains((*it)->columnList(), key))
{
// If so, remove it from the column list
(*it)->removeFromColumnList(key);
// If the column list is empty now, remove the entire constraint. Otherwise save the updated column list
if((*it)->columnList().empty())
it = m_constraints.erase(it);
else
++it;
} else {
++it;
}
}
}
void Table::renameKeyInAllConstraints(const std::string& key, const std::string& to)
{
// Do nothing if the key hasn't really changed
if(key == to)
return;
// Find all occurrences of the key and change it to the new one
for(auto& it : m_constraints)
{
if(contains(it->columnList(), key))
it->replaceInColumnList(key, to);
}
}
std::string IndexedColumn::toString(const std::string& indent, const std::string& sep) const
{
std::string name = m_isExpression ? m_name : escapeIdentifier(m_name);
std::string order = (m_order.empty() ? "" : (sep + m_order));
return indent + name + order;
}
Index& Index::operator=(const Index& rhs)
{
// Base class
Object::operator=(rhs);
// Just assign the easy stuff
m_unique = rhs.m_unique;
m_table = rhs.m_table;
m_whereExpr = rhs.m_whereExpr;
// Make copies of the column
std::copy(rhs.fields.begin(), rhs.fields.end(), std::back_inserter(fields));
return *this;
}
StringVector Index::columnSqlList() const
{
StringVector sl;
for(const IndexedColumn& c : fields)
sl.push_back(c.toString());
return sl;
}
std::string Index::sql(const std::string& schema, bool ifNotExists) const
{
// Start CREATE (UNIQUE) INDEX statement
std::string sql;
if(m_unique)
sql = "CREATE UNIQUE INDEX ";
else
sql = "CREATE INDEX ";
if(ifNotExists)
sql += "IF NOT EXISTS ";
sql += ObjectIdentifier(schema, m_name).toString(true);
sql += " ON ";
sql += sqlb::escapeIdentifier(m_table);
sql += " (\n";
// Add column list
sql += joinStringVector(columnSqlList(), ",\n");
// Add partial index bit
sql += "\n)";
if(!m_whereExpr.empty())
sql += " WHERE " + m_whereExpr;
return sql + ";";
}
FieldInfoList Index::fieldInformation() const
{
FieldInfoList result;
for(const IndexedColumn& c : fields)
result.emplace_back(c.name(), c.order(), c.toString(" ", " "));
return result;
}
IndexPtr Index::parseSQL(const std::string& sSQL)
{
parser::ParserDriver drv;
if(!drv.parse(sSQL))
{
IndexPtr i = std::dynamic_pointer_cast<Index>(drv.result);
i->setOriginalSql(sSQL);
return i;
} else {
std::cerr << "Sqlite parse error: " << sSQL << std::endl;
return std::make_shared<Index>("");
}
}
ViewPtr View::parseSQL(const std::string& sSQL)
{
// TODO
auto v = std::make_shared<View>("");
v->setOriginalSql(sSQL);
return v;
}
StringVector View::fieldNames() const
{
StringVector sl;
for(const Field& f : fields)
sl.push_back(f.name());
return sl;
}
FieldInfoList View::fieldInformation() const
{
FieldInfoList result;
for(const Field& f : fields)
result.emplace_back(f.name(), f.type(), f.toString(" ", " "));
return result;
}
TriggerPtr Trigger::parseSQL(const std::string& sSQL)
{
// TODO
auto t = std::make_shared<Trigger>("");
t->setOriginalSql(sSQL);
return t;
}
} //namespace sqlb