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
776 lines (664 loc) · 22.8 KB
/
sqlitetypes.cpp
File metadata and controls
776 lines (664 loc) · 22.8 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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#include "sqlitetypes.h"
#include "grammar/Sqlite3Lexer.hpp"
#include "grammar/Sqlite3Parser.hpp"
#include <sstream>
#include <QDebug>
namespace sqlb {
QStringList Field::Datatypes = QStringList() << "INTEGER" << "TEXT" << "BLOB" << "REAL" << "NUMERIC";
QString escapeIdentifier(QString id)
{
return '`' + id.replace('`', "``") + '`';
}
QStringList fieldVectorToFieldNames(const FieldVector& vector)
{
QStringList result;
foreach(const FieldPtr& field, vector)
result.append(escapeIdentifier(field->name()));
return result;
}
bool ForeignKeyClause::isSet() const
{
return m_override.size() || m_table.size();
}
QString ForeignKeyClause::toString() const
{
if(!isSet())
return QString();
if(m_override.size())
return m_override;
QString result = escapeIdentifier(m_table);
if(m_columns.size())
{
result += "(";
foreach(const QString& column, m_columns)
result += escapeIdentifier(column) + ',';
result.chop(1); // Remove last comma
result += ")";
}
if(m_constraint.size())
result += " " + m_constraint;
return result;
}
void ForeignKeyClause::setFromString(const QString& fk)
{
m_override = fk;
}
QString ForeignKeyClause::toSql(const FieldVector& applyOn) const
{
QString result;
if(!m_name.isNull())
result += QString("CONSTRAINT %1 ").arg(escapeIdentifier(m_name));
result += QString("FOREIGN KEY(%1) REFERENCES %2").arg(fieldVectorToFieldNames(applyOn).join(",")).arg(this->toString());
return result;
}
QString UniqueConstraint::toSql(const FieldVector& applyOn) const
{
QString result;
if(!m_name.isNull())
result += QString("CONSTRAINT %1 ").arg(escapeIdentifier(m_name));
result += QString("UNIQUE(%1)").arg(fieldVectorToFieldNames(applyOn).join(","));
return result;
}
QString PrimaryKeyConstraint::toSql(const FieldVector& applyOn) const
{
QString result;
if(!m_name.isNull())
result += QString("CONSTRAINT %1 ").arg(escapeIdentifier(m_name));
result += QString("PRIMARY KEY(%1)").arg(fieldVectorToFieldNames(applyOn).join(","));
return result;
}
QString Field::toString(const QString& indent, const QString& sep) const
{
QString str = indent + escapeIdentifier(m_name) + sep + m_type;
if(m_notnull)
str += " NOT NULL";
if(!m_defaultvalue.isEmpty())
str += QString(" DEFAULT %1").arg(m_defaultvalue);
if(!m_check.isEmpty())
str += " CHECK(" + m_check + ")";
if(m_autoincrement)
str += " PRIMARY KEY AUTOINCREMENT";
if(m_unique)
str += " UNIQUE";
return str;
}
bool Field::isText() const
{
QString norm = m_type.trimmed().toLower();
return norm.startsWith("character")
|| norm.startsWith("varchar")
|| norm.startsWith("varying character")
|| norm.startsWith("nchar")
|| norm.startsWith("native character")
|| norm.startsWith("nvarchar")
|| norm == "text"
|| norm == "clob";
}
bool Field::isInteger() const
{
QString norm = m_type.trimmed().toLower();
return norm == "int"
|| norm == "integer"
|| norm == "tinyint"
|| norm == "smallint"
|| norm == "mediumint"
|| norm == "bigint"
|| norm == "unsigned big int"
|| norm == "int2"
|| norm == "int8";
}
void Table::clear()
{
m_rowidColumn = "_rowid_";
m_fields.clear();
m_constraints.clear();
}
Table::~Table()
{
clear();
}
void Table::addField(const FieldPtr& f)
{
m_fields.append(FieldPtr(f));
}
bool Table::removeField(const QString& sFieldName)
{
int index = findField(sFieldName);
if( index != -1)
{
m_fields.remove(index);
return true;
}
return false;
}
void Table::setFields(const FieldVector &fields)
{
clear();
m_fields = fields;
}
void Table::setField(int index, FieldPtr f)
{
FieldPtr oldField = m_fields[index];
m_fields[index] = f;
// Update all constraints. If an existing field is updated but was used in a constraint, the pointers in the constraint key needs to be updated
// to the new field, too.
if(oldField)
{
ConstraintMap::iterator it = m_constraints.begin();
while(it != m_constraints.end())
{
// Loop through all fields mentioned in a foreign key
FieldVector fields = it.key();
bool modified = false;
for(int i=0;i<fields.size();++i)
{
// If the field that is being modified is in there update it to the new field and set a flag that something has changed.
// This is used below to know when to update the map key
if(fields[i] == oldField)
{
fields[i] = f;
modified = true;
}
}
if(modified)
{
// When we need to update the map key, we insert a new constraint using the updated field vector and the old
// constraint information, and delete the old one afterwards
m_constraints.insert(fields, it.value());
it = m_constraints.erase(it);
} else {
++it;
}
}
}
}
int Table::findField(const QString &sname) const
{
for(int i = 0; i < m_fields.count(); ++i)
{
if(m_fields.at(i)->name().compare(sname, Qt::CaseInsensitive) == 0)
return i;
}
return -1;
}
int Table::findPk() const
{
// TODO This is a stupid function (and always was) which should be fixed/improved
FieldVector pk = primaryKey();
if(pk.empty())
return -1;
else
return findField(pk.at(0)->name());
}
QStringList Table::fieldList() const
{
QStringList sl;
foreach(const FieldPtr& f, m_fields) {
sl << f->toString();
}
return sl;
}
QStringList Table::fieldNames() const
{
QStringList sl;
foreach(FieldPtr f, m_fields)
sl << f->name();
return sl;
}
bool Table::hasAutoIncrement() const
{
foreach(FieldPtr f, m_fields) {
if(f->autoIncrement())
return true;
}
return false;
}
QPair<Table, bool> Table::parseSQL(const QString &sSQL)
{
std::stringstream s;
s << sSQL.toStdString();
Sqlite3Lexer lex(s);
Sqlite3Parser parser(lex);
antlr::ASTFactory ast_factory;
parser.initializeASTFactory(ast_factory);
parser.setASTFactory(&ast_factory);
try
{
parser.createtable();
CreateTableWalker ctw(parser.getAST());
return qMakePair(ctw.table(), ctw.modifysupported());
}
catch(antlr::ANTLRException& ex)
{
qCritical() << "Sqlite parse error: " << QString::fromStdString(ex.toString()) << "(" << sSQL << ")";
}
catch(...)
{
qCritical() << "Sqlite parse error: " << sSQL; //TODO
}
return qMakePair(Table(""), false);
}
QString Table::sql() const
{
QString sql = QString("CREATE TABLE %1 (\n").arg(escapeIdentifier(m_name));
sql += fieldList().join(",\n");
// Constraints
ConstraintMap::const_iterator it = m_constraints.constBegin();
bool autoincrement = hasAutoIncrement();
while(it != m_constraints.constEnd())
{
if(!autoincrement || it.value()->type() != Constraint::PrimaryKeyConstraintType)
{
sql += QString(",\n\t");
sql += it.value()->toSql(it.key());
}
++it;
}
sql += "\n)";
// without rowid
if(isWithoutRowidTable())
sql += " WITHOUT ROWID";
return sql + ";";
}
void Table::addConstraint(FieldPtr field, ConstraintPtr constraint)
{
FieldVector v;
v.push_back(field);
addConstraint(v, constraint);
}
void Table::addConstraint(FieldVector fields, ConstraintPtr constraint)
{
m_constraints.insert(fields, constraint);
}
ConstraintPtr Table::constraint(FieldPtr field, Constraint::ConstraintTypes type) const
{
QList<ConstraintPtr> list = constraints(field, type);
if(list.size())
return list.at(0);
else
return ConstraintPtr(nullptr);
}
ConstraintPtr Table::constraint(FieldVector fields, Constraint::ConstraintTypes type) const
{
QList<ConstraintPtr> list = constraints(fields, type);
if(list.size())
return list.at(0);
else
return ConstraintPtr(nullptr);
}
QList<ConstraintPtr> Table::constraints(FieldPtr field, Constraint::ConstraintTypes type) const
{
FieldVector v;
v.push_back(field);
return constraints(v, type);
}
QList<ConstraintPtr> Table::constraints(FieldVector fields, Constraint::ConstraintTypes type) const
{
QList<ConstraintPtr> clist;
if(fields.isEmpty())
clist = m_constraints.values();
else
clist = m_constraints.values(fields);
if(type == Constraint::NoType)
{
return clist;
} else {
QList<ConstraintPtr> clist_typed;
foreach(const ConstraintPtr& ptr, clist)
{
if(ptr->type() == type)
clist_typed.push_back(ptr);
}
return clist_typed;
}
}
FieldVector& Table::primaryKeyRef()
{
return const_cast<FieldVector&>(static_cast<const Table*>(this)->primaryKey());
}
const FieldVector& Table::primaryKey() const
{
ConstraintMap::ConstIterator it = m_constraints.constBegin();
while(it != m_constraints.constEnd())
{
if(it.value()->type() == Constraint::PrimaryKeyConstraintType)
return it.key();
++it;
}
static FieldVector emptyFieldVector;
return emptyFieldVector;
}
namespace
{
QString identifier(antlr::RefAST ident)
{
QString sident = ident->getText().c_str();
if(ident->getType() == sqlite3TokenTypes::QUOTEDID ||
ident->getType() == Sqlite3Lexer::QUOTEDLITERAL ||
ident->getType() == sqlite3TokenTypes::STRINGLITERAL)
{
// Remember the way the identifier is quoted
QChar quoteChar = sident.at(0);
// Remove first and final character, i.e. the quotes
sident.remove(0, 1);
sident.chop(1);
// Replace all remaining occurences of two succeeding quote characters and replace them
// by a single instance. This is done because two quotes can be used as a means of escaping
// the quote character, thus only the visual representation has its two quotes, the actual
// name contains only one.
sident.replace(QString(quoteChar) + quoteChar, quoteChar);
}
return sident;
}
QString concatTextAST(antlr::RefAST t, bool withspace = false)
{
QStringList stext;
while(t != antlr::nullAST)
{
stext.append(t->getText().c_str());
t = t->getNextSibling();
}
return stext.join(withspace ? " " : "");
}
}
namespace {
QString tablename(const antlr::RefAST& n)
{
if(n->getType() == sqlite3TokenTypes::KEYWORDASTABLENAME)
return concatTextAST(n->getFirstChild());
else
return identifier(n);
}
QString columnname(const antlr::RefAST& n)
{
if(n->getType() == sqlite3TokenTypes::KEYWORDASCOLUMNNAME)
return concatTextAST(n->getFirstChild());
else
return identifier(n);
}
}
Table CreateTableWalker::table()
{
Table tab("");
if( m_root ) //CREATE TABLE
{
antlr::RefAST s = m_root->getFirstChild();
//skip to tablename
while(s->getType() != Sqlite3Lexer::ID &&
s->getType() != Sqlite3Lexer::QUOTEDID &&
s->getType() != Sqlite3Lexer::QUOTEDLITERAL &&
s->getType() != Sqlite3Lexer::STRINGLITERAL &&
s->getType() != sqlite3TokenTypes::KEYWORDASTABLENAME)
{
s = s->getNextSibling();
}
tab.setName(tablename(s));
s = s->getNextSibling(); // LPAREN
s = s->getNextSibling(); // first column name
antlr::RefAST column = s;
// loop columndefs
while(column != antlr::nullAST && column->getType() == sqlite3TokenTypes::COLUMNDEF)
{
parsecolumn(tab, column->getFirstChild());
column = column->getNextSibling(); //COMMA or RPAREN
column = column->getNextSibling(); //null or tableconstraint
s = s->getNextSibling(); // COLUMNDEF
s = s->getNextSibling(); // COMMA or RPAREN
}
// now we are finished or it is a tableconstraint
while(s != antlr::nullAST)
{
// Is this a 'without rowid' definiton?
if(s->getType() != sqlite3TokenTypes::WITHOUT)
{
// It's not, so treat this as table constraints
antlr::RefAST tc = s->getFirstChild();
// skip constraint name, if there is any
QString constraint_name;
if(tc->getType() == sqlite3TokenTypes::CONSTRAINT)
{
tc = tc->getNextSibling(); // CONSTRAINT
constraint_name = identifier(tc);
tc = tc->getNextSibling(); // identifier
}
switch(tc->getType())
{
case sqlite3TokenTypes::PRIMARY:
{
PrimaryKeyConstraint* pk = new PrimaryKeyConstraint;
pk->setName(constraint_name);
tc = tc->getNextSibling()->getNextSibling(); // skip primary and key
tc = tc->getNextSibling(); // skip LPAREN
FieldVector fields;
do
{
QString col = columnname(tc);
FieldPtr field = tab.field(tab.findField(col));
fields.push_back(field);
tc = tc->getNextSibling();
if(tc != antlr::nullAST
&& (tc->getType() == sqlite3TokenTypes::ASC
|| tc->getType() == sqlite3TokenTypes::DESC))
{
// TODO save ASC / DESC information?
m_bModifySupported = false;
tc = tc->getNextSibling();
}
if(tc != antlr::nullAST && tc->getType() == sqlite3TokenTypes::AUTOINCREMENT)
{
field->setAutoIncrement(true);
tc = tc->getNextSibling();
}
while(tc != antlr::nullAST && tc->getType() == sqlite3TokenTypes::COMMA)
{
tc = tc->getNextSibling(); // skip ident and comma
}
} while(tc != antlr::nullAST && tc->getType() != sqlite3TokenTypes::RPAREN);
tab.addConstraint(fields, ConstraintPtr(pk));
}
break;
case sqlite3TokenTypes::UNIQUE:
{
UniqueConstraint* unique = new UniqueConstraint;
unique->setName(constraint_name);
tc = tc->getNextSibling(); // skip UNIQUE
tc = tc->getNextSibling(); // skip LPAREN
FieldVector fields;
do
{
QString col = columnname(tc);
FieldPtr field = tab.field(tab.findField(col));
fields.push_back(field);
tc = tc->getNextSibling();
if(tc != antlr::nullAST
&& (tc->getType() == sqlite3TokenTypes::ASC
|| tc->getType() == sqlite3TokenTypes::DESC))
{
// TODO save ASC / DESC information?
m_bModifySupported = false;
tc = tc->getNextSibling();
}
while(tc != antlr::nullAST && tc->getType() == sqlite3TokenTypes::COMMA)
{
tc = tc->getNextSibling(); // skip ident and comma
}
} while(tc != antlr::nullAST && tc->getType() != sqlite3TokenTypes::RPAREN);
if(fields.size() == 1 && constraint_name.isEmpty())
fields[0]->setUnique(true);
else
tab.addConstraint(fields, ConstraintPtr(unique));
}
break;
case sqlite3TokenTypes::FOREIGN:
{
ForeignKeyClause* fk = new ForeignKeyClause;
fk->setName(constraint_name);
tc = tc->getNextSibling(); // FOREIGN
tc = tc->getNextSibling(); // KEY
tc = tc->getNextSibling(); // LPAREN
FieldVector fields;
do
{
QString col = columnname(tc);
FieldPtr field = tab.field(tab.findField(col));
fields.push_back(field);
tc = tc->getNextSibling();
while(tc != antlr::nullAST && tc->getType() == sqlite3TokenTypes::COMMA)
tc = tc->getNextSibling(); // skip ident and comma
} while(tc != antlr::nullAST && tc->getType() != sqlite3TokenTypes::RPAREN);
tc = tc->getNextSibling();
tc = tc->getNextSibling(); // REFERENCES
fk->setTable(identifier(tc));
tc = tc->getNextSibling(); // identifier
if(tc != antlr::nullAST && tc->getType() == sqlite3TokenTypes::LPAREN)
{
tc = tc->getNextSibling(); // LPAREN
QStringList fk_cols;
while(tc != antlr::nullAST && tc->getType() != sqlite3TokenTypes::RPAREN)
{
if(tc->getType() != sqlite3TokenTypes::COMMA)
fk_cols.push_back(identifier(tc));
tc = tc->getNextSibling();
}
fk->setColumns(fk_cols);
tc = tc->getNextSibling(); // RPAREN
}
fk->setConstraint(concatTextAST(tc, true));
tab.addConstraint(fields, ConstraintPtr(fk));
}
break;
default:
{
m_bModifySupported = false;
}
break;
}
s = s->getNextSibling(); //COMMA or RPAREN
if(s->getType() == sqlite3TokenTypes::COMMA || s->getType() == sqlite3TokenTypes::RPAREN)
s = s->getNextSibling();
} else {
// It is
s = s->getNextSibling(); // WITHOUT
s = s->getNextSibling(); // ROWID
tab.setRowidColumn(tab.fields().at(tab.findPk())->name());
}
}
}
return tab;
}
void CreateTableWalker::parsecolumn(Table& table, antlr::RefAST c)
{
QString colname;
QString type = "TEXT";
bool autoincrement = false;
bool primarykey = false;
bool notnull = false;
bool unique = false;
QString defaultvalue;
QString check;
sqlb::ForeignKeyClause* foreignKey = 0;
colname = columnname(c);
c = c->getNextSibling(); //type?
if(c != antlr::nullAST && c->getType() == sqlite3TokenTypes::TYPE_NAME)
{
type = concatTextAST(c->getFirstChild());
c = c->getNextSibling();
}
// finished with type parsing
// now columnconstraints
while(c != antlr::nullAST)
{
antlr::RefAST con = c->getFirstChild();
// skip constraint name, if there is any
if(con->getType() == sqlite3TokenTypes::CONSTRAINT)
{
m_bModifySupported = false;
con = con->getNextSibling()->getNextSibling();
}
switch(con->getType())
{
case sqlite3TokenTypes::PRIMARY:
{
primarykey = true;
con = con->getNextSibling()->getNextSibling(); // skip KEY
if(con != antlr::nullAST && (con->getType() == sqlite3TokenTypes::ASC
|| con->getType() == sqlite3TokenTypes::DESC))
{
m_bModifySupported = false;
con = con->getNextSibling(); //skip
}
if(con != antlr::nullAST && con->getType() == sqlite3TokenTypes::AUTOINCREMENT)
autoincrement = true;
}
break;
case sqlite3TokenTypes::NOT:
{
notnull = true;
}
break;
case sqlite3TokenTypes::CHECK:
{
con = con->getNextSibling(); //LPAREN
check = concatTextAST(con, true);
// remove parenthesis
check.remove(check.length()-1, 1);
check.remove(0,1);
check = check.trimmed();
}
break;
case sqlite3TokenTypes::DEFAULT:
{
con = con->getNextSibling(); //SIGNEDNUMBER,STRING,LPAREN
defaultvalue = concatTextAST(con);
}
break;
case sqlite3TokenTypes::UNIQUE:
{
unique = true;
}
break;
case sqlite3TokenTypes::REFERENCES:
{
con = con->getNextSibling(); // REFERENCES
foreignKey = new ForeignKeyClause;
foreignKey->setTable(identifier(con));
con = con->getNextSibling(); // identifier
if(con != antlr::nullAST && con->getType() == sqlite3TokenTypes::LPAREN)
{
con = con->getNextSibling(); // LPAREN
QStringList fk_cols;
while(con != antlr::nullAST && con->getType() != sqlite3TokenTypes::RPAREN)
{
if(con->getType() != sqlite3TokenTypes::COMMA)
fk_cols.push_back(identifier(con));
con = con->getNextSibling();
}
foreignKey->setColumns(fk_cols);
con = con->getNextSibling(); // RPAREN
}
foreignKey->setConstraint(concatTextAST(con, true));
}
break;
default:
{
m_bModifySupported = false;
}
break;
}
c = c->getNextSibling();
}
FieldPtr f = FieldPtr(new Field(colname, type, notnull, defaultvalue, check, unique));
f->setAutoIncrement(autoincrement);
table.addField(f);
if(foreignKey)
table.addConstraint(f, ConstraintPtr(foreignKey));
if(primarykey)
{
FieldVector v;
if(table.constraint(v, Constraint::PrimaryKeyConstraintType))
table.primaryKeyRef().push_back(f);
else
table.addConstraint(f, ConstraintPtr(new PrimaryKeyConstraint()));
}
}
} //namespace sqlb