64bit fixes
[AROS-Contrib.git] / sqlite3 / build.c
blob688f83aace5485e3308d18e875ff8ac6019bac81
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains C code routines that are called by the SQLite parser
13 ** when syntax rules are reduced. The routines in this file handle the
14 ** following kinds of SQL syntax:
16 ** CREATE TABLE
17 ** DROP TABLE
18 ** CREATE INDEX
19 ** DROP INDEX
20 ** creating ID lists
21 ** BEGIN TRANSACTION
22 ** COMMIT
23 ** ROLLBACK
25 ** $Id$
27 #include "sqliteInt.h"
28 #include <ctype.h>
31 ** This routine is called when a new SQL statement is beginning to
32 ** be parsed. Initialize the pParse structure as needed.
34 void sqlite3BeginParse(Parse *pParse, int explainFlag){
35 pParse->explain = explainFlag;
36 pParse->nVar = 0;
40 ** This routine is called after a single SQL statement has been
41 ** parsed and a VDBE program to execute that statement has been
42 ** prepared. This routine puts the finishing touches on the
43 ** VDBE program and resets the pParse structure for the next
44 ** parse.
46 ** Note that if an error occurred, it might be the case that
47 ** no VDBE code was generated.
49 void sqlite3FinishCoding(Parse *pParse){
50 sqlite3 *db;
51 Vdbe *v;
53 if( sqlite3_malloc_failed ) return;
54 if( pParse->nested ) return;
55 if( !pParse->pVdbe ){
56 if( pParse->rc==SQLITE_OK && pParse->nErr ){
57 pParse->rc = SQLITE_ERROR;
59 return;
62 /* Begin by generating some termination code at the end of the
63 ** vdbe program
65 db = pParse->db;
66 v = sqlite3GetVdbe(pParse);
67 if( v ){
68 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
70 /* The cookie mask contains one bit for each database file open.
71 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
72 ** set for each database that is used. Generate code to start a
73 ** transaction on each used database and to verify the schema cookie
74 ** on each used database.
76 if( pParse->cookieGoto>0 ){
77 u32 mask;
78 int iDb;
79 sqlite3VdbeChangeP2(v, pParse->cookieGoto-1, sqlite3VdbeCurrentAddr(v));
80 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81 if( (mask & pParse->cookieMask)==0 ) continue;
82 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
83 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
85 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
88 /* Add a No-op that contains the complete text of the compiled SQL
89 ** statement as its P3 argument. This does not change the functionality
90 ** of the program.
92 ** This is used to implement sqlite3_trace().
94 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
98 /* Get the VDBE program ready for execution
100 if( v && pParse->nErr==0 ){
101 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
102 sqlite3VdbeTrace(v, trace);
103 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
104 pParse->nTab+3, pParse->nMaxDepth+1, pParse->explain);
105 pParse->rc = SQLITE_DONE;
106 pParse->colNamesSet = 0;
107 }else if( pParse->rc==SQLITE_OK ){
108 pParse->rc = SQLITE_ERROR;
110 pParse->nTab = 0;
111 pParse->nMem = 0;
112 pParse->nSet = 0;
113 pParse->nVar = 0;
114 pParse->cookieMask = 0;
115 pParse->cookieGoto = 0;
119 ** Run the parser and code generator recursively in order to generate
120 ** code for the SQL statement given onto the end of the pParse context
121 ** currently under construction. When the parser is run recursively
122 ** this way, the final OP_Halt is not appended and other initialization
123 ** and finalization steps are omitted because those are handling by the
124 ** outermost parser.
126 ** Not everything is nestable. This facility is designed to permit
127 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
128 ** care if you decide to try to use this routine for some other purposes.
130 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
131 va_list ap;
132 char *zSql;
133 int rc;
134 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
135 char saveBuf[SAVE_SZ];
137 if( pParse->nErr ) return;
138 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
139 va_start(ap, zFormat);
140 zSql = sqlite3VMPrintf(zFormat, ap);
141 va_end(ap);
142 if( zSql==0 ){
143 return; /* A malloc must have failed */
145 pParse->nested++;
146 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
147 memset(&pParse->nVar, 0, SAVE_SZ);
148 rc = sqlite3RunParser(pParse, zSql, 0);
149 sqliteFree(zSql);
150 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
151 pParse->nested--;
155 ** Locate the in-memory structure that describes a particular database
156 ** table given the name of that table and (optionally) the name of the
157 ** database containing the table. Return NULL if not found.
159 ** If zDatabase is 0, all databases are searched for the table and the
160 ** first matching table is returned. (No checking for duplicate table
161 ** names is done.) The search order is TEMP first, then MAIN, then any
162 ** auxiliary databases added using the ATTACH command.
164 ** See also sqlite3LocateTable().
166 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
167 Table *p = 0;
168 int i;
169 assert( zName!=0 );
170 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
171 for(i=OMIT_TEMPDB; i<db->nDb; i++){
172 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
173 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
174 p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
175 if( p ) break;
177 return p;
181 ** Locate the in-memory structure that describes a particular database
182 ** table given the name of that table and (optionally) the name of the
183 ** database containing the table. Return NULL if not found. Also leave an
184 ** error message in pParse->zErrMsg.
186 ** The difference between this routine and sqlite3FindTable() is that this
187 ** routine leaves an error message in pParse->zErrMsg where
188 ** sqlite3FindTable() does not.
190 Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
191 Table *p;
193 /* Read the database schema. If an error occurs, leave an error message
194 ** and code in pParse and return NULL. */
195 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
196 return 0;
199 p = sqlite3FindTable(pParse->db, zName, zDbase);
200 if( p==0 ){
201 if( zDbase ){
202 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
203 }else if( sqlite3FindTable(pParse->db, zName, 0)!=0 ){
204 sqlite3ErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
205 zName, zDbase);
206 }else{
207 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
209 pParse->checkSchema = 1;
211 return p;
215 ** Locate the in-memory structure that describes
216 ** a particular index given the name of that index
217 ** and the name of the database that contains the index.
218 ** Return NULL if not found.
220 ** If zDatabase is 0, all databases are searched for the
221 ** table and the first matching index is returned. (No checking
222 ** for duplicate index names is done.) The search order is
223 ** TEMP first, then MAIN, then any auxiliary databases added
224 ** using the ATTACH command.
226 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
227 Index *p = 0;
228 int i;
229 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
230 for(i=OMIT_TEMPDB; i<db->nDb; i++){
231 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
232 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
233 p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
234 if( p ) break;
236 return p;
240 ** Reclaim the memory used by an index
242 static void freeIndex(Index *p){
243 sqliteFree(p->zColAff);
244 sqliteFree(p);
248 ** Remove the given index from the index hash table, and free
249 ** its memory structures.
251 ** The index is removed from the database hash tables but
252 ** it is not unlinked from the Table that it indexes.
253 ** Unlinking from the Table must be done by the calling function.
255 static void sqliteDeleteIndex(sqlite3 *db, Index *p){
256 Index *pOld;
258 assert( db!=0 && p->zName!=0 );
259 pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName,
260 strlen(p->zName)+1, 0);
261 if( pOld!=0 && pOld!=p ){
262 sqlite3HashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
263 strlen(pOld->zName)+1, pOld);
265 freeIndex(p);
269 ** For the index called zIdxName which is found in the database iDb,
270 ** unlike that index from its Table then remove the index from
271 ** the index hash table and free all memory structures associated
272 ** with the index.
274 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
275 Index *pIndex;
276 int len;
278 len = strlen(zIdxName);
279 pIndex = sqlite3HashInsert(&db->aDb[iDb].idxHash, zIdxName, len+1, 0);
280 if( pIndex ){
281 if( pIndex->pTable->pIndex==pIndex ){
282 pIndex->pTable->pIndex = pIndex->pNext;
283 }else{
284 Index *p;
285 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
286 if( p && p->pNext==pIndex ){
287 p->pNext = pIndex->pNext;
290 freeIndex(pIndex);
292 db->flags |= SQLITE_InternChanges;
296 ** Erase all schema information from the in-memory hash tables of
297 ** a single database. This routine is called to reclaim memory
298 ** before the database closes. It is also called during a rollback
299 ** if there were schema changes during the transaction or if a
300 ** schema-cookie mismatch occurs.
302 ** If iDb<=0 then reset the internal schema tables for all database
303 ** files. If iDb>=2 then reset the internal schema for only the
304 ** single file indicated.
306 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
307 HashElem *pElem;
308 Hash temp1;
309 Hash temp2;
310 int i, j;
312 assert( iDb>=0 && iDb<db->nDb );
313 db->flags &= ~SQLITE_Initialized;
314 for(i=iDb; i<db->nDb; i++){
315 Db *pDb = &db->aDb[i];
316 temp1 = pDb->tblHash;
317 temp2 = pDb->trigHash;
318 sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
319 sqlite3HashClear(&pDb->aFKey);
320 sqlite3HashClear(&pDb->idxHash);
321 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
322 sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
324 sqlite3HashClear(&temp2);
325 sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
326 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
327 Table *pTab = sqliteHashData(pElem);
328 sqlite3DeleteTable(db, pTab);
330 sqlite3HashClear(&temp1);
331 pDb->pSeqTab = 0;
332 DbClearProperty(db, i, DB_SchemaLoaded);
333 if( iDb>0 ) return;
335 assert( iDb==0 );
336 db->flags &= ~SQLITE_InternChanges;
338 /* If one or more of the auxiliary database files has been closed,
339 ** then remove then from the auxiliary database list. We take the
340 ** opportunity to do this here since we have just deleted all of the
341 ** schema hash tables and therefore do not have to make any changes
342 ** to any of those tables.
344 for(i=0; i<db->nDb; i++){
345 struct Db *pDb = &db->aDb[i];
346 if( pDb->pBt==0 ){
347 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
348 pDb->pAux = 0;
351 for(i=j=2; i<db->nDb; i++){
352 struct Db *pDb = &db->aDb[i];
353 if( pDb->pBt==0 ){
354 sqliteFree(pDb->zName);
355 pDb->zName = 0;
356 continue;
358 if( j<i ){
359 db->aDb[j] = db->aDb[i];
361 j++;
363 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
364 db->nDb = j;
365 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
366 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
367 sqliteFree(db->aDb);
368 db->aDb = db->aDbStatic;
373 ** This routine is called whenever a rollback occurs. If there were
374 ** schema changes during the transaction, then we have to reset the
375 ** internal hash tables and reload them from disk.
377 void sqlite3RollbackInternalChanges(sqlite3 *db){
378 if( db->flags & SQLITE_InternChanges ){
379 sqlite3ResetInternalSchema(db, 0);
384 ** This routine is called when a commit occurs.
386 void sqlite3CommitInternalChanges(sqlite3 *db){
387 db->flags &= ~SQLITE_InternChanges;
391 ** Clear the column names from a table or view.
393 static void sqliteResetColumnNames(Table *pTable){
394 int i;
395 Column *pCol;
396 assert( pTable!=0 );
397 if( (pCol = pTable->aCol)!=0 ){
398 for(i=0; i<pTable->nCol; i++, pCol++){
399 sqliteFree(pCol->zName);
400 sqlite3ExprDelete(pCol->pDflt);
401 sqliteFree(pCol->zType);
403 sqliteFree(pTable->aCol);
405 pTable->aCol = 0;
406 pTable->nCol = 0;
410 ** Remove the memory data structures associated with the given
411 ** Table. No changes are made to disk by this routine.
413 ** This routine just deletes the data structure. It does not unlink
414 ** the table data structure from the hash table. Nor does it remove
415 ** foreign keys from the sqlite.aFKey hash table. But it does destroy
416 ** memory structures of the indices and foreign keys associated with
417 ** the table.
419 ** Indices associated with the table are unlinked from the "db"
420 ** data structure if db!=NULL. If db==NULL, indices attached to
421 ** the table are deleted, but it is assumed they have already been
422 ** unlinked.
424 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
425 Index *pIndex, *pNext;
426 FKey *pFKey, *pNextFKey;
428 if( pTable==0 ) return;
430 /* Do not delete the table until the reference count reaches zero. */
431 pTable->nRef--;
432 if( pTable->nRef>0 ){
433 return;
435 assert( pTable->nRef==0 );
437 /* Delete all indices associated with this table
439 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
440 pNext = pIndex->pNext;
441 assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
442 sqliteDeleteIndex(db, pIndex);
445 #ifndef SQLITE_OMIT_FOREIGN_KEY
446 /* Delete all foreign keys associated with this table. The keys
447 ** should have already been unlinked from the db->aFKey hash table
449 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
450 pNextFKey = pFKey->pNextFrom;
451 assert( pTable->iDb<db->nDb );
452 assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey,
453 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
454 sqliteFree(pFKey);
456 #endif
458 /* Delete the Table structure itself.
460 sqliteResetColumnNames(pTable);
461 sqliteFree(pTable->zName);
462 sqliteFree(pTable->zColAff);
463 sqlite3SelectDelete(pTable->pSelect);
464 sqliteFree(pTable);
468 ** Unlink the given table from the hash tables and the delete the
469 ** table structure with all its indices and foreign keys.
471 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
472 Table *p;
473 FKey *pF1, *pF2;
474 Db *pDb;
476 assert( db!=0 );
477 assert( iDb>=0 && iDb<db->nDb );
478 assert( zTabName && zTabName[0] );
479 pDb = &db->aDb[iDb];
480 p = sqlite3HashInsert(&pDb->tblHash, zTabName, strlen(zTabName)+1, 0);
481 if( p ){
482 #ifndef SQLITE_OMIT_FOREIGN_KEY
483 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
484 int nTo = strlen(pF1->zTo) + 1;
485 pF2 = sqlite3HashFind(&pDb->aFKey, pF1->zTo, nTo);
486 if( pF2==pF1 ){
487 sqlite3HashInsert(&pDb->aFKey, pF1->zTo, nTo, pF1->pNextTo);
488 }else{
489 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
490 if( pF2 ){
491 pF2->pNextTo = pF1->pNextTo;
495 #endif
496 sqlite3DeleteTable(db, p);
498 db->flags |= SQLITE_InternChanges;
502 ** Given a token, return a string that consists of the text of that
503 ** token with any quotations removed. Space to hold the returned string
504 ** is obtained from sqliteMalloc() and must be freed by the calling
505 ** function.
507 ** Tokens are often just pointers into the original SQL text and so
508 ** are not \000 terminated and are not persistent. The returned string
509 ** is \000 terminated and is persistent.
511 char *sqlite3NameFromToken(Token *pName){
512 char *zName;
513 if( pName ){
514 zName = sqliteStrNDup(pName->z, pName->n);
515 sqlite3Dequote(zName);
516 }else{
517 zName = 0;
519 return zName;
523 ** Open the sqlite_master table stored in database number iDb for
524 ** writing. The table is opened using cursor 0.
526 void sqlite3OpenMasterTable(Vdbe *v, int iDb){
527 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
528 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
529 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
533 ** The token *pName contains the name of a database (either "main" or
534 ** "temp" or the name of an attached db). This routine returns the
535 ** index of the named database in db->aDb[], or -1 if the named db
536 ** does not exist.
538 static int findDb(sqlite3 *db, Token *pName){
539 int i = -1; /* Database number */
540 int n; /* Number of characters in the name */
541 Db *pDb; /* A database whose name space is being searched */
542 char *zName; /* Name we are searching for */
544 zName = sqlite3NameFromToken(pName);
545 if( zName ){
546 n = strlen(zName);
547 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
548 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
549 0==sqlite3StrICmp(pDb->zName, zName) ){
550 break;
553 sqliteFree(zName);
555 return i;
558 /* The table or view or trigger name is passed to this routine via tokens
559 ** pName1 and pName2. If the table name was fully qualified, for example:
561 ** CREATE TABLE xxx.yyy (...);
563 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
564 ** the table name is not fully qualified, i.e.:
566 ** CREATE TABLE yyy(...);
568 ** Then pName1 is set to "yyy" and pName2 is "".
570 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
571 ** pName2) that stores the unqualified table name. The index of the
572 ** database "xxx" is returned.
574 int sqlite3TwoPartName(
575 Parse *pParse, /* Parsing and code generating context */
576 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
577 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
578 Token **pUnqual /* Write the unqualified object name here */
580 int iDb; /* Database holding the object */
581 sqlite3 *db = pParse->db;
583 if( pName2 && pName2->n>0 ){
584 assert( !db->init.busy );
585 *pUnqual = pName2;
586 iDb = findDb(db, pName1);
587 if( iDb<0 ){
588 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
589 pParse->nErr++;
590 return -1;
592 }else{
593 assert( db->init.iDb==0 || db->init.busy );
594 iDb = db->init.iDb;
595 *pUnqual = pName1;
597 return iDb;
601 ** This routine is used to check if the UTF-8 string zName is a legal
602 ** unqualified name for a new schema object (table, index, view or
603 ** trigger). All names are legal except those that begin with the string
604 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
605 ** is reserved for internal use.
607 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
608 if( !pParse->db->init.busy && pParse->nested==0
609 && (pParse->db->flags & SQLITE_WriteSchema)==0
610 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
611 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
612 return SQLITE_ERROR;
614 return SQLITE_OK;
618 ** Begin constructing a new table representation in memory. This is
619 ** the first of several action routines that get called in response
620 ** to a CREATE TABLE statement. In particular, this routine is called
621 ** after seeing tokens "CREATE" and "TABLE" and the table name. The
622 ** pStart token is the CREATE and pName is the table name. The isTemp
623 ** flag is true if the table should be stored in the auxiliary database
624 ** file instead of in the main database file. This is normally the case
625 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
626 ** CREATE and TABLE.
628 ** The new table record is initialized and put in pParse->pNewTable.
629 ** As more of the CREATE TABLE statement is parsed, additional action
630 ** routines will be called to add more information to this record.
631 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
632 ** is called to complete the construction of the new table record.
634 void sqlite3StartTable(
635 Parse *pParse, /* Parser context */
636 Token *pStart, /* The "CREATE" token */
637 Token *pName1, /* First part of the name of the table or view */
638 Token *pName2, /* Second part of the name of the table or view */
639 int isTemp, /* True if this is a TEMP table */
640 int isView /* True if this is a VIEW */
642 Table *pTable;
643 Index *pIdx;
644 char *zName = 0; /* The name of the new table */
645 sqlite3 *db = pParse->db;
646 Vdbe *v;
647 int iDb; /* Database number to create the table in */
648 Token *pName; /* Unqualified name of the table to create */
650 /* The table or view name to create is passed to this routine via tokens
651 ** pName1 and pName2. If the table name was fully qualified, for example:
653 ** CREATE TABLE xxx.yyy (...);
655 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
656 ** the table name is not fully qualified, i.e.:
658 ** CREATE TABLE yyy(...);
660 ** Then pName1 is set to "yyy" and pName2 is "".
662 ** The call below sets the pName pointer to point at the token (pName1 or
663 ** pName2) that stores the unqualified table name. The variable iDb is
664 ** set to the index of the database that the table or view is to be
665 ** created in.
667 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
668 if( iDb<0 ) return;
669 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
670 /* If creating a temp table, the name may not be qualified */
671 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
672 return;
674 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
676 pParse->sNameToken = *pName;
677 zName = sqlite3NameFromToken(pName);
678 if( zName==0 ) return;
679 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
680 goto begin_table_error;
682 if( db->init.iDb==1 ) isTemp = 1;
683 #ifndef SQLITE_OMIT_AUTHORIZATION
684 assert( (isTemp & 1)==isTemp );
686 int code;
687 char *zDb = db->aDb[iDb].zName;
688 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
689 goto begin_table_error;
691 if( isView ){
692 if( !OMIT_TEMPDB && isTemp ){
693 code = SQLITE_CREATE_TEMP_VIEW;
694 }else{
695 code = SQLITE_CREATE_VIEW;
697 }else{
698 if( !OMIT_TEMPDB && isTemp ){
699 code = SQLITE_CREATE_TEMP_TABLE;
700 }else{
701 code = SQLITE_CREATE_TABLE;
704 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
705 goto begin_table_error;
708 #endif
710 /* Make sure the new table name does not collide with an existing
711 ** index or table name in the same database. Issue an error message if
712 ** it does.
714 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
715 goto begin_table_error;
717 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
718 if( pTable ){
719 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
720 goto begin_table_error;
722 if( (pIdx = sqlite3FindIndex(db, zName, 0))!=0 &&
723 ( iDb==0 || !db->init.busy) ){
724 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
725 goto begin_table_error;
727 pTable = sqliteMalloc( sizeof(Table) );
728 if( pTable==0 ){
729 pParse->rc = SQLITE_NOMEM;
730 pParse->nErr++;
731 goto begin_table_error;
733 pTable->zName = zName;
734 pTable->nCol = 0;
735 pTable->aCol = 0;
736 pTable->iPKey = -1;
737 pTable->pIndex = 0;
738 pTable->iDb = iDb;
739 pTable->nRef = 1;
740 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
741 pParse->pNewTable = pTable;
743 /* If this is the magic sqlite_sequence table used by autoincrement,
744 ** then record a pointer to this table in the main database structure
745 ** so that INSERT can find the table easily.
747 #ifndef SQLITE_OMIT_AUTOINCREMENT
748 if( strcmp(zName, "sqlite_sequence")==0 ){
749 db->aDb[iDb].pSeqTab = pTable;
751 #endif
753 /* Begin generating the code that will insert the table record into
754 ** the SQLITE_MASTER table. Note in particular that we must go ahead
755 ** and allocate the record number for the table entry now. Before any
756 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
757 ** indices to be created and the table record must come before the
758 ** indices. Hence, the record number for the table must be allocated
759 ** now.
761 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
762 int lbl;
763 sqlite3BeginWriteOperation(pParse, 0, iDb);
765 /* If the file format and encoding in the database have not been set,
766 ** set them now.
768 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
769 lbl = sqlite3VdbeMakeLabel(v);
770 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
771 sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0);
772 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
773 sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0);
774 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
775 sqlite3VdbeResolveLabel(v, lbl);
777 /* This just creates a place-holder record in the sqlite_master table.
778 ** The record created does not contain anything yet. It will be replaced
779 ** by the real entry in code generated at sqlite3EndTable().
781 ** The rowid for the new entry is left on the top of the stack.
782 ** The rowid value is needed by the code that sqlite3EndTable will
783 ** generate.
785 #ifndef SQLITE_OMIT_VIEW
786 if( isView ){
787 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
788 }else
789 #endif
791 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
793 sqlite3OpenMasterTable(v, iDb);
794 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
795 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
796 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
797 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
798 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
799 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
802 /* Normal (non-error) return. */
803 return;
805 /* If an error occurs, we jump here */
806 begin_table_error:
807 sqliteFree(zName);
808 return;
812 ** This macro is used to compare two strings in a case-insensitive manner.
813 ** It is slightly faster than calling sqlite3StrICmp() directly, but
814 ** produces larger code.
816 ** WARNING: This macro is not compatible with the strcmp() family. It
817 ** returns true if the two strings are equal, otherwise false.
819 #define STRICMP(x, y) (\
820 sqlite3UpperToLower[*(unsigned char *)(x)]== \
821 sqlite3UpperToLower[*(unsigned char *)(y)] \
822 && sqlite3StrICmp((x)+1,(y)+1)==0 )
825 ** Add a new column to the table currently being constructed.
827 ** The parser calls this routine once for each column declaration
828 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
829 ** first to get things going. Then this routine is called for each
830 ** column.
832 void sqlite3AddColumn(Parse *pParse, Token *pName){
833 Table *p;
834 int i;
835 char *z;
836 Column *pCol;
837 if( (p = pParse->pNewTable)==0 ) return;
838 z = sqlite3NameFromToken(pName);
839 if( z==0 ) return;
840 for(i=0; i<p->nCol; i++){
841 if( STRICMP(z, p->aCol[i].zName) ){
842 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
843 sqliteFree(z);
844 return;
847 if( (p->nCol & 0x7)==0 ){
848 Column *aNew;
849 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
850 if( aNew==0 ){
851 sqliteFree(z);
852 return;
854 p->aCol = aNew;
856 pCol = &p->aCol[p->nCol];
857 memset(pCol, 0, sizeof(p->aCol[0]));
858 pCol->zName = z;
860 /* If there is no type specified, columns have the default affinity
861 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
862 ** be called next to set pCol->affinity correctly.
864 pCol->affinity = SQLITE_AFF_NONE;
865 pCol->pColl = pParse->db->pDfltColl;
866 p->nCol++;
870 ** This routine is called by the parser while in the middle of
871 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
872 ** been seen on a column. This routine sets the notNull flag on
873 ** the column currently under construction.
875 void sqlite3AddNotNull(Parse *pParse, int onError){
876 Table *p;
877 int i;
878 if( (p = pParse->pNewTable)==0 ) return;
879 i = p->nCol-1;
880 if( i>=0 ) p->aCol[i].notNull = onError;
884 ** Scan the column type name zType (length nType) and return the
885 ** associated affinity type.
887 ** This routine does a case-independent search of zType for the
888 ** substrings in the following table. If one of the substrings is
889 ** found, the corresponding affinity is returned. If zType contains
890 ** more than one of the substrings, entries toward the top of
891 ** the table take priority. For example, if zType is 'BLOBINT',
892 ** SQLITE_AFF_INTEGER is returned.
894 ** Substring | Affinity
895 ** --------------------------------
896 ** 'INT' | SQLITE_AFF_INTEGER
897 ** 'CHAR' | SQLITE_AFF_TEXT
898 ** 'CLOB' | SQLITE_AFF_TEXT
899 ** 'TEXT' | SQLITE_AFF_TEXT
900 ** 'BLOB' | SQLITE_AFF_NONE
902 ** If none of the substrings in the above table are found,
903 ** SQLITE_AFF_NUMERIC is returned.
905 static char sqlite3AffinityType(const char *zType, int nType){
906 u32 h = 0;
907 char aff = SQLITE_AFF_NUMERIC;
908 const unsigned char *zIn = zType;
909 const unsigned char *zEnd = (zIn+nType);
911 while( zIn!=zEnd ){
912 h = (h<<8) + sqlite3UpperToLower[*zIn];
913 zIn++;
914 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
915 aff = SQLITE_AFF_TEXT;
916 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
917 aff = SQLITE_AFF_TEXT;
918 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
919 aff = SQLITE_AFF_TEXT;
920 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
921 && aff==SQLITE_AFF_NUMERIC ){
922 aff = SQLITE_AFF_NONE;
923 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
924 aff = SQLITE_AFF_INTEGER;
925 break;
929 return aff;
933 ** This routine is called by the parser while in the middle of
934 ** parsing a CREATE TABLE statement. The pFirst token is the first
935 ** token in the sequence of tokens that describe the type of the
936 ** column currently under construction. pLast is the last token
937 ** in the sequence. Use this information to construct a string
938 ** that contains the typename of the column and store that string
939 ** in zType.
941 void sqlite3AddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
942 Table *p;
943 int i, j;
944 int n;
945 char *z;
946 const unsigned char *zIn;
948 Column *pCol;
949 if( (p = pParse->pNewTable)==0 ) return;
950 i = p->nCol-1;
951 if( i<0 ) return;
952 pCol = &p->aCol[i];
953 zIn = pFirst->z;
954 n = pLast->n + (pLast->z - zIn);
955 assert( pCol->zType==0 );
956 z = pCol->zType = sqliteMallocRaw(n+1);
957 if( z==0 ) return;
958 for(i=j=0; i<n; i++){
959 int c = zIn[i];
960 if( isspace(c) ) continue;
961 z[j++] = c;
963 z[j] = 0;
964 pCol->affinity = sqlite3AffinityType(z, n);
968 ** The expression is the default value for the most recently added column
969 ** of the table currently under construction.
971 ** Default value expressions must be constant. Raise an exception if this
972 ** is not the case.
974 ** This routine is called by the parser while in the middle of
975 ** parsing a CREATE TABLE statement.
977 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
978 Table *p;
979 Column *pCol;
980 if( (p = pParse->pNewTable)==0 ) return;
981 pCol = &(p->aCol[p->nCol-1]);
982 if( !sqlite3ExprIsConstant(pExpr) ){
983 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
984 pCol->zName);
985 }else{
986 sqlite3ExprDelete(pCol->pDflt);
987 pCol->pDflt = sqlite3ExprDup(pExpr);
989 sqlite3ExprDelete(pExpr);
993 ** Designate the PRIMARY KEY for the table. pList is a list of names
994 ** of columns that form the primary key. If pList is NULL, then the
995 ** most recently added column of the table is the primary key.
997 ** A table can have at most one primary key. If the table already has
998 ** a primary key (and this is the second primary key) then create an
999 ** error.
1001 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1002 ** then we will try to use that column as the rowid. Set the Table.iPKey
1003 ** field of the table under construction to be the index of the
1004 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1005 ** no INTEGER PRIMARY KEY.
1007 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1008 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1010 void sqlite3AddPrimaryKey(
1011 Parse *pParse, /* Parsing context */
1012 ExprList *pList, /* List of field names to be indexed */
1013 int onError, /* What to do with a uniqueness conflict */
1014 int autoInc /* True if the AUTOINCREMENT keyword is present */
1016 Table *pTab = pParse->pNewTable;
1017 char *zType = 0;
1018 int iCol = -1, i;
1019 if( pTab==0 ) goto primary_key_exit;
1020 if( pTab->hasPrimKey ){
1021 sqlite3ErrorMsg(pParse,
1022 "table \"%s\" has more than one primary key", pTab->zName);
1023 goto primary_key_exit;
1025 pTab->hasPrimKey = 1;
1026 if( pList==0 ){
1027 iCol = pTab->nCol - 1;
1028 pTab->aCol[iCol].isPrimKey = 1;
1029 }else{
1030 for(i=0; i<pList->nExpr; i++){
1031 for(iCol=0; iCol<pTab->nCol; iCol++){
1032 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1033 break;
1036 if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
1038 if( pList->nExpr>1 ) iCol = -1;
1040 if( iCol>=0 && iCol<pTab->nCol ){
1041 zType = pTab->aCol[iCol].zType;
1043 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){
1044 pTab->iPKey = iCol;
1045 pTab->keyConf = onError;
1046 pTab->autoInc = autoInc;
1047 }else if( autoInc ){
1048 #ifndef SQLITE_OMIT_AUTOINCREMENT
1049 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1050 "INTEGER PRIMARY KEY");
1051 #endif
1052 }else{
1053 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0);
1054 pList = 0;
1057 primary_key_exit:
1058 sqlite3ExprListDelete(pList);
1059 return;
1063 ** Set the collation function of the most recently parsed table column
1064 ** to the CollSeq given.
1066 void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
1067 Table *p;
1068 Index *pIdx;
1069 CollSeq *pColl;
1070 int i;
1072 if( (p = pParse->pNewTable)==0 ) return;
1073 i = p->nCol-1;
1075 pColl = sqlite3LocateCollSeq(pParse, zType, nType);
1076 p->aCol[i].pColl = pColl;
1078 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1079 ** then an index may have been created on this column before the
1080 ** collation type was added. Correct this if it is the case.
1082 for(pIdx = p->pIndex; pIdx; pIdx=pIdx->pNext){
1083 assert( pIdx->nColumn==1 );
1084 if( pIdx->aiColumn[0]==i ) pIdx->keyInfo.aColl[0] = pColl;
1089 ** Call sqlite3CheckCollSeq() for all collating sequences in an index,
1090 ** in order to verify that all the necessary collating sequences are
1091 ** loaded.
1093 int sqlite3CheckIndexCollSeq(Parse *pParse, Index *pIdx){
1094 if( pIdx ){
1095 int i;
1096 for(i=0; i<pIdx->nColumn; i++){
1097 if( sqlite3CheckCollSeq(pParse, pIdx->keyInfo.aColl[i]) ){
1098 return SQLITE_ERROR;
1102 return SQLITE_OK;
1106 ** This function returns the collation sequence for database native text
1107 ** encoding identified by the string zName, length nName.
1109 ** If the requested collation sequence is not available, or not available
1110 ** in the database native encoding, the collation factory is invoked to
1111 ** request it. If the collation factory does not supply such a sequence,
1112 ** and the sequence is available in another text encoding, then that is
1113 ** returned instead.
1115 ** If no versions of the requested collations sequence are available, or
1116 ** another error occurs, NULL is returned and an error message written into
1117 ** pParse.
1119 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
1120 sqlite3 *db = pParse->db;
1121 u8 enc = db->enc;
1122 u8 initbusy = db->init.busy;
1124 CollSeq *pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
1125 if( !initbusy && (!pColl || !pColl->xCmp) ){
1126 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1127 if( !pColl ){
1128 if( nName<0 ){
1129 nName = strlen(zName);
1131 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1132 pColl = 0;
1136 return pColl;
1141 ** Generate code that will increment the schema cookie.
1143 ** The schema cookie is used to determine when the schema for the
1144 ** database changes. After each schema change, the cookie value
1145 ** changes. When a process first reads the schema it records the
1146 ** cookie. Thereafter, whenever it goes to access the database,
1147 ** it checks the cookie to make sure the schema has not changed
1148 ** since it was last read.
1150 ** This plan is not completely bullet-proof. It is possible for
1151 ** the schema to change multiple times and for the cookie to be
1152 ** set back to prior value. But schema changes are infrequent
1153 ** and the probability of hitting the same cookie value is only
1154 ** 1 chance in 2^32. So we're safe enough.
1156 void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
1157 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].schema_cookie+1, 0);
1158 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
1162 ** Measure the number of characters needed to output the given
1163 ** identifier. The number returned includes any quotes used
1164 ** but does not include the null terminator.
1166 ** The estimate is conservative. It might be larger that what is
1167 ** really needed.
1169 static int identLength(const char *z){
1170 int n;
1171 for(n=0; *z; n++, z++){
1172 if( *z=='"' ){ n++; }
1174 return n + 2;
1178 ** Write an identifier onto the end of the given string. Add
1179 ** quote characters as needed.
1181 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1182 unsigned char *zIdent = (unsigned char*)zSignedIdent;
1183 int i, j, needQuote;
1184 i = *pIdx;
1185 for(j=0; zIdent[j]; j++){
1186 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1188 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
1189 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1190 if( needQuote ) z[i++] = '"';
1191 for(j=0; zIdent[j]; j++){
1192 z[i++] = zIdent[j];
1193 if( zIdent[j]=='"' ) z[i++] = '"';
1195 if( needQuote ) z[i++] = '"';
1196 z[i] = 0;
1197 *pIdx = i;
1201 ** Generate a CREATE TABLE statement appropriate for the given
1202 ** table. Memory to hold the text of the statement is obtained
1203 ** from sqliteMalloc() and must be freed by the calling function.
1205 static char *createTableStmt(Table *p){
1206 int i, k, n;
1207 char *zStmt;
1208 char *zSep, *zSep2, *zEnd, *z;
1209 Column *pCol;
1210 n = 0;
1211 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1212 n += identLength(pCol->zName);
1213 z = pCol->zType;
1214 if( z ){
1215 n += (strlen(z) + 1);
1218 n += identLength(p->zName);
1219 if( n<50 ){
1220 zSep = "";
1221 zSep2 = ",";
1222 zEnd = ")";
1223 }else{
1224 zSep = "\n ";
1225 zSep2 = ",\n ";
1226 zEnd = "\n)";
1228 n += 35 + 6*p->nCol;
1229 zStmt = sqliteMallocRaw( n );
1230 if( zStmt==0 ) return 0;
1231 strcpy(zStmt, !OMIT_TEMPDB&&p->iDb==1 ? "CREATE TEMP TABLE ":"CREATE TABLE ");
1232 k = strlen(zStmt);
1233 identPut(zStmt, &k, p->zName);
1234 zStmt[k++] = '(';
1235 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1236 strcpy(&zStmt[k], zSep);
1237 k += strlen(&zStmt[k]);
1238 zSep = zSep2;
1239 identPut(zStmt, &k, pCol->zName);
1240 if( (z = pCol->zType)!=0 ){
1241 zStmt[k++] = ' ';
1242 strcpy(&zStmt[k], z);
1243 k += strlen(z);
1246 strcpy(&zStmt[k], zEnd);
1247 return zStmt;
1251 ** This routine is called to report the final ")" that terminates
1252 ** a CREATE TABLE statement.
1254 ** The table structure that other action routines have been building
1255 ** is added to the internal hash tables, assuming no errors have
1256 ** occurred.
1258 ** An entry for the table is made in the master table on disk, unless
1259 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1260 ** it means we are reading the sqlite_master table because we just
1261 ** connected to the database or because the sqlite_master table has
1262 ** recently changed, so the entry for this table already exists in
1263 ** the sqlite_master table. We do not want to create it again.
1265 ** If the pSelect argument is not NULL, it means that this routine
1266 ** was called to create a table generated from a
1267 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1268 ** the new table will match the result set of the SELECT.
1270 void sqlite3EndTable(
1271 Parse *pParse, /* Parse context */
1272 Token *pCons, /* The ',' token after the last column defn. */
1273 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1274 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1276 Table *p;
1277 sqlite3 *db = pParse->db;
1279 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
1280 p = pParse->pNewTable;
1281 if( p==0 ) return;
1283 assert( !db->init.busy || !pSelect );
1285 /* If the db->init.busy is 1 it means we are reading the SQL off the
1286 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1287 ** So do not write to the disk again. Extract the root page number
1288 ** for the table from the db->init.newTnum field. (The page number
1289 ** should have been put there by the sqliteOpenCb routine.)
1291 if( db->init.busy ){
1292 p->tnum = db->init.newTnum;
1295 /* If not initializing, then create a record for the new table
1296 ** in the SQLITE_MASTER table of the database. The record number
1297 ** for the new table entry should already be on the stack.
1299 ** If this is a TEMPORARY table, write the entry into the auxiliary
1300 ** file instead of into the main database file.
1302 if( !db->init.busy ){
1303 int n;
1304 Vdbe *v;
1305 char *zType; /* "view" or "table" */
1306 char *zType2; /* "VIEW" or "TABLE" */
1307 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
1309 v = sqlite3GetVdbe(pParse);
1310 if( v==0 ) return;
1312 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1314 /* Create the rootpage for the new table and push it onto the stack.
1315 ** A view has no rootpage, so just push a zero onto the stack for
1316 ** views. Initialize zType at the same time.
1318 if( p->pSelect==0 ){
1319 /* A regular table */
1320 /* sqlite3VdbeAddOp(v, OP_CreateTable, p->iDb, 0); */
1321 zType = "table";
1322 zType2 = "TABLE";
1323 #ifndef SQLITE_OMIT_VIEW
1324 }else{
1325 /* A view */
1326 /* sqlite3VdbeAddOp(v, OP_Integer, 0, 0); */
1327 zType = "view";
1328 zType2 = "VIEW";
1329 #endif
1332 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1333 ** statement to populate the new table. The root-page number for the
1334 ** new table is on the top of the vdbe stack.
1336 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1337 ** suitable state to query for the column names and types to be used
1338 ** by the new table.
1340 if( pSelect ){
1341 Table *pSelTab;
1342 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1343 sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
1344 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1345 pParse->nTab = 2;
1346 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
1347 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1348 if( pParse->nErr==0 ){
1349 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1350 if( pSelTab==0 ) return;
1351 assert( p->aCol==0 );
1352 p->nCol = pSelTab->nCol;
1353 p->aCol = pSelTab->aCol;
1354 pSelTab->nCol = 0;
1355 pSelTab->aCol = 0;
1356 sqlite3DeleteTable(0, pSelTab);
1360 /* Compute the complete text of the CREATE statement */
1361 if( pSelect ){
1362 zStmt = createTableStmt(p);
1363 }else{
1364 n = pEnd->z - pParse->sNameToken.z + 1;
1365 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1368 /* A slot for the record has already been allocated in the
1369 ** SQLITE_MASTER table. We just need to update that slot with all
1370 ** the information we've collected. The rowid for the preallocated
1371 ** slot is the 2nd item on the stack. The top of the stack is the
1372 ** root page for the new table (or a 0 if this is a view).
1374 sqlite3NestedParse(pParse,
1375 "UPDATE %Q.%s "
1376 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1377 "WHERE rowid=#1",
1378 db->aDb[p->iDb].zName, SCHEMA_TABLE(p->iDb),
1379 zType,
1380 p->zName,
1381 p->zName,
1382 zStmt
1384 sqliteFree(zStmt);
1385 sqlite3ChangeCookie(db, v, p->iDb);
1387 #ifndef SQLITE_OMIT_AUTOINCREMENT
1388 /* Check to see if we need to create an sqlite_sequence table for
1389 ** keeping track of autoincrement keys.
1391 if( p->autoInc ){
1392 Db *pDb = &db->aDb[p->iDb];
1393 if( pDb->pSeqTab==0 ){
1394 sqlite3NestedParse(pParse,
1395 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1396 pDb->zName
1400 #endif
1402 /* Reparse everything to update our internal data structures */
1403 sqlite3VdbeOp3(v, OP_ParseSchema, p->iDb, 0,
1404 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
1408 /* Add the table to the in-memory representation of the database.
1410 if( db->init.busy && pParse->nErr==0 ){
1411 Table *pOld;
1412 FKey *pFKey;
1413 Db *pDb = &db->aDb[p->iDb];
1414 pOld = sqlite3HashInsert(&pDb->tblHash, p->zName, strlen(p->zName)+1, p);
1415 if( pOld ){
1416 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1417 return;
1419 #ifndef SQLITE_OMIT_FOREIGN_KEY
1420 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1421 int nTo = strlen(pFKey->zTo) + 1;
1422 pFKey->pNextTo = sqlite3HashFind(&pDb->aFKey, pFKey->zTo, nTo);
1423 sqlite3HashInsert(&pDb->aFKey, pFKey->zTo, nTo, pFKey);
1425 #endif
1426 pParse->pNewTable = 0;
1427 db->nTable++;
1428 db->flags |= SQLITE_InternChanges;
1430 #ifndef SQLITE_OMIT_ALTERTABLE
1431 if( !p->pSelect ){
1432 assert( !pSelect && pCons && pEnd );
1433 if( pCons->z==0 ) pCons = pEnd;
1434 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z);
1436 #endif
1440 #ifndef SQLITE_OMIT_VIEW
1442 ** The parser calls this routine in order to create a new VIEW
1444 void sqlite3CreateView(
1445 Parse *pParse, /* The parsing context */
1446 Token *pBegin, /* The CREATE token that begins the statement */
1447 Token *pName1, /* The token that holds the name of the view */
1448 Token *pName2, /* The token that holds the name of the view */
1449 Select *pSelect, /* A SELECT statement that will become the new view */
1450 int isTemp /* TRUE for a TEMPORARY view */
1452 Table *p;
1453 int n;
1454 const unsigned char *z;
1455 Token sEnd;
1456 DbFixer sFix;
1457 Token *pName;
1459 if( pParse->nVar>0 ){
1460 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1461 sqlite3SelectDelete(pSelect);
1462 return;
1464 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1);
1465 p = pParse->pNewTable;
1466 if( p==0 || pParse->nErr ){
1467 sqlite3SelectDelete(pSelect);
1468 return;
1470 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1471 if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName)
1472 && sqlite3FixSelect(&sFix, pSelect)
1474 sqlite3SelectDelete(pSelect);
1475 return;
1478 /* Make a copy of the entire SELECT statement that defines the view.
1479 ** This will force all the Expr.token.z values to be dynamically
1480 ** allocated rather than point to the input string - which means that
1481 ** they will persist after the current sqlite3_exec() call returns.
1483 p->pSelect = sqlite3SelectDup(pSelect);
1484 sqlite3SelectDelete(pSelect);
1485 if( !pParse->db->init.busy ){
1486 sqlite3ViewGetColumnNames(pParse, p);
1489 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1490 ** the end.
1492 sEnd = pParse->sLastToken;
1493 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1494 sEnd.z += sEnd.n;
1496 sEnd.n = 0;
1497 n = sEnd.z - pBegin->z;
1498 z = (const unsigned char*)pBegin->z;
1499 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1500 sEnd.z = &z[n-1];
1501 sEnd.n = 1;
1503 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1504 sqlite3EndTable(pParse, 0, &sEnd, 0);
1505 return;
1507 #endif /* SQLITE_OMIT_VIEW */
1509 #ifndef SQLITE_OMIT_VIEW
1511 ** The Table structure pTable is really a VIEW. Fill in the names of
1512 ** the columns of the view in the pTable structure. Return the number
1513 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
1515 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1516 Table *pSelTab; /* A fake table from which we get the result set */
1517 Select *pSel; /* Copy of the SELECT that implements the view */
1518 int nErr = 0; /* Number of errors encountered */
1519 int n; /* Temporarily holds the number of cursors assigned */
1521 assert( pTable );
1523 /* A positive nCol means the columns names for this view are
1524 ** already known.
1526 if( pTable->nCol>0 ) return 0;
1528 /* A negative nCol is a special marker meaning that we are currently
1529 ** trying to compute the column names. If we enter this routine with
1530 ** a negative nCol, it means two or more views form a loop, like this:
1532 ** CREATE VIEW one AS SELECT * FROM two;
1533 ** CREATE VIEW two AS SELECT * FROM one;
1535 ** Actually, this error is caught previously and so the following test
1536 ** should always fail. But we will leave it in place just to be safe.
1538 if( pTable->nCol<0 ){
1539 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1540 return 1;
1543 /* If we get this far, it means we need to compute the table names.
1544 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1545 ** "*" elements in the results set of the view and will assign cursors
1546 ** to the elements of the FROM clause. But we do not want these changes
1547 ** to be permanent. So the computation is done on a copy of the SELECT
1548 ** statement that defines the view.
1550 assert( pTable->pSelect );
1551 pSel = sqlite3SelectDup(pTable->pSelect);
1552 n = pParse->nTab;
1553 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1554 pTable->nCol = -1;
1555 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1556 pParse->nTab = n;
1557 if( pSelTab ){
1558 assert( pTable->aCol==0 );
1559 pTable->nCol = pSelTab->nCol;
1560 pTable->aCol = pSelTab->aCol;
1561 pSelTab->nCol = 0;
1562 pSelTab->aCol = 0;
1563 sqlite3DeleteTable(0, pSelTab);
1564 DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
1565 }else{
1566 pTable->nCol = 0;
1567 nErr++;
1569 sqlite3SelectDelete(pSel);
1570 return nErr;
1572 #endif /* SQLITE_OMIT_VIEW */
1574 #ifndef SQLITE_OMIT_VIEW
1576 ** Clear the column names from every VIEW in database idx.
1578 static void sqliteViewResetAll(sqlite3 *db, int idx){
1579 HashElem *i;
1580 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1581 for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
1582 Table *pTab = sqliteHashData(i);
1583 if( pTab->pSelect ){
1584 sqliteResetColumnNames(pTab);
1587 DbClearProperty(db, idx, DB_UnresetViews);
1589 #else
1590 # define sqliteViewResetAll(A,B)
1591 #endif /* SQLITE_OMIT_VIEW */
1594 ** This function is called by the VDBE to adjust the internal schema
1595 ** used by SQLite when the btree layer moves a table root page. The
1596 ** root-page of a table or index in database iDb has changed from iFrom
1597 ** to iTo.
1599 #ifndef SQLITE_OMIT_AUTOVACUUM
1600 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1601 HashElem *pElem;
1603 for(pElem=sqliteHashFirst(&pDb->tblHash); pElem; pElem=sqliteHashNext(pElem)){
1604 Table *pTab = sqliteHashData(pElem);
1605 if( pTab->tnum==iFrom ){
1606 pTab->tnum = iTo;
1607 return;
1610 for(pElem=sqliteHashFirst(&pDb->idxHash); pElem; pElem=sqliteHashNext(pElem)){
1611 Index *pIdx = sqliteHashData(pElem);
1612 if( pIdx->tnum==iFrom ){
1613 pIdx->tnum = iTo;
1614 return;
1617 assert(0);
1619 #endif
1622 ** Write code to erase the table with root-page iTable from database iDb.
1623 ** Also write code to modify the sqlite_master table and internal schema
1624 ** if a root-page of another table is moved by the btree-layer whilst
1625 ** erasing iTable (this can happen with an auto-vacuum database).
1627 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1628 Vdbe *v = sqlite3GetVdbe(pParse);
1629 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1630 #ifndef SQLITE_OMIT_AUTOVACUUM
1631 /* OP_Destroy pushes an integer onto the stack. If this integer
1632 ** is non-zero, then it is the root page number of a table moved to
1633 ** location iTable. The following code modifies the sqlite_master table to
1634 ** reflect this.
1636 ** The "#0" in the SQL is a special constant that means whatever value
1637 ** is on the top of the stack. See sqlite3RegisterExpr().
1639 sqlite3NestedParse(pParse,
1640 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
1641 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
1642 #endif
1646 ** Write VDBE code to erase table pTab and all associated indices on disk.
1647 ** Code to update the sqlite_master tables and internal schema definitions
1648 ** in case a root-page belonging to another table is moved by the btree layer
1649 ** is also added (this can happen with an auto-vacuum database).
1651 static void destroyTable(Parse *pParse, Table *pTab){
1652 #ifdef SQLITE_OMIT_AUTOVACUUM
1653 Index *pIdx;
1654 destroyRootPage(pParse, pTab->tnum, pTab->iDb);
1655 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1656 destroyRootPage(pParse, pIdx->tnum, pIdx->iDb);
1658 #else
1659 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1660 ** is not defined), then it is important to call OP_Destroy on the
1661 ** table and index root-pages in order, starting with the numerically
1662 ** largest root-page number. This guarantees that none of the root-pages
1663 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1664 ** following were coded:
1666 ** OP_Destroy 4 0
1667 ** ...
1668 ** OP_Destroy 5 0
1670 ** and root page 5 happened to be the largest root-page number in the
1671 ** database, then root page 5 would be moved to page 4 by the
1672 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1673 ** a free-list page.
1675 int iTab = pTab->tnum;
1676 int iDestroyed = 0;
1678 while( 1 ){
1679 Index *pIdx;
1680 int iLargest = 0;
1682 if( iDestroyed==0 || iTab<iDestroyed ){
1683 iLargest = iTab;
1685 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1686 int iIdx = pIdx->tnum;
1687 assert( pIdx->iDb==pTab->iDb );
1688 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1689 iLargest = iIdx;
1692 if( iLargest==0 ) return;
1693 destroyRootPage(pParse, iLargest, pTab->iDb);
1694 iDestroyed = iLargest;
1696 #endif
1700 ** This routine is called to do the work of a DROP TABLE statement.
1701 ** pName is the name of the table to be dropped.
1703 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
1704 Table *pTab;
1705 Vdbe *v;
1706 sqlite3 *db = pParse->db;
1707 int iDb;
1709 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
1710 assert( pName->nSrc==1 );
1711 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1713 if( pTab==0 ) goto exit_drop_table;
1714 iDb = pTab->iDb;
1715 assert( iDb>=0 && iDb<db->nDb );
1716 #ifndef SQLITE_OMIT_AUTHORIZATION
1718 int code;
1719 const char *zTab = SCHEMA_TABLE(pTab->iDb);
1720 const char *zDb = db->aDb[pTab->iDb].zName;
1721 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
1722 goto exit_drop_table;
1724 if( isView ){
1725 if( !OMIT_TEMPDB && iDb==1 ){
1726 code = SQLITE_DROP_TEMP_VIEW;
1727 }else{
1728 code = SQLITE_DROP_VIEW;
1730 }else{
1731 if( !OMIT_TEMPDB && iDb==1 ){
1732 code = SQLITE_DROP_TEMP_TABLE;
1733 }else{
1734 code = SQLITE_DROP_TABLE;
1737 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1738 goto exit_drop_table;
1740 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1741 goto exit_drop_table;
1744 #endif
1745 if( pTab->readOnly || pTab==db->aDb[iDb].pSeqTab ){
1746 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
1747 goto exit_drop_table;
1750 #ifndef SQLITE_OMIT_VIEW
1751 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1752 ** on a table.
1754 if( isView && pTab->pSelect==0 ){
1755 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1756 goto exit_drop_table;
1758 if( !isView && pTab->pSelect ){
1759 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1760 goto exit_drop_table;
1762 #endif
1764 /* Generate code to remove the table from the master table
1765 ** on disk.
1767 v = sqlite3GetVdbe(pParse);
1768 if( v ){
1769 Trigger *pTrigger;
1770 int iDb = pTab->iDb;
1771 Db *pDb = &db->aDb[iDb];
1772 sqlite3BeginWriteOperation(pParse, 0, iDb);
1774 /* Drop all triggers associated with the table being dropped. Code
1775 ** is generated to remove entries from sqlite_master and/or
1776 ** sqlite_temp_master if required.
1778 pTrigger = pTab->pTrigger;
1779 while( pTrigger ){
1780 assert( pTrigger->iDb==iDb || pTrigger->iDb==1 );
1781 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
1782 pTrigger = pTrigger->pNext;
1785 #ifndef SQLITE_OMIT_AUTOINCREMENT
1786 /* Remove any entries of the sqlite_sequence table associated with
1787 ** the table being dropped. This is done before the table is dropped
1788 ** at the btree level, in case the sqlite_sequence table needs to
1789 ** move as a result of the drop (can happen in auto-vacuum mode).
1791 if( pTab->autoInc ){
1792 sqlite3NestedParse(pParse,
1793 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1794 pDb->zName, pTab->zName
1797 #endif
1799 /* Drop all SQLITE_MASTER table and index entries that refer to the
1800 ** table. The program name loops through the master table and deletes
1801 ** every row that refers to a table of the same name as the one being
1802 ** dropped. Triggers are handled seperately because a trigger can be
1803 ** created in the temp database that refers to a table in another
1804 ** database.
1806 sqlite3NestedParse(pParse,
1807 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
1808 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
1809 if( !isView ){
1810 destroyTable(pParse, pTab);
1813 /* Remove the table entry from SQLite's internal schema and modify
1814 ** the schema cookie.
1816 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
1817 sqlite3ChangeCookie(db, v, iDb);
1819 sqliteViewResetAll(db, iDb);
1821 exit_drop_table:
1822 sqlite3SrcListDelete(pName);
1826 ** This routine is called to create a new foreign key on the table
1827 ** currently under construction. pFromCol determines which columns
1828 ** in the current table point to the foreign key. If pFromCol==0 then
1829 ** connect the key to the last column inserted. pTo is the name of
1830 ** the table referred to. pToCol is a list of tables in the other
1831 ** pTo table that the foreign key points to. flags contains all
1832 ** information about the conflict resolution algorithms specified
1833 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1835 ** An FKey structure is created and added to the table currently
1836 ** under construction in the pParse->pNewTable field. The new FKey
1837 ** is not linked into db->aFKey at this point - that does not happen
1838 ** until sqlite3EndTable().
1840 ** The foreign key is set for IMMEDIATE processing. A subsequent call
1841 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
1843 void sqlite3CreateForeignKey(
1844 Parse *pParse, /* Parsing context */
1845 ExprList *pFromCol, /* Columns in this table that point to other table */
1846 Token *pTo, /* Name of the other table */
1847 ExprList *pToCol, /* Columns in the other table */
1848 int flags /* Conflict resolution algorithms. */
1850 #ifndef SQLITE_OMIT_FOREIGN_KEY
1851 FKey *pFKey = 0;
1852 Table *p = pParse->pNewTable;
1853 int nByte;
1854 int i;
1855 int nCol;
1856 char *z;
1858 assert( pTo!=0 );
1859 if( p==0 || pParse->nErr ) goto fk_end;
1860 if( pFromCol==0 ){
1861 int iCol = p->nCol-1;
1862 if( iCol<0 ) goto fk_end;
1863 if( pToCol && pToCol->nExpr!=1 ){
1864 sqlite3ErrorMsg(pParse, "foreign key on %s"
1865 " should reference only one column of table %T",
1866 p->aCol[iCol].zName, pTo);
1867 goto fk_end;
1869 nCol = 1;
1870 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
1871 sqlite3ErrorMsg(pParse,
1872 "number of columns in foreign key does not match the number of "
1873 "columns in the referenced table");
1874 goto fk_end;
1875 }else{
1876 nCol = pFromCol->nExpr;
1878 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1879 if( pToCol ){
1880 for(i=0; i<pToCol->nExpr; i++){
1881 nByte += strlen(pToCol->a[i].zName) + 1;
1884 pFKey = sqliteMalloc( nByte );
1885 if( pFKey==0 ) goto fk_end;
1886 pFKey->pFrom = p;
1887 pFKey->pNextFrom = p->pFKey;
1888 z = (char*)&pFKey[1];
1889 pFKey->aCol = (struct sColMap*)z;
1890 z += sizeof(struct sColMap)*nCol;
1891 pFKey->zTo = z;
1892 memcpy(z, pTo->z, pTo->n);
1893 z[pTo->n] = 0;
1894 z += pTo->n+1;
1895 pFKey->pNextTo = 0;
1896 pFKey->nCol = nCol;
1897 if( pFromCol==0 ){
1898 pFKey->aCol[0].iFrom = p->nCol-1;
1899 }else{
1900 for(i=0; i<nCol; i++){
1901 int j;
1902 for(j=0; j<p->nCol; j++){
1903 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
1904 pFKey->aCol[i].iFrom = j;
1905 break;
1908 if( j>=p->nCol ){
1909 sqlite3ErrorMsg(pParse,
1910 "unknown column \"%s\" in foreign key definition",
1911 pFromCol->a[i].zName);
1912 goto fk_end;
1916 if( pToCol ){
1917 for(i=0; i<nCol; i++){
1918 int n = strlen(pToCol->a[i].zName);
1919 pFKey->aCol[i].zCol = z;
1920 memcpy(z, pToCol->a[i].zName, n);
1921 z[n] = 0;
1922 z += n+1;
1925 pFKey->isDeferred = 0;
1926 pFKey->deleteConf = flags & 0xff;
1927 pFKey->updateConf = (flags >> 8 ) & 0xff;
1928 pFKey->insertConf = (flags >> 16 ) & 0xff;
1930 /* Link the foreign key to the table as the last step.
1932 p->pFKey = pFKey;
1933 pFKey = 0;
1935 fk_end:
1936 sqliteFree(pFKey);
1937 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1938 sqlite3ExprListDelete(pFromCol);
1939 sqlite3ExprListDelete(pToCol);
1943 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
1944 ** clause is seen as part of a foreign key definition. The isDeferred
1945 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
1946 ** The behavior of the most recently created foreign key is adjusted
1947 ** accordingly.
1949 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
1950 #ifndef SQLITE_OMIT_FOREIGN_KEY
1951 Table *pTab;
1952 FKey *pFKey;
1953 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
1954 pFKey->isDeferred = isDeferred;
1955 #endif
1959 ** Generate code that will erase and refill index *pIdx. This is
1960 ** used to initialize a newly created index or to recompute the
1961 ** content of an index in response to a REINDEX command.
1963 ** if memRootPage is not negative, it means that the index is newly
1964 ** created. The memory cell specified by memRootPage contains the
1965 ** root page number of the index. If memRootPage is negative, then
1966 ** the index already exists and must be cleared before being refilled and
1967 ** the root page number of the index is taken from pIndex->tnum.
1969 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
1970 Table *pTab = pIndex->pTable; /* The table that is indexed */
1971 int iTab = pParse->nTab; /* Btree cursor used for pTab */
1972 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
1973 int addr1; /* Address of top of loop */
1974 int tnum; /* Root page of index */
1975 Vdbe *v; /* Generate code into this virtual machine */
1976 int isUnique; /* True for a unique index */
1978 #ifndef SQLITE_OMIT_AUTHORIZATION
1979 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
1980 pParse->db->aDb[pIndex->iDb].zName ) ){
1981 return;
1983 #endif
1985 /* Ensure all the required collation sequences are available. This
1986 ** routine will invoke the collation-needed callback if necessary (and
1987 ** if one has been registered).
1989 if( sqlite3CheckIndexCollSeq(pParse, pIndex) ){
1990 return;
1993 v = sqlite3GetVdbe(pParse);
1994 if( v==0 ) return;
1995 if( memRootPage>=0 ){
1996 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
1997 tnum = 0;
1998 }else{
1999 tnum = pIndex->tnum;
2000 sqlite3VdbeAddOp(v, OP_Clear, tnum, pIndex->iDb);
2002 sqlite3VdbeAddOp(v, OP_Integer, pIndex->iDb, 0);
2003 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum,
2004 (char*)&pIndex->keyInfo, P3_KEYINFO);
2005 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
2006 sqlite3VdbeAddOp(v, OP_OpenRead, iTab, pTab->tnum);
2007 sqlite3VdbeAddOp(v, OP_SetNumColumns, iTab, pTab->nCol);
2008 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2009 sqlite3GenerateIndexKey(v, pIndex, iTab);
2010 isUnique = pIndex->onError!=OE_None;
2011 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, isUnique);
2012 if( isUnique ){
2013 sqlite3VdbeChangeP3(v, -1, "indexed columns are not unique", P3_STATIC);
2015 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
2016 sqlite3VdbeChangeP2(v, addr1, sqlite3VdbeCurrentAddr(v));
2017 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2018 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2022 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2023 ** and pTblList is the name of the table that is to be indexed. Both will
2024 ** be NULL for a primary key or an index that is created to satisfy a
2025 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2026 ** as the table to be indexed. pParse->pNewTable is a table that is
2027 ** currently being constructed by a CREATE TABLE statement.
2029 ** pList is a list of columns to be indexed. pList will be NULL if this
2030 ** is a primary key or unique-constraint on the most recent column added
2031 ** to the table currently under construction.
2033 void sqlite3CreateIndex(
2034 Parse *pParse, /* All information about this parse */
2035 Token *pName1, /* First part of index name. May be NULL */
2036 Token *pName2, /* Second part of index name. May be NULL */
2037 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2038 ExprList *pList, /* A list of columns to be indexed */
2039 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2040 Token *pStart, /* The CREATE token that begins a CREATE TABLE
2041 statement */
2042 Token *pEnd /* The ")" that closes the CREATE INDEX statement */
2045 Table *pTab = NULL; /* Table to be indexed */
2046 Index *pIndex = NULL; /* The index to be created */
2047 STRPTR zName = NULL;
2048 int i, j;
2049 Token nullId; /* Fake token for an empty ID list */
2050 DbFixer sFix; /* For assigning database names to pTable */
2051 sqlite3 *db = pParse->db;
2052 int iDb; /* Index of the database that is being written */
2053 Token *pName = NULL; /* Unqualified name of the index to create */
2055 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
2058 * Find the table that is to be indexed. Return early if not found.
2059 * */
2060 if( pTblName )
2063 * Use the two-part index name to determine the database to search for
2064 * the table. 'Fix' the table name to this db before looking up the
2065 * table.
2066 * */
2067 assert( pName1 && pName2 );
2068 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2069 if( iDb < 0 ) goto exit_create_index;
2071 #ifndef SQLITE_OMIT_TEMPDB
2073 * If the index name was unqualified, check if the the table is a temp
2074 * table. If so, set the database to 1.
2075 * */
2076 pTab = sqlite3SrcListLookup(pParse, pTblName);
2077 if( pName2 && !pName2->n && pTab && pTab->iDb == 1 )
2078 iDb = 1;
2079 #endif
2081 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName)
2082 && sqlite3FixSrcList(&sFix, pTblName))
2083 goto exit_create_index;
2085 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2086 pTblName->a[0].zDatabase);
2087 if( !pTab ) goto exit_create_index;
2088 assert( iDb==pTab->iDb );
2090 else
2092 assert( !pName );
2093 pTab = pParse->pNewTable;
2094 iDb = pTab->iDb;
2097 if( pTab==0 || pParse->nErr ) goto exit_create_index;
2098 if( pTab->readOnly )
2100 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2101 goto exit_create_index;
2103 #ifndef SQLITE_OMIT_VIEW
2104 if( pTab->pSelect )
2106 sqlite3ErrorMsg(pParse, "views may not be indexed");
2107 goto exit_create_index;
2109 #endif
2112 * Find the name of the index. Make sure there is not already another index
2113 * or table with the same name.
2115 * Exception: If we are reading the names of permanent indices from the
2116 * sqlite_master table (because some other process changed the schema) and
2117 * one of the index names collides with the name of a temporary table or
2118 * index, then we will continue to process this index.
2120 * If pName==0 it means that we are dealing with a primary key or UNIQUE
2121 * constraint. We have to invent our own name.
2122 * */
2123 if( pName )
2125 zName = sqlite3NameFromToken(pName);
2126 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
2127 if( zName==0 ) goto exit_create_index;
2128 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) )
2129 goto exit_create_index;
2131 if( !db->init.busy )
2133 Index *pISameName; /* Another index with the same name */
2134 Table *pTSameName; /* A table with same name as the index */
2135 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
2136 if( (pISameName = sqlite3FindIndex(db, zName, db->aDb[iDb].zName)))
2138 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2139 goto exit_create_index;
2141 if( (pTSameName = sqlite3FindTable(db, zName, 0))!=0 )
2143 sqlite3ErrorMsg( pParse,
2144 "there is already a table named %s", zName);
2145 goto exit_create_index;
2149 else
2151 char zBuf[30];
2152 int n;
2153 Index *pLoop;
2154 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2155 sprintf(zBuf,"_%d",n);
2156 zName = NULL;
2157 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, NULL);
2158 if( !zName ) goto exit_create_index;
2161 /* Check for authorization to create an index. */
2162 #ifndef SQLITE_OMIT_AUTHORIZATION
2164 const char *zDb = db->aDb[iDb].zName;
2165 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb),0,zDb) )
2166 goto exit_create_index;
2167 i = SQLITE_CREATE_INDEX;
2168 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2169 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) )
2170 goto exit_create_index;
2172 #endif
2175 * If pList==0, it means this routine was called to make a primary key out
2176 * of the last column added to the table under construction. So create
2177 * a fake list to simulate this.
2178 * */
2179 if( !pList )
2181 nullId.z = pTab->aCol[pTab->nCol-1].zName;
2182 nullId.n = strlen(nullId.z);
2183 pList = sqlite3ExprListAppend(0, 0, &nullId);
2184 if( !pList ) goto exit_create_index;
2188 * Allocate the index structure.
2189 * */
2190 pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
2191 (sizeof(int) + sizeof(CollSeq*))*pList->nExpr );
2192 if( sqlite3_malloc_failed ) goto exit_create_index;
2193 pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
2194 pIndex->zName = (STRPTR)&pIndex->aiColumn[pList->nExpr];
2195 strcpy(pIndex->zName, zName);
2196 pIndex->pTable = pTab;
2197 pIndex->nColumn = pList->nExpr;
2198 pIndex->onError = onError;
2199 pIndex->autoIndex = pName==0;
2200 pIndex->iDb = iDb;
2203 * Scan the names of the columns of the table to be indexed and load the
2204 * column indices into the Index structure. Report an error if any column
2205 * is not found.
2206 * */
2207 for(i=0; i<pList->nExpr; i++)
2209 for(j=0; j<pTab->nCol; j++)
2210 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 )
2211 break;
2212 if( j>=pTab->nCol )
2214 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2215 pTab->zName, pList->a[i].zName);
2216 goto exit_create_index;
2218 pIndex->aiColumn[i] = j;
2219 if( pList->a[i].pExpr )
2221 assert( pList->a[i].pExpr->pColl );
2222 pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl;
2224 else pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl;
2225 assert( pIndex->keyInfo.aColl[i] );
2226 if( !db->init.busy
2227 && sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i]) )
2228 goto exit_create_index;
2230 pIndex->keyInfo.nField = pList->nExpr;
2232 if( pTab==pParse->pNewTable )
2235 * This routine has been called to create an automatic index as a
2236 * result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2237 * a PRIMARY KEY or UNIQUE clause following the column definitions.
2238 * i.e. one of:
2240 * CREATE TABLE t(x PRIMARY KEY, y);
2241 * CREATE TABLE t(x, y, UNIQUE(x, y));
2243 * Either way, check to see if the table already has such an index. If
2244 * so, don't bother creating this one. This only applies to
2245 * automatically created indices. Users can do as they wish with
2246 * explicit indices.
2247 * */
2248 Index *pIdx;
2249 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext)
2251 int k;
2252 assert( pIdx->onError != OE_None );
2253 assert( pIdx->autoIndex );
2254 assert( pIndex->onError != OE_None );
2256 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2257 for(k=0; k < pIdx->nColumn; k++)
2259 if( pIdx->aiColumn[k] != pIndex->aiColumn[k] ) break;
2260 if( pIdx->keyInfo.aColl[k]!=pIndex->keyInfo.aColl[k] ) break;
2262 if( k==pIdx->nColumn )
2264 if( pIdx->onError!=pIndex->onError )
2267 * This constraint creates the same index as a previous
2268 * constraint specified somewhere in the CREATE TABLE
2269 * statement. However the ON CONFLICT clauses are
2270 * different. If both this constraint and the previous
2271 * equivalent constraint have explicit ON CONFLICT clauses
2272 * this is an error. Otherwise, use the explicitly
2273 * specified behaviour for the index.
2274 * */
2275 if( !(pIdx->onError==OE_Default
2276 || pIndex->onError==OE_Default) )
2278 sqlite3ErrorMsg(pParse,
2279 "conflicting ON CONFLICT clauses specified",
2282 if( pIdx->onError==OE_Default )
2283 pIdx->onError = pIndex->onError;
2285 goto exit_create_index;
2291 * Link the new Index structure to its table and to the other in-memory
2292 * database structures.
2293 * */
2294 if( db->init.busy )
2296 Index *p;
2297 p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash,
2298 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
2299 if( p )
2301 assert( p==pIndex ); /* Malloc must have failed */
2302 goto exit_create_index;
2304 db->flags |= SQLITE_InternChanges;
2305 if( pTblName )
2306 pIndex->tnum = db->init.newTnum;
2309 * If the db->init.busy is 0 then create the index on disk. This involves
2310 * writing the index into the master table and filling in the index with
2311 * the current table contents.
2313 * The db->init.busy is 0 when the user first enters a CREATE INDEX
2314 * command. db->init.busy is 1 when a database is opened and CREATE INDEX
2315 * statements are read out of the master table. In the latter case the
2316 * index already exists on disk, which is why we don't want to recreate it.
2318 * If pTblName==0 it means this index is generated as a primary key or
2319 * UNIQUE constraint of a CREATE TABLE statement. Since the table has just
2320 * been created, it contains no data and the index initialization step can
2321 * be skipped.
2322 * */
2323 else if( db->init.busy==0 )
2325 Vdbe *v;
2326 char *zStmt;
2327 int iMem = pParse->nMem++;
2329 v = sqlite3GetVdbe(pParse);
2330 if( v==0 ) goto exit_create_index;
2332 /* Create the rootpage for the index */
2333 sqlite3BeginWriteOperation(pParse, 1, iDb);
2334 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
2335 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2338 * Gather the complete text of the CREATE INDEX statement into the
2339 * zStmt variable.
2340 * */
2341 if( pStart && pEnd )
2342 /* A named index with an explicit CREATE INDEX statement */
2343 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
2344 onError==OE_None ? "" : " UNIQUE",
2345 pEnd->z - pName->z + 1,
2346 pName->z);
2347 else
2349 /* An automatic index created by a PRIMARY KEY or UNIQUE
2350 * constraint */
2351 /* zStmt = sqlite3MPrintf(""); */
2352 zStmt = 0;
2355 /* Add an entry in sqlite_master for this index */
2356 sqlite3NestedParse(pParse,
2357 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
2358 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2359 pIndex->zName, pTab->zName, zStmt );
2360 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2361 sqliteFree(zStmt);
2364 * Fill the index with data and reparse the schema. Code an OP_Expire
2365 * to invalidate all pre-compiled statements.
2366 * */
2367 if( pTblName )
2369 sqlite3RefillIndex(pParse, pIndex, iMem);
2370 sqlite3ChangeCookie(db, v, iDb);
2371 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2372 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
2373 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
2378 * When adding an index to the list of indices for a table, make sure all
2379 * indices labeled OE_Replace come after all those labeled OE_Ignore. This
2380 * is necessary for the correct operation of UPDATE and INSERT.
2381 * */
2382 if( db->init.busy || pTblName==0 )
2384 if( onError!=OE_Replace || pTab->pIndex==0
2385 || pTab->pIndex->onError==OE_Replace)
2387 pIndex->pNext = pTab->pIndex;
2388 pTab->pIndex = pIndex;
2390 else
2392 Index *pOther = pTab->pIndex;
2393 while( pOther->pNext && pOther->pNext->onError!=OE_Replace )
2394 pOther = pOther->pNext;
2395 pIndex->pNext = pOther->pNext;
2396 pOther->pNext = pIndex;
2398 pIndex = 0;
2401 /* Clean up before exiting */
2402 exit_create_index:
2403 if( pIndex )
2404 freeIndex(pIndex);
2405 sqlite3ExprListDelete(pList);
2406 sqlite3SrcListDelete(pTblName);
2407 sqliteFree(zName);
2412 * This routine will drop an existing named index. This routine implements the
2413 * DROP INDEX statement.
2414 * */
2415 void sqlite3DropIndex(Parse *pParse, SrcList *pName)
2417 Index *pIndex;
2418 Vdbe *v;
2419 sqlite3 *db = pParse->db;
2421 if( pParse->nErr || sqlite3_malloc_failed )
2422 goto exit_drop_index;
2424 assert( pName->nSrc==1 );
2425 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2426 goto exit_drop_index;
2428 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2429 if( pIndex==0 ){
2430 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2431 pParse->checkSchema = 1;
2432 goto exit_drop_index;
2434 if( pIndex->autoIndex ){
2435 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
2436 "or PRIMARY KEY constraint cannot be dropped", 0);
2437 goto exit_drop_index;
2439 #ifndef SQLITE_OMIT_AUTHORIZATION
2441 int code = SQLITE_DROP_INDEX;
2442 Table *pTab = pIndex->pTable;
2443 const char *zDb = db->aDb[pIndex->iDb].zName;
2444 const char *zTab = SCHEMA_TABLE(pIndex->iDb);
2445 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
2446 goto exit_drop_index;
2448 if( !OMIT_TEMPDB && pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
2449 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
2450 goto exit_drop_index;
2453 #endif
2455 /* Generate code to remove the index and from the master table */
2456 v = sqlite3GetVdbe(pParse);
2457 if( v ){
2458 int iDb = pIndex->iDb;
2459 sqlite3NestedParse(pParse,
2460 "DELETE FROM %Q.%s WHERE name=%Q",
2461 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2462 pIndex->zName
2464 sqlite3ChangeCookie(db, v, iDb);
2465 destroyRootPage(pParse, pIndex->tnum, iDb);
2466 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
2469 exit_drop_index:
2470 sqlite3SrcListDelete(pName);
2474 ** Append a new element to the given IdList. Create a new IdList if
2475 ** need be.
2477 ** A new IdList is returned, or NULL if malloc() fails.
2479 IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
2480 if( pList==0 ){
2481 pList = sqliteMalloc( sizeof(IdList) );
2482 if( pList==0 ) return 0;
2483 pList->nAlloc = 0;
2485 if( pList->nId>=pList->nAlloc ){
2486 struct IdList_item *a;
2487 pList->nAlloc = pList->nAlloc*2 + 5;
2488 a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
2489 if( a==0 ){
2490 sqlite3IdListDelete(pList);
2491 return 0;
2493 pList->a = a;
2495 memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
2496 pList->a[pList->nId].zName = sqlite3NameFromToken(pToken);
2497 pList->nId++;
2498 return pList;
2502 ** Append a new table name to the given SrcList. Create a new SrcList if
2503 ** need be. A new entry is created in the SrcList even if pToken is NULL.
2505 ** A new SrcList is returned, or NULL if malloc() fails.
2507 ** If pDatabase is not null, it means that the table has an optional
2508 ** database name prefix. Like this: "database.table". The pDatabase
2509 ** points to the table name and the pTable points to the database name.
2510 ** The SrcList.a[].zName field is filled with the table name which might
2511 ** come from pTable (if pDatabase is NULL) or from pDatabase.
2512 ** SrcList.a[].zDatabase is filled with the database name from pTable,
2513 ** or with NULL if no database is specified.
2515 ** In other words, if call like this:
2517 ** sqlite3SrcListAppend(A,B,0);
2519 ** Then B is a table name and the database name is unspecified. If called
2520 ** like this:
2522 ** sqlite3SrcListAppend(A,B,C);
2524 ** Then C is the table name and B is the database name.
2526 SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
2527 struct SrcList_item *pItem;
2528 if( pList==0 ){
2529 pList = sqliteMalloc( sizeof(SrcList) );
2530 if( pList==0 ) return 0;
2531 pList->nAlloc = 1;
2533 if( pList->nSrc>=pList->nAlloc ){
2534 SrcList *pNew;
2535 pList->nAlloc *= 2;
2536 pNew = sqliteRealloc(pList,
2537 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
2538 if( pNew==0 ){
2539 sqlite3SrcListDelete(pList);
2540 return 0;
2542 pList = pNew;
2544 pItem = &pList->a[pList->nSrc];
2545 memset(pItem, 0, sizeof(pList->a[0]));
2546 if( pDatabase && pDatabase->z==0 ){
2547 pDatabase = 0;
2549 if( pDatabase && pTable ){
2550 Token *pTemp = pDatabase;
2551 pDatabase = pTable;
2552 pTable = pTemp;
2554 pItem->zName = sqlite3NameFromToken(pTable);
2555 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2556 pItem->iCursor = -1;
2557 pList->nSrc++;
2558 return pList;
2562 ** Assign cursors to all tables in a SrcList
2564 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
2565 int i;
2566 struct SrcList_item *pItem;
2567 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2568 if( pItem->iCursor>=0 ) break;
2569 pItem->iCursor = pParse->nTab++;
2570 if( pItem->pSelect ){
2571 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
2577 ** Add an alias to the last identifier on the given identifier list.
2579 void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
2580 if( pList && pList->nSrc>0 ){
2581 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
2586 ** Delete an IdList.
2588 void sqlite3IdListDelete(IdList *pList){
2589 int i;
2590 if( pList==0 ) return;
2591 for(i=0; i<pList->nId; i++){
2592 sqliteFree(pList->a[i].zName);
2594 sqliteFree(pList->a);
2595 sqliteFree(pList);
2599 ** Return the index in pList of the identifier named zId. Return -1
2600 ** if not found.
2602 int sqlite3IdListIndex(IdList *pList, const char *zName){
2603 int i;
2604 if( pList==0 ) return -1;
2605 for(i=0; i<pList->nId; i++){
2606 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2608 return -1;
2612 ** Delete an entire SrcList including all its substructure.
2614 void sqlite3SrcListDelete(SrcList *pList){
2615 int i;
2616 struct SrcList_item *pItem;
2617 if( pList==0 ) return;
2618 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2619 sqliteFree(pItem->zDatabase);
2620 sqliteFree(pItem->zName);
2621 sqliteFree(pItem->zAlias);
2622 sqlite3DeleteTable(0, pItem->pTab);
2623 sqlite3SelectDelete(pItem->pSelect);
2624 sqlite3ExprDelete(pItem->pOn);
2625 sqlite3IdListDelete(pItem->pUsing);
2627 sqliteFree(pList);
2631 ** Begin a transaction
2633 void sqlite3BeginTransaction(Parse *pParse, int type){
2634 sqlite3 *db;
2635 Vdbe *v;
2636 int i;
2638 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2639 if( pParse->nErr || sqlite3_malloc_failed ) return;
2640 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
2642 v = sqlite3GetVdbe(pParse);
2643 if( !v ) return;
2644 if( type!=TK_DEFERRED ){
2645 for(i=0; i<db->nDb; i++){
2646 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2649 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
2653 ** Commit a transaction
2655 void sqlite3CommitTransaction(Parse *pParse){
2656 sqlite3 *db;
2657 Vdbe *v;
2659 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2660 if( pParse->nErr || sqlite3_malloc_failed ) return;
2661 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
2663 v = sqlite3GetVdbe(pParse);
2664 if( v ){
2665 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
2670 ** Rollback a transaction
2672 void sqlite3RollbackTransaction(Parse *pParse){
2673 sqlite3 *db;
2674 Vdbe *v;
2676 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2677 if( pParse->nErr || sqlite3_malloc_failed ) return;
2678 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
2680 v = sqlite3GetVdbe(pParse);
2681 if( v ){
2682 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
2687 ** Make sure the TEMP database is open and available for use. Return
2688 ** the number of errors. Leave any error messages in the pParse structure.
2690 static int sqlite3OpenTempDatabase(Parse *pParse){
2691 sqlite3 *db = pParse->db;
2692 if( db->aDb[1].pBt==0 && !pParse->explain ){
2693 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2694 if( rc!=SQLITE_OK ){
2695 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2696 "file for storing temporary tables");
2697 pParse->rc = rc;
2698 return 1;
2700 if( db->flags & !db->autoCommit ){
2701 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2702 if( rc!=SQLITE_OK ){
2703 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2704 "the temporary database file");
2705 pParse->rc = rc;
2706 return 1;
2710 return 0;
2714 ** Generate VDBE code that will verify the schema cookie and start
2715 ** a read-transaction for all named database files.
2717 ** It is important that all schema cookies be verified and all
2718 ** read transactions be started before anything else happens in
2719 ** the VDBE program. But this routine can be called after much other
2720 ** code has been generated. So here is what we do:
2722 ** The first time this routine is called, we code an OP_Goto that
2723 ** will jump to a subroutine at the end of the program. Then we
2724 ** record every database that needs its schema verified in the
2725 ** pParse->cookieMask field. Later, after all other code has been
2726 ** generated, the subroutine that does the cookie verifications and
2727 ** starts the transactions will be coded and the OP_Goto P2 value
2728 ** will be made to point to that subroutine. The generation of the
2729 ** cookie verification subroutine code happens in sqlite3FinishCoding().
2731 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
2732 ** schema on any databases. This can be used to position the OP_Goto
2733 ** early in the code, before we know if any database tables will be used.
2735 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
2736 sqlite3 *db;
2737 Vdbe *v;
2738 int mask;
2740 v = sqlite3GetVdbe(pParse);
2741 if( v==0 ) return; /* This only happens if there was a prior error */
2742 db = pParse->db;
2743 if( pParse->cookieGoto==0 ){
2744 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
2746 if( iDb>=0 ){
2747 assert( iDb<db->nDb );
2748 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
2749 assert( iDb<32 );
2750 mask = 1<<iDb;
2751 if( (pParse->cookieMask & mask)==0 ){
2752 pParse->cookieMask |= mask;
2753 pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie;
2754 if( !OMIT_TEMPDB && iDb==1 ){
2755 sqlite3OpenTempDatabase(pParse);
2762 ** Generate VDBE code that prepares for doing an operation that
2763 ** might change the database.
2765 ** This routine starts a new transaction if we are not already within
2766 ** a transaction. If we are already within a transaction, then a checkpoint
2767 ** is set if the setStatement parameter is true. A checkpoint should
2768 ** be set for operations that might fail (due to a constraint) part of
2769 ** the way through and which will need to undo some writes without having to
2770 ** rollback the whole transaction. For operations where all constraints
2771 ** can be checked before any changes are made to the database, it is never
2772 ** necessary to undo a write and the checkpoint should not be set.
2774 ** Only database iDb and the temp database are made writable by this call.
2775 ** If iDb==0, then the main and temp databases are made writable. If
2776 ** iDb==1 then only the temp database is made writable. If iDb>1 then the
2777 ** specified auxiliary database and the temp database are made writable.
2779 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
2780 Vdbe *v = sqlite3GetVdbe(pParse);
2781 if( v==0 ) return;
2782 sqlite3CodeVerifySchema(pParse, iDb);
2783 pParse->writeMask |= 1<<iDb;
2784 if( setStatement && pParse->nested==0 ){
2785 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
2787 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
2788 sqlite3BeginWriteOperation(pParse, setStatement, 1);
2793 ** Check to see if pIndex uses the collating sequence pColl. Return
2794 ** true if it does and false if it does not.
2796 #ifndef SQLITE_OMIT_REINDEX
2797 static int collationMatch(CollSeq *pColl, Index *pIndex){
2798 int n = pIndex->keyInfo.nField;
2799 CollSeq **pp = pIndex->keyInfo.aColl;
2800 while( n-- ){
2801 if( *pp==pColl ) return 1;
2802 pp++;
2804 return 0;
2806 #endif
2809 ** Recompute all indices of pTab that use the collating sequence pColl.
2810 ** If pColl==0 then recompute all indices of pTab.
2812 #ifndef SQLITE_OMIT_REINDEX
2813 void reindexTable(Parse *pParse, Table *pTab, CollSeq *pColl){
2814 Index *pIndex; /* An index associated with pTab */
2816 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
2817 if( pColl==0 || collationMatch(pColl,pIndex) ){
2818 sqlite3BeginWriteOperation(pParse, 0, pTab->iDb);
2819 sqlite3RefillIndex(pParse, pIndex, -1);
2823 #endif
2826 ** Recompute all indices of all tables in all databases where the
2827 ** indices use the collating sequence pColl. If pColl==0 then recompute
2828 ** all indices everywhere.
2830 #ifndef SQLITE_OMIT_REINDEX
2831 void reindexDatabases(Parse *pParse, CollSeq *pColl){
2832 Db *pDb; /* A single database */
2833 int iDb; /* The database index number */
2834 sqlite3 *db = pParse->db; /* The database connection */
2835 HashElem *k; /* For looping over tables in pDb */
2836 Table *pTab; /* A table in the database */
2838 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
2839 if( pDb==0 ) continue;
2840 for(k=sqliteHashFirst(&pDb->tblHash); k; k=sqliteHashNext(k)){
2841 pTab = (Table*)sqliteHashData(k);
2842 reindexTable(pParse, pTab, pColl);
2846 #endif
2849 ** Generate code for the REINDEX command.
2851 ** REINDEX -- 1
2852 ** REINDEX <collation> -- 2
2853 ** REINDEX ?<database>.?<tablename> -- 3
2854 ** REINDEX ?<database>.?<indexname> -- 4
2856 ** Form 1 causes all indices in all attached databases to be rebuilt.
2857 ** Form 2 rebuilds all indices in all databases that use the named
2858 ** collating function. Forms 3 and 4 rebuild the named index or all
2859 ** indices associated with the named table.
2861 #ifndef SQLITE_OMIT_REINDEX
2862 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
2863 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
2864 char *z; /* Name of a table or index */
2865 const char *zDb; /* Name of the database */
2866 Table *pTab; /* A table in the database */
2867 Index *pIndex; /* An index associated with pTab */
2868 int iDb; /* The database index number */
2869 sqlite3 *db = pParse->db; /* The database connection */
2870 Token *pObjName; /* Name of the table or index to be reindexed */
2872 /* Read the database schema. If an error occurs, leave an error message
2873 ** and code in pParse and return NULL. */
2874 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2875 return;
2878 if( pName1==0 || pName1->z==0 ){
2879 reindexDatabases(pParse, 0);
2880 return;
2881 }else if( pName2==0 || pName2->z==0 ){
2882 pColl = sqlite3FindCollSeq(db, db->enc, pName1->z, pName1->n, 0);
2883 if( pColl ){
2884 reindexDatabases(pParse, pColl);
2885 return;
2888 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
2889 if( iDb<0 ) return;
2890 z = sqlite3NameFromToken(pObjName);
2891 zDb = db->aDb[iDb].zName;
2892 pTab = sqlite3FindTable(db, z, zDb);
2893 if( pTab ){
2894 reindexTable(pParse, pTab, 0);
2895 sqliteFree(z);
2896 return;
2898 pIndex = sqlite3FindIndex(db, z, zDb);
2899 sqliteFree(z);
2900 if( pIndex ){
2901 sqlite3BeginWriteOperation(pParse, 0, iDb);
2902 sqlite3RefillIndex(pParse, pIndex, -1);
2903 return;
2905 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
2907 #endif