-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.c
2156 lines (2043 loc) · 65.6 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
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** 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
** PRAGMA
**
** $Id: build.c,v 1.1.1.1 2004/08/08 15:03:57 matt Exp $
*/
#include "sqliteInt.h"
#include <ctype.h>
/*
** This routine is called when a new SQL statement is beginning to
** be parsed. Check to see if the schema for the database needs
** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
** If it does, then read it.
*/
void sqliteBeginParse(Parse *pParse, int explainFlag){
sqlite *db = pParse->db;
int i;
pParse->explain = explainFlag;
if((db->flags & SQLITE_Initialized)==0 && db->init.busy==0 ){
int rc = sqliteInit(db, &pParse->zErrMsg);
if( rc!=SQLITE_OK ){
pParse->rc = rc;
pParse->nErr++;
}
}
for(i=0; i<db->nDb; i++){
DbClearProperty(db, i, DB_Locked);
if( !db->aDb[i].inTrans ){
DbClearProperty(db, i, DB_Cookie);
}
}
pParse->nVar = 0;
}
/*
** This routine is called after a single SQL statement has been
** parsed and we want to execute the VDBE code to implement
** that statement. Prior action routines should have already
** constructed VDBE code to do the work of the SQL statement.
** This routine just has to execute the VDBE code.
**
** Note that if an error occurred, it might be the case that
** no VDBE code was generated.
*/
void sqliteExec(Parse *pParse){
sqlite *db = pParse->db;
Vdbe *v = pParse->pVdbe;
if( v==0 && (v = sqliteGetVdbe(pParse))!=0 ){
sqliteVdbeAddOp(v, OP_Halt, 0, 0);
}
if( sqlite_malloc_failed ) return;
if( v && pParse->nErr==0 ){
FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
sqliteVdbeTrace(v, trace);
sqliteVdbeMakeReady(v, pParse->nVar, pParse->explain);
pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
pParse->colNamesSet = 0;
}else if( pParse->rc==SQLITE_OK ){
pParse->rc = SQLITE_ERROR;
}
pParse->nTab = 0;
pParse->nMem = 0;
pParse->nSet = 0;
pParse->nAgg = 0;
pParse->nVar = 0;
}
/*
** 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 sqliteLocateTable().
*/
Table *sqliteFindTable(sqlite *db, const char *zName, const char *zDatabase){
Table *p = 0;
int i;
for(i=0; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
if( zDatabase!=0 && sqliteStrICmp(zDatabase, db->aDb[j].zName) ) continue;
p = sqliteHashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
if( p ) break;
}
return p;
}
/*
** 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.
** Also leave an error message in pParse->zErrMsg.
**
** The difference between this routine and sqliteFindTable()
** is that this routine leaves an error message in pParse->zErrMsg
** where sqliteFindTable() does not.
*/
Table *sqliteLocateTable(Parse *pParse, const char *zName, const char *zDbase){
Table *p;
p = sqliteFindTable(pParse->db, zName, zDbase);
if( p==0 ){
if( zDbase ){
sqliteErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
}else if( sqliteFindTable(pParse->db, zName, 0)!=0 ){
sqliteErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
zName, zDbase);
}else{
sqliteErrorMsg(pParse, "no such table: %s", zName);
}
}
return p;
}
/*
** 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.
**
** If zDatabase is 0, all databases are searched for the
** table and the first matching index is returned. (No checking
** for duplicate index names is done.) The search order is
** TEMP first, then MAIN, then any auxiliary databases added
** using the ATTACH command.
*/
Index *sqliteFindIndex(sqlite *db, const char *zName, const char *zDb){
Index *p = 0;
int i;
for(i=0; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
if( zDb && sqliteStrICmp(zDb, db->aDb[j].zName) ) continue;
p = sqliteHashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
if( p ) break;
}
return p;
}
/*
** Remove the given index from the index hash table, and free
** its memory structures.
**
** The index is removed from the database hash tables but
** it is not unlinked from the Table that it indexes.
** Unlinking from the Table must be done by the calling function.
*/
static void sqliteDeleteIndex(sqlite *db, Index *p){
Index *pOld;
assert( db!=0 && p->zName!=0 );
pOld = sqliteHashInsert(&db->aDb[p->iDb].idxHash, p->zName,
strlen(p->zName)+1, 0);
if( pOld!=0 && pOld!=p ){
sqliteHashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
strlen(pOld->zName)+1, pOld);
}
sqliteFree(p);
}
/*
** Unlink the given index from its table, then remove
** the index from the index hash table and free its memory
** structures.
*/
void sqliteUnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
if( pIndex->pTable->pIndex==pIndex ){
pIndex->pTable->pIndex = pIndex->pNext;
}else{
Index *p;
for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
if( p && p->pNext==pIndex ){
p->pNext = pIndex->pNext;
}
}
sqliteDeleteIndex(db, pIndex);
}
/*
** Erase all schema information from the in-memory hash tables of
** database connection. This routine is called to reclaim memory
** before the connection closes. It is also called during a rollback
** if there were schema changes during the transaction.
**
** If iDb<=0 then reset the internal schema tables for all database
** files. If iDb>=2 then reset the internal schema for only the
** single file indicated.
*/
void sqliteResetInternalSchema(sqlite *db, int iDb){
HashElem *pElem;
Hash temp1;
Hash temp2;
int i, j;
assert( iDb>=0 && iDb<db->nDb );
db->flags &= ~SQLITE_Initialized;
for(i=iDb; i<db->nDb; i++){
Db *pDb = &db->aDb[i];
temp1 = pDb->tblHash;
temp2 = pDb->trigHash;
sqliteHashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
sqliteHashClear(&pDb->aFKey);
sqliteHashClear(&pDb->idxHash);
for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
Trigger *pTrigger = sqliteHashData(pElem);
sqliteDeleteTrigger(pTrigger);
}
sqliteHashClear(&temp2);
sqliteHashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
Table *pTab = sqliteHashData(pElem);
sqliteDeleteTable(db, pTab);
}
sqliteHashClear(&temp1);
DbClearProperty(db, i, DB_SchemaLoaded);
if( iDb>0 ) return;
}
assert( iDb==0 );
db->flags &= ~SQLITE_InternChanges;
/* If one or more of the auxiliary database files has been closed,
** then remove then from the auxiliary database list. We take the
** opportunity to do this here since we have just deleted all of the
** schema hash tables and therefore do not have to make any changes
** to any of those tables.
*/
for(i=0; i<db->nDb; i++){
struct Db *pDb = &db->aDb[i];
if( pDb->pBt==0 ){
if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
pDb->pAux = 0;
}
}
for(i=j=2; i<db->nDb; i++){
struct Db *pDb = &db->aDb[i];
if( pDb->pBt==0 ){
sqliteFree(pDb->zName);
pDb->zName = 0;
continue;
}
if( j<i ){
db->aDb[j] = db->aDb[i];
}
j++;
}
memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
db->nDb = j;
if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
sqliteFree(db->aDb);
db->aDb = db->aDbStatic;
}
}
/*
** This routine is called whenever a rollback occurs. If there were
** schema changes during the transaction, then we have to reset the
** internal hash tables and reload them from disk.
*/
void sqliteRollbackInternalChanges(sqlite *db){
if( db->flags & SQLITE_InternChanges ){
sqliteResetInternalSchema(db, 0);
}
}
/*
** This routine is called when a commit occurs.
*/
void sqliteCommitInternalChanges(sqlite *db){
db->aDb[0].schema_cookie = db->next_cookie;
db->flags &= ~SQLITE_InternChanges;
}
/*
** 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. Nor does it remove
** foreign keys from the sqlite.aFKey hash table. But it does destroy
** memory structures of the indices and foreign keys associated with
** the table.
**
** Indices associated with the table are unlinked from the "db"
** data structure if db!=NULL. If db==NULL, indices attached to
** the table are deleted, but it is assumed they have already been
** unlinked.
*/
void sqliteDeleteTable(sqlite *db, Table *pTable){
int i;
Index *pIndex, *pNext;
FKey *pFKey, *pNextFKey;
if( pTable==0 ) return;
/* Delete all indices associated with this table
*/
for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
pNext = pIndex->pNext;
assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
sqliteDeleteIndex(db, pIndex);
}
/* Delete all foreign keys associated with this table. The keys
** should have already been unlinked from the db->aFKey hash table
*/
for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
pNextFKey = pFKey->pNextFrom;
assert( pTable->iDb<db->nDb );
assert( sqliteHashFind(&db->aDb[pTable->iDb].aFKey,
pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
sqliteFree(pFKey);
}
/* Delete the Table structure itself.
*/
for(i=0; i<pTable->nCol; i++){
sqliteFree(pTable->aCol[i].zName);
sqliteFree(pTable->aCol[i].zDflt);
sqliteFree(pTable->aCol[i].zType);
}
sqliteFree(pTable->zName);
sqliteFree(pTable->aCol);
sqliteSelectDelete(pTable->pSelect);
sqliteFree(pTable);
}
/*
** Unlink the given table from the hash tables and the delete the
** table structure with all its indices and foreign keys.
*/
static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
Table *pOld;
FKey *pF1, *pF2;
int i = p->iDb;
assert( db!=0 );
pOld = sqliteHashInsert(&db->aDb[i].tblHash, p->zName, strlen(p->zName)+1, 0);
assert( pOld==0 || pOld==p );
for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
int nTo = strlen(pF1->zTo) + 1;
pF2 = sqliteHashFind(&db->aDb[i].aFKey, pF1->zTo, nTo);
if( pF2==pF1 ){
sqliteHashInsert(&db->aDb[i].aFKey, pF1->zTo, nTo, pF1->pNextTo);
}else{
while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
if( pF2 ){
pF2->pNextTo = pF1->pNextTo;
}
}
}
sqliteDeleteTable(db, p);
}
/*
** Construct the name of a user table or index from a token.
**
** Space to hold the name is obtained from sqliteMalloc() and must
** be freed by the calling function.
*/
char *sqliteTableNameFromToken(Token *pName){
char *zName = sqliteStrNDup(pName->z, pName->n);
sqliteDequote(zName);
return zName;
}
/*
** Generate code to open the appropriate master table. The table
** opened will be SQLITE_MASTER for persistent tables and
** SQLITE_TEMP_MASTER for temporary tables. The table is opened
** on cursor 0.
*/
void sqliteOpenMasterTable(Vdbe *v, int isTemp){
sqliteVdbeAddOp(v, OP_Integer, isTemp, 0);
sqliteVdbeAddOp(v, OP_OpenWrite, 0, 2);
}
/*
** 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
** pStart token is the CREATE and pName is 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 sqliteEndTable() routine
** is called to complete the construction of the new table record.
*/
void sqliteStartTable(
Parse *pParse, /* Parser context */
Token *pStart, /* The "CREATE" token */
Token *pName, /* Name of table or view to create */
int isTemp, /* True if this is a TEMP table */
int isView /* True if this is a VIEW */
){
Table *pTable;
Index *pIdx;
char *zName;
sqlite *db = pParse->db;
Vdbe *v;
int iDb;
pParse->sFirstToken = *pStart;
zName = sqliteTableNameFromToken(pName);
if( zName==0 ) return;
if( db->init.iDb==1 ) isTemp = 1;
#ifndef SQLITE_OMIT_AUTHORIZATION
assert( (isTemp & 1)==isTemp );
{
int code;
char *zDb = isTemp ? "temp" : "main";
if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
sqliteFree(zName);
return;
}
if( isView ){
if( isTemp ){
code = SQLITE_CREATE_TEMP_VIEW;
}else{
code = SQLITE_CREATE_VIEW;
}
}else{
if( isTemp ){
code = SQLITE_CREATE_TEMP_TABLE;
}else{
code = SQLITE_CREATE_TABLE;
}
}
if( sqliteAuthCheck(pParse, code, zName, 0, zDb) ){
sqliteFree(zName);
return;
}
}
#endif
/* Before trying to create a temporary table, make sure the Btree for
** holding temporary tables is open.
*/
if( isTemp && db->aDb[1].pBt==0 && !pParse->explain ){
int rc = sqliteBtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
if( rc!=SQLITE_OK ){
sqliteErrorMsg(pParse, "unable to open a temporary database "
"file for storing temporary tables");
pParse->nErr++;
return;
}
if( db->flags & SQLITE_InTrans ){
rc = sqliteBtreeBeginTrans(db->aDb[1].pBt);
if( rc!=SQLITE_OK ){
sqliteErrorMsg(pParse, "unable to get a write lock on "
"the temporary database file");
return;
}
}
}
/* Make sure the new table name does not collide with an existing
** index or table name. Issue an error message if it does.
**
** If we are re-reading the sqlite_master table because of a schema
** change and a new permanent table is found whose name collides with
** an existing temporary table, that is not an error.
*/
pTable = sqliteFindTable(db, zName, 0);
iDb = isTemp ? 1 : db->init.iDb;
if( pTable!=0 && (pTable->iDb==iDb || !db->init.busy) ){
sqliteErrorMsg(pParse, "table %T already exists", pName);
sqliteFree(zName);
return;
}
if( (pIdx = sqliteFindIndex(db, zName, 0))!=0 &&
(pIdx->iDb==0 || !db->init.busy) ){
sqliteErrorMsg(pParse, "there is already an index named %s", zName);
sqliteFree(zName);
return;
}
pTable = sqliteMalloc( sizeof(Table) );
if( pTable==0 ){
sqliteFree(zName);
return;
}
pTable->zName = zName;
pTable->nCol = 0;
pTable->aCol = 0;
pTable->iPKey = -1;
pTable->pIndex = 0;
pTable->iDb = iDb;
if( pParse->pNewTable ) sqliteDeleteTable(db, pParse->pNewTable);
pParse->pNewTable = pTable;
/* Begin generating the code that will insert the table record into
** the SQLITE_MASTER 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 = sqliteGetVdbe(pParse))!=0 ){
sqliteBeginWriteOperation(pParse, 0, isTemp);
if( !isTemp ){
sqliteVdbeAddOp(v, OP_Integer, db->file_format, 0);
sqliteVdbeAddOp(v, OP_SetCookie, 0, 1);
}
sqliteOpenMasterTable(v, isTemp);
sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
sqliteVdbeAddOp(v, OP_Dup, 0, 0);
sqliteVdbeAddOp(v, OP_String, 0, 0);
sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
}
}
/*
** 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. sqliteStartTable() gets called
** first to get things going. Then this routine is called for each
** column.
*/
void sqliteAddColumn(Parse *pParse, Token *pName){
Table *p;
int i;
char *z = 0;
Column *pCol;
if( (p = pParse->pNewTable)==0 ) return;
sqliteSetNString(&z, pName->z, pName->n, 0);
if( z==0 ) return;
sqliteDequote(z);
for(i=0; i<p->nCol; i++){
if( sqliteStrICmp(z, p->aCol[i].zName)==0 ){
sqliteErrorMsg(pParse, "duplicate column name: %s", z);
sqliteFree(z);
return;
}
}
if( (p->nCol & 0x7)==0 ){
Column *aNew;
aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
if( aNew==0 ) return;
p->aCol = aNew;
}
pCol = &p->aCol[p->nCol];
memset(pCol, 0, sizeof(p->aCol[0]));
pCol->zName = z;
pCol->sortOrder = SQLITE_SO_NUM;
p->nCol++;
}
/*
** 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 sqliteAddNotNull(Parse *pParse, int onError){
Table *p;
int i;
if( (p = pParse->pNewTable)==0 ) return;
i = p->nCol-1;
if( i>=0 ) p->aCol[i].notNull = onError;
}
/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement. The pFirst token is the first
** token in the sequence of tokens that describe the type of the
** column currently under construction. pLast is the last token
** in the sequence. Use this information to construct a string
** that contains the typename of the column and store that string
** in zType.
*/
void sqliteAddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
Table *p;
int i, j;
int n;
char *z, **pz;
Column *pCol;
if( (p = pParse->pNewTable)==0 ) return;
i = p->nCol-1;
if( i<0 ) return;
pCol = &p->aCol[i];
pz = &pCol->zType;
n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
sqliteSetNString(pz, pFirst->z, n, 0);
z = *pz;
if( z==0 ) return;
for(i=j=0; z[i]; i++){
int c = z[i];
if( isspace(c) ) continue;
z[j++] = c;
}
z[j] = 0;
if( pParse->db->file_format>=4 ){
pCol->sortOrder = sqliteCollateType(z, n);
}else{
pCol->sortOrder = SQLITE_SO_NUM;
}
}
/*
** The given token is the default value for the last column added to
** the table currently under construction. If "minusFlag" is true, it
** means the value token was preceded by a minus sign.
**
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.
*/
void sqliteAddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
Table *p;
int i;
char **pz;
if( (p = pParse->pNewTable)==0 ) return;
i = p->nCol-1;
if( i<0 ) return;
pz = &p->aCol[i].zDflt;
if( minusFlag ){
sqliteSetNString(pz, "-", 1, pVal->z, pVal->n, 0);
}else{
sqliteSetNString(pz, pVal->z, pVal->n, 0);
}
sqliteDequote(*pz);
}
/*
** 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.
**
** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
** then we will try to use that column as the row id. (Exception:
** For backwards compatibility with older databases, do not do this
** if the file format version number is less than 1.) Set the Table.iPKey
** field of the table under construction to be the index of the
** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
** no INTEGER PRIMARY KEY.
**
** If the key is not an INTEGER PRIMARY KEY, then create a unique
** index for the key. No index is created for INTEGER PRIMARY KEYs.
*/
void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){
Table *pTab = pParse->pNewTable;
char *zType = 0;
int iCol = -1, i;
if( pTab==0 ) goto primary_key_exit;
if( pTab->hasPrimKey ){
sqliteErrorMsg(pParse,
"table \"%s\" has more than one primary key", pTab->zName);
goto primary_key_exit;
}
pTab->hasPrimKey = 1;
if( pList==0 ){
iCol = pTab->nCol - 1;
pTab->aCol[iCol].isPrimKey = 1;
}else{
for(i=0; i<pList->nId; i++){
for(iCol=0; iCol<pTab->nCol; iCol++){
if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ) break;
}
if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
}
if( pList->nId>1 ) iCol = -1;
}
if( iCol>=0 && iCol<pTab->nCol ){
zType = pTab->aCol[iCol].zType;
}
if( pParse->db->file_format>=1 &&
zType && sqliteStrICmp(zType, "INTEGER")==0 ){
pTab->iPKey = iCol;
pTab->keyConf = onError;
}else{
sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0);
pList = 0;
}
primary_key_exit:
sqliteIdListDelete(pList);
return;
}
/*
** Return the appropriate collating type given a type name.
**
** The collation type is text (SQLITE_SO_TEXT) if the type
** name contains the character stream "text" or "blob" or
** "clob". Any other type name is collated as numeric
** (SQLITE_SO_NUM).
*/
int sqliteCollateType(const char *zType, int nType){
int i;
for(i=0; i<nType-3; i++){
int c = *(zType++) | 0x60;
if( (c=='b' || c=='c') && sqliteStrNICmp(zType, "lob", 3)==0 ){
return SQLITE_SO_TEXT;
}
if( c=='c' && sqliteStrNICmp(zType, "har", 3)==0 ){
return SQLITE_SO_TEXT;
}
if( c=='t' && sqliteStrNICmp(zType, "ext", 3)==0 ){
return SQLITE_SO_TEXT;
}
}
return SQLITE_SO_NUM;
}
/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement. A "COLLATE" clause has
** been seen on a column. This routine sets the Column.sortOrder on
** the column currently under construction.
*/
void sqliteAddCollateType(Parse *pParse, int collType){
Table *p;
int i;
if( (p = pParse->pNewTable)==0 ) return;
i = p->nCol-1;
if( i>=0 ) p->aCol[i].sortOrder = collType;
}
/*
** Come up with a new random value for the schema cookie. Make sure
** the new value is different from the old.
**
** The schema cookie is used to determine when the schema for the
** database changes. After each schema change, the cookie value
** changes. When a process first reads the schema it records the
** cookie. Thereafter, whenever it goes to access the database,
** it checks the cookie to make sure the schema has not changed
** since it was last read.
**
** This plan is not completely bullet-proof. It is possible for
** the schema to change multiple times and for the cookie to be
** set back to prior value. But schema changes are infrequent
** and the probability of hitting the same cookie value is only
** 1 chance in 2^32. So we're safe enough.
*/
void sqliteChangeCookie(sqlite *db, Vdbe *v){
if( db->next_cookie==db->aDb[0].schema_cookie ){
unsigned char r;
sqliteRandomness(1, &r);
db->next_cookie = db->aDb[0].schema_cookie + r + 1;
db->flags |= SQLITE_InternChanges;
sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0);
sqliteVdbeAddOp(v, OP_SetCookie, 0, 0);
}
}
/*
** Measure the number of characters needed to output the given
** identifier. The number returned includes any quotes used
** but does not include the null terminator.
*/
static int identLength(const char *z){
int n;
int needQuote = 0;
for(n=0; *z; n++, z++){
if( *z=='\'' ){ n++; needQuote=1; }
}
return n + needQuote*2;
}
/*
** Write an identifier onto the end of the given string. Add
** quote characters as needed.
*/
static void identPut(char *z, int *pIdx, char *zIdent){
int i, j, needQuote;
i = *pIdx;
for(j=0; zIdent[j]; j++){
if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
}
needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
|| sqliteKeywordCode(zIdent, j)!=TK_ID;
if( needQuote ) z[i++] = '\'';
for(j=0; zIdent[j]; j++){
z[i++] = zIdent[j];
if( zIdent[j]=='\'' ) z[i++] = '\'';
}
if( needQuote ) z[i++] = '\'';
z[i] = 0;
*pIdx = i;
}
/*
** Generate a CREATE TABLE statement appropriate for the given
** table. Memory to hold the text of the statement is obtained
** from sqliteMalloc() and must be freed by the calling function.
*/
static char *createTableStmt(Table *p){
int i, k, n;
char *zStmt;
char *zSep, *zSep2, *zEnd;
n = 0;
for(i=0; i<p->nCol; i++){
n += identLength(p->aCol[i].zName);
}
n += identLength(p->zName);
if( n<40 ){
zSep = "";
zSep2 = ",";
zEnd = ")";
}else{
zSep = "\n ";
zSep2 = ",\n ";
zEnd = "\n)";
}
n += 35 + 6*p->nCol;
zStmt = sqliteMallocRaw( n );
if( zStmt==0 ) return 0;
strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
k = strlen(zStmt);
identPut(zStmt, &k, p->zName);
zStmt[k++] = '(';
for(i=0; i<p->nCol; i++){
strcpy(&zStmt[k], zSep);
k += strlen(&zStmt[k]);
zSep = zSep2;
identPut(zStmt, &k, p->aCol[i].zName);
}
strcpy(&zStmt[k], zEnd);
return zStmt;
}
/*
** This routine is called to report the final ")" that terminates
** a CREATE TABLE statement.
**
** The table structure that other action routines have been building
** is added to the internal hash tables, assuming no errors have
** occurred.
**
** An entry for the table is made in the master table on disk, unless
** this is a temporary table or db->init.busy==1. When db->init.busy==1
** it means we are reading the sqlite_master table because we just
** connected to the database or because the sqlite_master table has
** recently changes, so the entry for this table already exists in
** the sqlite_master table. We do not want to create it again.
**
** If the pSelect argument is not NULL, it means that this routine
** was called to create a table generated from a
** "CREATE TABLE ... AS SELECT ..." statement. The column names of
** the new table will match the result set of the SELECT.
*/
void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){
Table *p;
sqlite *db = pParse->db;
if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return;
p = pParse->pNewTable;
if( p==0 ) return;
/* If the table is generated from a SELECT, then construct the
** list of columns and the text of the table.
*/
if( pSelect ){
Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect);
if( pSelTab==0 ) return;
assert( p->aCol==0 );
p->nCol = pSelTab->nCol;
p->aCol = pSelTab->aCol;
pSelTab->nCol = 0;
pSelTab->aCol = 0;
sqliteDeleteTable(0, pSelTab);
}
/* If the db->init.busy is 1 it means we are reading the SQL off the
** "sqlite_master" or "sqlite_temp_master" table on the disk.
** So do not write to the disk again. Extract the root page number
** for the table from the db->init.newTnum field. (The page number
** should have been put there by the sqliteOpenCb routine.)
*/
if( db->init.busy ){
p->tnum = db->init.newTnum;
}
/* If not initializing, then create a record for the new table
** in the SQLITE_MASTER table of the database. The record number
** for the new table entry should already be on the stack.
**
** If this is a TEMPORARY table, write the entry into the auxiliary
** file instead of into the main database file.
*/
if( !db->init.busy ){
int n;
Vdbe *v;
v = sqliteGetVdbe(pParse);
if( v==0 ) return;
if( p->pSelect==0 ){
/* A regular table */
sqliteVdbeOp3(v, OP_CreateTable, 0, p->iDb, (char*)&p->tnum, P3_POINTER);
}else{
/* A view */
sqliteVdbeAddOp(v, OP_Integer, 0, 0);
}
p->tnum = 0;
sqliteVdbeAddOp(v, OP_Pull, 1, 0);
sqliteVdbeOp3(v, OP_String, 0, 0, p->pSelect==0?"table":"view", P3_STATIC);
sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
sqliteVdbeAddOp(v, OP_Dup, 4, 0);
sqliteVdbeAddOp(v, OP_String, 0, 0);
if( pSelect ){
char *z = createTableStmt(p);
n = z ? strlen(z) : 0;
sqliteVdbeChangeP3(v, -1, z, n);
sqliteFree(z);
}else{
assert( pEnd!=0 );
n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1;
sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n);
}
sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
if( !p->iDb ){
sqliteChangeCookie(db, v);
}
sqliteVdbeAddOp(v, OP_Close, 0, 0);
if( pSelect ){
sqliteVdbeAddOp(v, OP_Integer, p->iDb, 0);
sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0);
pParse->nTab = 2;
sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0);
}
sqliteEndWriteOperation(pParse);
}
/* Add the table to the in-memory representation of the database.
*/
if( pParse->explain==0 && pParse->nErr==0 ){
Table *pOld;
FKey *pFKey;
pOld = sqliteHashInsert(&db->aDb[p->iDb].tblHash,
p->zName, strlen(p->zName)+1, p);
if( pOld ){
assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
return;
}
for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
int nTo = strlen(pFKey->zTo) + 1;
pFKey->pNextTo = sqliteHashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo);
sqliteHashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey);
}
pParse->pNewTable = 0;
db->nTable++;
db->flags |= SQLITE_InternChanges;
}
}
/*
** The parser calls this routine in order to create a new VIEW
*/
void sqliteCreateView(
Parse *pParse, /* The parsing context */
Token *pBegin, /* The CREATE token that begins the statement */
Token *pName, /* The token that holds the name of the view */
Select *pSelect, /* A SELECT statement that will become the new view */
int isTemp /* TRUE for a TEMPORARY view */
){
Table *p;
int n;