-
Notifications
You must be signed in to change notification settings - Fork 377
/
build.c
4361 lines (4056 loc) · 125 KB
/
build.c
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This file contains C code routines that are called by the SQLite parser
* when syntax rules are reduced. The routines in this file handle the
* following kinds of SQL syntax:
*
* CREATE TABLE
* DROP TABLE
* CREATE INDEX
* DROP INDEX
* creating ID lists
* BEGIN TRANSACTION
* COMMIT
* ROLLBACK
*/
#include "sqliteInt.h"
#include "vdbeInt.h"
#include "tarantoolInt.h"
#include "box/session.h"
#include "box/identifier.h"
/*
* This routine is called after a single SQL statement has been
* parsed and a VDBE program to execute that statement has been
* prepared. This routine puts the finishing touches on the
* VDBE program and resets the pParse structure for the next
* parse.
*
* Note that if an error occurred, it might be the case that
* no VDBE code was generated.
*/
void
sqlite3FinishCoding(Parse * pParse)
{
sqlite3 *db;
Vdbe *v;
assert(pParse->pToplevel == 0);
db = pParse->db;
if (pParse->nested)
return;
if (db->mallocFailed || pParse->nErr) {
if (pParse->rc == SQLITE_OK)
pParse->rc = SQLITE_ERROR;
return;
}
/* Begin by generating some termination code at the end of the
* vdbe program
*/
v = sqlite3GetVdbe(pParse);
assert(!pParse->isMultiWrite
|| sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
if (v) {
sqlite3VdbeAddOp0(v, OP_Halt);
#if SQLITE_USER_AUTHENTICATION
if (pParse->nTableLock > 0 && db->init.busy == 0) {
sqlite3UserAuthInit(db);
if (db->auth.authLevel < UAUTH_User) {
sqlite3ErrorMsg(pParse,
"user not authenticated");
pParse->rc = SQLITE_AUTH_USER;
return;
}
}
#endif
/* The cookie mask contains one bit for each database file open.
* (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
* set for each database that is used. Generate code to start a
* transaction on each used database and to verify the schema cookie
* on each used database.
*/
if (db->mallocFailed == 0
&& (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
) {
int i;
assert(sqlite3VdbeGetOp(v, 0)->opcode == OP_Init);
sqlite3VdbeJumpHere(v, 0);
Schema *pSchema;
if (DbMaskTest(pParse->cookieMask, 0) != 0) {
pSchema = db->pSchema;
sqlite3VdbeAddOp2(v, OP_Transaction, /* Opcode */
0, /* P1 */
DbMaskTest(pParse->writeMask, 0) /* P2 */
);
if (pParse->initiateTTrans)
sqlite3VdbeAddOp0(v, OP_TTransaction);
if (db->init.busy == 0)
sqlite3VdbeChangeP5(v, 1);
VdbeComment((v, "usesStmtJournal=%d",
pParse->mayAbort
&& pParse->isMultiWrite));
}
/* Code constant expressions that where factored out of inner loops */
if (pParse->pConstExpr) {
ExprList *pEL = pParse->pConstExpr;
pParse->okConstFactor = 0;
for (i = 0; i < pEL->nExpr; i++) {
sqlite3ExprCode(pParse, pEL->a[i].pExpr,
pEL->a[i].u.
iConstExprReg);
}
}
/* Finally, jump back to the beginning of the executable code. */
sqlite3VdbeGoto(v, 1);
}
}
/* Get the VDBE program ready for execution
*/
if (v && pParse->nErr == 0 && !db->mallocFailed) {
assert(pParse->iCacheLevel == 0); /* Disables and re-enables match */
/* A minimum of one cursor is required if autoincrement is used
* See ticket [a696379c1f08866]
*/
if (pParse->pAinc != 0 && pParse->nTab == 0)
pParse->nTab = 1;
sqlite3VdbeMakeReady(v, pParse);
pParse->rc = SQLITE_DONE;
} else {
pParse->rc = SQLITE_ERROR;
}
}
/*
* Run the parser and code generator recursively in order to generate
* code for the SQL statement given onto the end of the pParse context
* currently under construction. When the parser is run recursively
* this way, the final OP_Halt is not appended and other initialization
* and finalization steps are omitted because those are handling by the
* outermost parser.
*
* Not everything is nestable. This facility is designed to perform
* basic DDL operations. Use care if you decide to try to use this routine
* for some other purposes.
*/
void
sqlite3NestedParse(Parse * pParse, const char *zFormat, ...)
{
va_list ap;
char *zSql;
char *zErrMsg = 0;
sqlite3 *db = pParse->db;
char saveBuf[PARSE_TAIL_SZ];
if (pParse->nErr)
return;
assert(pParse->nested < 10); /* Nesting should only be of limited depth */
va_start(ap, zFormat);
zSql = sqlite3VMPrintf(db, zFormat, ap);
va_end(ap);
if (zSql == 0) {
return; /* A malloc must have failed */
}
pParse->nested++;
memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
sqlite3RunParser(pParse, zSql, &zErrMsg);
sqlite3DbFree(db, zErrMsg);
sqlite3DbFree(db, zSql);
memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
pParse->nested--;
}
#if SQLITE_USER_AUTHENTICATION
/*
* Return TRUE if zTable is the name of the system table that stores the
* list of users and their access credentials.
*/
int
sqlite3UserAuthTable(const char *zTable)
{
return sqlite3_stricmp(zTable, "sqlite_user") == 0;
}
#endif
/*
* Locate the in-memory structure that describes a particular database
* table given the name of that table and (optionally) the name of the
* database containing the table. Return NULL if not found.
*
* If zDatabase is 0, all databases are searched for the table and the
* first matching table is returned. (No checking for duplicate table
* names is done.) The search order is TEMP first, then MAIN, then any
* auxiliary databases added using the ATTACH command.
*
* See also sqlite3LocateTable().
*/
Table *
sqlite3FindTable(sqlite3 * db, const char *zName)
{
#if SQLITE_USER_AUTHENTICATION
/* Only the admin user is allowed to know that the sqlite_user table
* exists
*/
if (db->auth.authLevel < UAUTH_Admin
&& sqlite3UserAuthTable(zName) != 0) {
return 0;
}
#endif
return sqlite3HashFind(&db->pSchema->tblHash, zName);
}
/*
* Locate the in-memory structure that describes a particular database
* table given the name of that table. Return NULL if not found.
* Also leave an error message in pParse->zErrMsg.
*
* The difference between this routine and sqlite3FindTable() is that this
* routine leaves an error message in pParse->zErrMsg where
* sqlite3FindTable() does not.
*/
Table *
sqlite3LocateTable(Parse * pParse, /* context in which to report errors */
u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
const char *zName /* Name of the table we are looking for */
)
{
Table *p;
/* Read the database schema. If an error occurs, leave an error message
* and code in pParse and return NULL.
*/
if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
return 0;
}
p = sqlite3FindTable(pParse->db, zName);
if (p == 0) {
const char *zMsg =
flags & LOCATE_VIEW ? "no such view" : "no such table";
if ((flags & LOCATE_NOERR) == 0) {
sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
pParse->checkSchema = 1;
}
}
return p;
}
/*
* Locate the table identified by *p.
*
* This is a wrapper around sqlite3LocateTable(). The difference between
* sqlite3LocateTable() and this function is that this function restricts
* the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
* non-NULL if it is part of a view or trigger program definition. See
* sqlite3FixSrcList() for details.
*/
Table *
sqlite3LocateTableItem(Parse * pParse, u32 flags, struct SrcList_item * p)
{
return sqlite3LocateTable(pParse, flags, p->zName);
}
/*
* Locate the in-memory structure that describes
* a particular index given the name of that index
* and the name of the database that contains the index.
* Return NULL if not found.
*/
Index *
sqlite3FindIndex(MAYBE_UNUSED sqlite3 * db, const char *zName, Table * pTab)
{
assert(pTab);
return sqlite3HashFind(&pTab->idxHash, zName);
}
Index *
sqlite3LocateIndex(sqlite3 * db, const char *zName, const char *zTable)
{
assert(zName);
assert(zTable);
Table *pTab = sqlite3FindTable(db, zTable);
if (pTab == 0) {
return 0;
}
return sqlite3FindIndex(db, zName, pTab);
}
/*
* Reclaim the memory used by an index
*/
static void
freeIndex(sqlite3 * db, Index * p)
{
#ifndef SQLITE_OMIT_ANALYZE
sqlite3DeleteIndexSamples(db, p);
#endif
sqlite3ExprDelete(db, p->pPartIdxWhere);
sqlite3ExprListDelete(db, p->aColExpr);
sqlite3DbFree(db, p->zColAff);
if (p->isResized)
sqlite3DbFree(db, (void *)p->azColl);
sqlite3_free(p->aiRowEst);
sqlite3DbFree(db, p);
}
/*
* For the index called zIdxName which is found in the database,
* unlike that index from its Table then remove the index from
* the index hash table and free all memory structures associated
* with the index.
*/
void
sqlite3UnlinkAndDeleteIndex(sqlite3 * db, Index * pIndex)
{
assert(pIndex != 0);
assert(&pIndex->pTable->idxHash);
struct session *user_session = current_session();
pIndex = sqlite3HashInsert(&pIndex->pTable->idxHash, pIndex->zName, 0);
if (ALWAYS(pIndex)) {
if (pIndex->pTable->pIndex == pIndex) {
pIndex->pTable->pIndex = pIndex->pNext;
} else {
Index *p;
/* Justification of ALWAYS(); The index must be on the list of
* indices.
*/
p = pIndex->pTable->pIndex;
while (ALWAYS(p) && p->pNext != pIndex) {
p = p->pNext;
}
if (ALWAYS(p && p->pNext == pIndex)) {
p->pNext = pIndex->pNext;
}
}
freeIndex(db, pIndex);
}
user_session->sql_flags |= SQLITE_InternChanges;
}
/*
* Reset the schema for the database.
*/
void
sqlite3ResetOneSchema(sqlite3 * db)
{
/* Case 1: Reset the single schema of the database */
assert(db->pSchema != 0);
sqlite3SchemaClear(db);
}
/*
* Erase all schema information from all attached databases (including
* "main" and "temp") for a single database connection.
*/
void
sqlite3ResetAllSchemasOfConnection(sqlite3 * db)
{
struct session *user_session = current_session();
if (db->pSchema) {
sqlite3SchemaClear(db);
}
user_session->sql_flags &= ~SQLITE_InternChanges;
}
/*
* This routine is called when a commit occurs.
*/
void
sqlite3CommitInternalChanges()
{
current_session()->sql_flags &= ~SQLITE_InternChanges;
}
/*
* Delete memory allocated for the column names of a table or view (the
* Table.aCol[] array).
*/
void
sqlite3DeleteColumnNames(sqlite3 * db, Table * pTable)
{
int i;
Column *pCol;
assert(pTable != 0);
if ((pCol = pTable->aCol) != 0) {
for (i = 0; i < pTable->nCol; i++, pCol++) {
sqlite3DbFree(db, pCol->zName);
sqlite3ExprDelete(db, pCol->pDflt);
sqlite3DbFree(db, pCol->zColl);
}
sqlite3DbFree(db, pTable->aCol);
}
}
/*
* Remove the memory data structures associated with the given
* Table. No changes are made to disk by this routine.
*
* This routine just deletes the data structure. It does not unlink
* the table data structure from the hash table. But it does destroy
* memory structures of the indices and foreign keys associated with
* the table.
*
* The db parameter is optional. It is needed if the Table object
* contains lookaside memory. (Table objects in the schema do not use
* lookaside memory, but some ephemeral Table objects do.) Or the
* db parameter can be used with db->pnBytesFreed to measure the memory
* used by the Table object.
*/
static void SQLITE_NOINLINE
deleteTable(sqlite3 * db, Table * pTable)
{
Index *pIndex, *pNext;
TESTONLY(int nLookaside;
)
/* Used to verify lookaside not used for schema */
/* Record the number of outstanding lookaside allocations in schema Tables
* prior to doing any free() operations. Since schema Tables do not use
* lookaside, this number should not change.
*/
TESTONLY(nLookaside =
(db
&& (pTable->tabFlags & TF_Ephemeral) ==
0) ? db->lookaside.nOut : 0);
/* Delete all indices associated with this table. */
for (pIndex = pTable->pIndex; pIndex; pIndex = pNext) {
pNext = pIndex->pNext;
assert(pIndex->pSchema == pTable->pSchema);
if ((db == 0 || db->pnBytesFreed == 0)) {
char *zName = pIndex->zName;
TESTONLY(Index *
pOld =) sqlite3HashInsert(&pTable->idxHash,
zName, 0);
assert(pOld == pIndex || pOld == 0);
}
freeIndex(db, pIndex);
}
/* Delete any foreign keys attached to this table. */
sqlite3FkDelete(db, pTable);
/* Delete the Table structure itself.
*/
sqlite3HashClear(&pTable->idxHash);
sqlite3DeleteColumnNames(db, pTable);
sqlite3DbFree(db, pTable->zName);
sqlite3DbFree(db, pTable->zColAff);
sqlite3SelectDelete(db, pTable->pSelect);
sqlite3ExprListDelete(db, pTable->pCheck);
sqlite3DbFree(db, pTable);
/* Verify that no lookaside memory was used by schema tables */
assert(nLookaside == 0 || nLookaside == db->lookaside.nOut);
}
void
sqlite3DeleteTable(sqlite3 * db, Table * pTable)
{
/* Do not delete the table until the reference count reaches zero. */
if (!pTable)
return;
if (((!db || db->pnBytesFreed == 0) && (--pTable->nTabRef) > 0))
return;
deleteTable(db, pTable);
}
/*
* Unlink the given table from the hash tables and the delete the
* table structure with all its indices and foreign keys.
*/
void
sqlite3UnlinkAndDeleteTable(sqlite3 * db, const char *zTabName)
{
Table *p;
assert(db != 0);
assert(zTabName);
testcase(zTabName[0] == 0); /* Zero-length table names are allowed */
p = sqlite3HashInsert(&db->pSchema->tblHash, zTabName, 0);
sqlite3DeleteTable(db, p);
}
/*
* Given a token, return a string that consists of the text of that
* token. Space to hold the returned string
* is obtained from sqliteMalloc() and must be freed by the calling
* function.
*
* Any quotation marks (ex: "name", 'name', [name], or `name`) that
* surround the body of the token are removed.
*
* Tokens are often just pointers into the original SQL text and so
* are not \000 terminated and are not persistent. The returned string
* is \000 terminated and is persistent.
*/
char *
sqlite3NameFromToken(sqlite3 * db, Token * pName)
{
char *zName;
if (pName) {
zName = sqlite3DbStrNDup(db, (char *)pName->z, pName->n);
sqlite3NormalizeName(zName);
} else {
zName = 0;
}
return zName;
}
/*
* Parameter zName points to a nul-terminated buffer containing the name
* of a database ("main", "temp" or the name of an attached db). This
* function returns the index of the named database in db->aDb[], or
* -1 if the named db cannot be found.
*/
int
sqlite3FindDbName(const char *zName MAYBE_UNUSED)
{
assert(0 == sqlite3_stricmp("main", zName));
return 0;
}
/*
* The token *pName contains the name of a database (either "main" or
* "temp" or the name of an attached db). This routine returns the
* index of the named database in db->aDb[], or -1 if the named db
* does not exist.
*/
int
sqlite3FindDb(sqlite3 * db, Token * pName)
{
int i; /* Database number */
char *zName; /* Name we are searching for */
zName = sqlite3NameFromToken(db, pName);
i = sqlite3FindDbName(zName);
sqlite3DbFree(db, zName);
return i;
}
/*
* This routine is used to check if the UTF-8 string zName is a legal
* unqualified name for an identifier.
* Some objects may not be checked, because they are validated in Tarantool.
* (e.g. table, index, column name of a real table)
* All names are legal except those that cantain non-printable
* characters or have length greater than BOX_NAME_MAX.
*/
int
sqlite3CheckIdentifierName(Parse *pParse, char *zName)
{
ssize_t len = strlen(zName);
if (len > BOX_NAME_MAX || identifier_check(zName, len) != 0) {
sqlite3ErrorMsg(pParse,
"identifier name is invalid: %s",
zName);
return SQLITE_ERROR;
}
return SQLITE_OK;
}
/*
* Return the PRIMARY KEY index of a table
*/
Index *
sqlite3PrimaryKeyIndex(Table * pTab)
{
Index *p;
for (p = pTab->pIndex; p && !IsPrimaryKeyIndex(p); p = p->pNext) {
}
return p;
}
/*
* Return the column of index pIdx that corresponds to table
* column iCol. Return -1 if not found.
*/
i16
sqlite3ColumnOfIndex(Index * pIdx, i16 iCol)
{
/* TARANTOOL: Data layout is the same in every index. */
(void) pIdx;
return iCol;
}
/*
* Begin constructing a new table representation in memory. This is
* the first of several action routines that get called in response
* to a CREATE TABLE statement. In particular, this routine is called
* after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
* flag is true if the table should be stored in the auxiliary database
* file instead of in the main database file. This is normally the case
* when the "TEMP" or "TEMPORARY" keyword occurs in between
* CREATE and TABLE.
*
* The new table record is initialized and put in pParse->pNewTable.
* As more of the CREATE TABLE statement is parsed, additional action
* routines will be called to add more information to this record.
* At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
* is called to complete the construction of the new table record.
*
* @param pParse Parser context.
* @param pName1 First part of the name of the table or view.
* @param noErr Do nothing if table already exists.
*/
void
sqlite3StartTable(Parse *pParse, Token *pName, int noErr)
{
Table *pTable;
char *zName = 0; /* The name of the new table */
sqlite3 *db = pParse->db;
Vdbe *v;
/* Do not account nested operations: the count of such
* operations depends on Tarantool data dictionary internals,
* such as data layout in system spaces.
*/
if (!pParse->nested) {
if ((v = sqlite3GetVdbe(pParse)) == NULL)
goto begin_table_error;
sqlite3VdbeCountChanges(v);
}
zName = sqlite3NameFromToken(db, pName);
pParse->sNameToken = *pName;
if (zName == 0)
return;
#ifndef SQLITE_OMIT_AUTHORIZATION
assert(isTemp == 0 || isTemp == 1);
assert(isView == 0 || (isView == 1 && isTemp == 0));
{
static const u8 aCode[] = {
SQLITE_CREATE_TABLE,
SQLITE_CREATE_TEMP_TABLE,
SQLITE_CREATE_VIEW
};
char *zDb = db->mdb.zDbSName;
if (sqlite3AuthCheck
(pParse, SQLITE_INSERT, MASTER_NAME, 0, zDb)) {
goto begin_table_error;
}
if (sqlite3AuthCheck(pParse, (int)aCode[isTemp + 2 * isView],
zName, 0, zDb)) {
goto begin_table_error;
}
}
#endif
/*
* Make sure the new table name does not collide with an
* existing index or table name in the same database.
* Issue an error message if it does.
*/
if (SQLITE_OK != sqlite3ReadSchema(pParse))
goto begin_table_error;
pTable = sqlite3FindTable(db, zName);
if (pTable) {
if (!noErr) {
sqlite3ErrorMsg(pParse,
"table %s already exists",
zName);
} else {
assert(!db->init.busy || CORRUPT_DB);
sqlite3CodeVerifySchema(pParse);
}
goto begin_table_error;
}
pTable = sqlite3DbMallocZero(db, sizeof(Table));
if (pTable == 0) {
assert(db->mallocFailed);
pParse->rc = SQLITE_NOMEM_BKPT;
pParse->nErr++;
goto begin_table_error;
}
pTable->zName = zName;
pTable->iPKey = -1;
pTable->iAutoIncPKey = -1;
pTable->pSchema = db->pSchema;
sqlite3HashInit(&pTable->idxHash);
pTable->nTabRef = 1;
pTable->nRowLogEst = 200;
assert(200 == sqlite3LogEst(1048576));
assert(pParse->pNewTable == 0);
pParse->pNewTable = pTable;
/* Begin generating the code that will create a new table.
* Note in particular that we must go ahead and allocate the
* record number for the table entry now. Before any
* PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
* indices to be created and the table record must come before the
* indices. Hence, the record number for the table must be allocated
* now.
*/
if (!db->init.busy && (v = sqlite3GetVdbe(pParse)) != 0)
sqlite3BeginWriteOperation(pParse, 1);
/* Normal (non-error) return. */
return;
/* If an error occurs, we jump here */
begin_table_error:
sqlite3DbFree(db, zName);
return;
}
/* Set properties of a table column based on the (magical)
* name of the column.
*/
#if SQLITE_ENABLE_HIDDEN_COLUMNS
void
sqlite3ColumnPropertiesFromName(Table * pTab, Column * pCol)
{
if (sqlite3_strnicmp(pCol->zName, "__hidden__", 10) == 0) {
pCol->colFlags |= COLFLAG_HIDDEN;
} else if (pTab && pCol != pTab->aCol
&& (pCol[-1].colFlags & COLFLAG_HIDDEN)) {
pTab->tabFlags |= TF_OOOHidden;
}
}
#endif
/*
* Add a new column to the table currently being constructed.
*
* The parser calls this routine once for each column declaration
* in a CREATE TABLE statement. sqlite3StartTable() gets called
* first to get things going. Then this routine is called for each
* column.
*/
void
sqlite3AddColumn(Parse * pParse, Token * pName, Token * pType)
{
Table *p;
int i;
char *z;
char *zType;
Column *pCol;
sqlite3 *db = pParse->db;
if ((p = pParse->pNewTable) == 0)
return;
#if SQLITE_MAX_COLUMN
if (p->nCol + 1 > db->aLimit[SQLITE_LIMIT_COLUMN]) {
sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
return;
}
#endif
z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
if (z == 0)
return;
memcpy(z, pName->z, pName->n);
z[pName->n] = 0;
sqlite3NormalizeName(z);
for (i = 0; i < p->nCol; i++) {
if (strcmp(z, p->aCol[i].zName) == 0) {
sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
sqlite3DbFree(db, z);
return;
}
}
if ((p->nCol & 0x7) == 0) {
Column *aNew;
aNew =
sqlite3DbRealloc(db, p->aCol,
(p->nCol + 8) * sizeof(p->aCol[0]));
if (aNew == 0) {
sqlite3DbFree(db, z);
return;
}
p->aCol = aNew;
}
pCol = &p->aCol[p->nCol];
memset(pCol, 0, sizeof(p->aCol[0]));
pCol->zName = z;
sqlite3ColumnPropertiesFromName(p, pCol);
if (pType->n == 0) {
/* If there is no type specified, columns have the default affinity
* 'BLOB'.
*/
pCol->affinity = SQLITE_AFF_BLOB;
pCol->szEst = 1;
} else {
zType = z + sqlite3Strlen30(z) + 1;
memcpy(zType, pType->z, pType->n);
zType[pType->n] = 0;
sqlite3Dequote(zType);
pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
pCol->colFlags |= COLFLAG_HASTYPE;
}
p->nCol++;
pParse->constraintName.n = 0;
}
/*
* This routine is called by the parser while in the middle of
* parsing a CREATE TABLE statement. A "NOT NULL" constraint has
* been seen on a column. This routine sets the notNull flag on
* the column currently under construction.
*/
void
sqlite3AddNotNull(Parse * pParse, int onError)
{
Table *p;
p = pParse->pNewTable;
if (p == 0 || NEVER(p->nCol < 1))
return;
p->aCol[p->nCol - 1].notNull = (u8) onError;
}
/*
* Scan the column type name zType (length nType) and return the
* associated affinity type.
*
* This routine does a case-independent search of zType for the
* substrings in the following table. If one of the substrings is
* found, the corresponding affinity is returned. If zType contains
* more than one of the substrings, entries toward the top of
* the table take priority. For example, if zType is 'BLOBINT',
* SQLITE_AFF_INTEGER is returned.
*
* Substring | Affinity
* --------------------------------
* 'INT' | SQLITE_AFF_INTEGER
* 'CHAR' | SQLITE_AFF_TEXT
* 'CLOB' | SQLITE_AFF_TEXT
* 'TEXT' | SQLITE_AFF_TEXT
* 'BLOB' | SQLITE_AFF_BLOB
* 'REAL' | SQLITE_AFF_REAL
* 'FLOA' | SQLITE_AFF_REAL
* 'DOUB' | SQLITE_AFF_REAL
*
* If none of the substrings in the above table are found,
* SQLITE_AFF_NUMERIC is returned.
*/
char
sqlite3AffinityType(const char *zIn, u8 * pszEst)
{
u32 h = 0;
char aff = SQLITE_AFF_NUMERIC;
const char *zChar = 0;
assert(zIn != 0);
while (zIn[0]) {
h = (h << 8) + sqlite3UpperToLower[(*zIn) & 0xff];
zIn++;
if (h == (('c' << 24) + ('h' << 16) + ('a' << 8) + 'r')) { /* CHAR */
aff = SQLITE_AFF_TEXT;
zChar = zIn;
} else if (h == (('c' << 24) + ('l' << 16) + ('o' << 8) + 'b')) { /* CLOB */
aff = SQLITE_AFF_TEXT;
} else if (h == (('t' << 24) + ('e' << 16) + ('x' << 8) + 't')) { /* TEXT */
aff = SQLITE_AFF_TEXT;
} else if (h == (('b' << 24) + ('l' << 16) + ('o' << 8) + 'b') /* BLOB */
&&(aff == SQLITE_AFF_NUMERIC
|| aff == SQLITE_AFF_REAL)) {
aff = SQLITE_AFF_BLOB;
if (zIn[0] == '(')
zChar = zIn;
#ifndef SQLITE_OMIT_FLOATING_POINT
} else if (h == (('r' << 24) + ('e' << 16) + ('a' << 8) + 'l') /* REAL */
&&aff == SQLITE_AFF_NUMERIC) {
aff = SQLITE_AFF_REAL;
} else if (h == (('f' << 24) + ('l' << 16) + ('o' << 8) + 'a') /* FLOA */
&&aff == SQLITE_AFF_NUMERIC) {
aff = SQLITE_AFF_REAL;
} else if (h == (('d' << 24) + ('o' << 16) + ('u' << 8) + 'b') /* DOUB */
&&aff == SQLITE_AFF_NUMERIC) {
aff = SQLITE_AFF_REAL;
#endif
} else if ((h & 0x00FFFFFF) == (('i' << 16) + ('n' << 8) + 't')) { /* INT */
aff = SQLITE_AFF_INTEGER;
break;
}
}
/* If pszEst is not NULL, store an estimate of the field size. The
* estimate is scaled so that the size of an integer is 1.
*/
if (pszEst) {
*pszEst = 1; /* default size is approx 4 bytes
*/
if (aff < SQLITE_AFF_NUMERIC) {
if (zChar) {
while (zChar[0]) {
if (sqlite3Isdigit(zChar[0])) {
int v = 0;
sqlite3GetInt32(zChar, &v);
v = v / 4 + 1;
if (v > 255)
v = 255;
*pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1)
*/
break;
}
zChar++;
}
} else {
*pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)
*/
}
}
}
return aff;
}
/*
* The expression is the default value for the most recently added column
* of the table currently under construction.
*
* Default value expressions must be constant. Raise an exception if this
* is not the case.
*
* This routine is called by the parser while in the middle of
* parsing a CREATE TABLE statement.
*/
void
sqlite3AddDefaultValue(Parse * pParse, ExprSpan * pSpan)
{
Table *p;
Column *pCol;
sqlite3 *db = pParse->db;
p = pParse->pNewTable;
if (p != 0) {
pCol = &(p->aCol[p->nCol - 1]);
if (!sqlite3ExprIsConstantOrFunction
(pSpan->pExpr, db->init.busy)) {
sqlite3ErrorMsg(pParse,
"default value of column [%s] is not constant",
pCol->zName);
} else {
/* A copy of pExpr is used instead of the original, as pExpr contains
* tokens that point to volatile memory. The 'span' of the expression
* is required by pragma table_info.
*/
Expr x;
sqlite3ExprDelete(db, pCol->pDflt);
memset(&x, 0, sizeof(x));
x.op = TK_SPAN;
x.u.zToken = sqlite3DbStrNDup(db, (char *)pSpan->zStart,
(int)(pSpan->zEnd -
pSpan->zStart));
x.pLeft = pSpan->pExpr;
x.flags = EP_Skip;
pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
sqlite3DbFree(db, x.u.zToken);
}
}
sqlite3ExprDelete(db, pSpan->pExpr);
}
/*
* Designate the PRIMARY KEY for the table. pList is a list of names
* of columns that form the primary key. If pList is NULL, then the
* most recently added column of the table is the primary key.
*
* A table can have at most one primary key. If the table already has
* a primary key (and this is the second primary key) then create an
* error.
*
* Set the Table.iPKey field of the table under construction to be the