Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / sqlite / sqlite-src-3080704 / src / build.c
blobb897494db3c2e478402917cfbe724de567177ac7
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 #include "sqliteInt.h"
28 ** This routine is called when a new SQL statement is beginning to
29 ** be parsed. Initialize the pParse structure as needed.
31 void sqlite3BeginParse(Parse *pParse, int explainFlag){
32 pParse->explain = (u8)explainFlag;
33 pParse->nVar = 0;
36 #ifndef SQLITE_OMIT_SHARED_CACHE
38 ** The TableLock structure is only used by the sqlite3TableLock() and
39 ** codeTableLocks() functions.
41 struct TableLock {
42 int iDb; /* The database containing the table to be locked */
43 int iTab; /* The root page of the table to be locked */
44 u8 isWriteLock; /* True for write lock. False for a read lock */
45 const char *zName; /* Name of the table */
49 ** Record the fact that we want to lock a table at run-time.
51 ** The table to be locked has root page iTab and is found in database iDb.
52 ** A read or a write lock can be taken depending on isWritelock.
54 ** This routine just records the fact that the lock is desired. The
55 ** code to make the lock occur is generated by a later call to
56 ** codeTableLocks() which occurs during sqlite3FinishCoding().
58 void sqlite3TableLock(
59 Parse *pParse, /* Parsing context */
60 int iDb, /* Index of the database containing the table to lock */
61 int iTab, /* Root page number of the table to be locked */
62 u8 isWriteLock, /* True for a write lock */
63 const char *zName /* Name of the table to be locked */
65 Parse *pToplevel = sqlite3ParseToplevel(pParse);
66 int i;
67 int nBytes;
68 TableLock *p;
69 assert( iDb>=0 );
71 for(i=0; i<pToplevel->nTableLock; i++){
72 p = &pToplevel->aTableLock[i];
73 if( p->iDb==iDb && p->iTab==iTab ){
74 p->isWriteLock = (p->isWriteLock || isWriteLock);
75 return;
79 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80 pToplevel->aTableLock =
81 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82 if( pToplevel->aTableLock ){
83 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
84 p->iDb = iDb;
85 p->iTab = iTab;
86 p->isWriteLock = isWriteLock;
87 p->zName = zName;
88 }else{
89 pToplevel->nTableLock = 0;
90 pToplevel->db->mallocFailed = 1;
95 ** Code an OP_TableLock instruction for each table locked by the
96 ** statement (configured by calls to sqlite3TableLock()).
98 static void codeTableLocks(Parse *pParse){
99 int i;
100 Vdbe *pVdbe;
102 pVdbe = sqlite3GetVdbe(pParse);
103 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
105 for(i=0; i<pParse->nTableLock; i++){
106 TableLock *p = &pParse->aTableLock[i];
107 int p1 = p->iDb;
108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
109 p->zName, P4_STATIC);
112 #else
113 #define codeTableLocks(x)
114 #endif
117 ** Return TRUE if the given yDbMask object is empty - if it contains no
118 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
119 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
121 #if SQLITE_MAX_ATTACHED>30
122 int sqlite3DbMaskAllZero(yDbMask m){
123 int i;
124 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
125 return 1;
127 #endif
130 ** This routine is called after a single SQL statement has been
131 ** parsed and a VDBE program to execute that statement has been
132 ** prepared. This routine puts the finishing touches on the
133 ** VDBE program and resets the pParse structure for the next
134 ** parse.
136 ** Note that if an error occurred, it might be the case that
137 ** no VDBE code was generated.
139 void sqlite3FinishCoding(Parse *pParse){
140 sqlite3 *db;
141 Vdbe *v;
143 assert( pParse->pToplevel==0 );
144 db = pParse->db;
145 if( db->mallocFailed ) return;
146 if( pParse->nested ) return;
147 if( pParse->nErr ) return;
149 /* Begin by generating some termination code at the end of the
150 ** vdbe program
152 v = sqlite3GetVdbe(pParse);
153 assert( !pParse->isMultiWrite
154 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
155 if( v ){
156 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
157 sqlite3VdbeAddOp0(v, OP_Halt);
159 #if SQLITE_USER_AUTHENTICATION
160 if( pParse->nTableLock>0 && db->init.busy==0 ){
161 sqlite3UserAuthInit(db);
162 if( db->auth.authLevel<UAUTH_User ){
163 pParse->rc = SQLITE_AUTH_USER;
164 sqlite3ErrorMsg(pParse, "user not authenticated");
165 return;
168 #endif
170 /* The cookie mask contains one bit for each database file open.
171 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
172 ** set for each database that is used. Generate code to start a
173 ** transaction on each used database and to verify the schema cookie
174 ** on each used database.
176 if( db->mallocFailed==0
177 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
179 int iDb, i;
180 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
181 sqlite3VdbeJumpHere(v, 0);
182 for(iDb=0; iDb<db->nDb; iDb++){
183 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
184 sqlite3VdbeUsesBtree(v, iDb);
185 sqlite3VdbeAddOp4Int(v,
186 OP_Transaction, /* Opcode */
187 iDb, /* P1 */
188 DbMaskTest(pParse->writeMask,iDb), /* P2 */
189 pParse->cookieValue[iDb], /* P3 */
190 db->aDb[iDb].pSchema->iGeneration /* P4 */
192 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
194 #ifndef SQLITE_OMIT_VIRTUALTABLE
195 for(i=0; i<pParse->nVtabLock; i++){
196 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
197 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
199 pParse->nVtabLock = 0;
200 #endif
202 /* Once all the cookies have been verified and transactions opened,
203 ** obtain the required table-locks. This is a no-op unless the
204 ** shared-cache feature is enabled.
206 codeTableLocks(pParse);
208 /* Initialize any AUTOINCREMENT data structures required.
210 sqlite3AutoincrementBegin(pParse);
212 /* Code constant expressions that where factored out of inner loops */
213 if( pParse->pConstExpr ){
214 ExprList *pEL = pParse->pConstExpr;
215 pParse->okConstFactor = 0;
216 for(i=0; i<pEL->nExpr; i++){
217 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
221 /* Finally, jump back to the beginning of the executable code. */
222 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
227 /* Get the VDBE program ready for execution
229 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
230 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
231 /* A minimum of one cursor is required if autoincrement is used
232 * See ticket [a696379c1f08866] */
233 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
234 sqlite3VdbeMakeReady(v, pParse);
235 pParse->rc = SQLITE_DONE;
236 pParse->colNamesSet = 0;
237 }else{
238 pParse->rc = SQLITE_ERROR;
240 pParse->nTab = 0;
241 pParse->nMem = 0;
242 pParse->nSet = 0;
243 pParse->nVar = 0;
244 DbMaskZero(pParse->cookieMask);
248 ** Run the parser and code generator recursively in order to generate
249 ** code for the SQL statement given onto the end of the pParse context
250 ** currently under construction. When the parser is run recursively
251 ** this way, the final OP_Halt is not appended and other initialization
252 ** and finalization steps are omitted because those are handling by the
253 ** outermost parser.
255 ** Not everything is nestable. This facility is designed to permit
256 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
257 ** care if you decide to try to use this routine for some other purposes.
259 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
260 va_list ap;
261 char *zSql;
262 char *zErrMsg = 0;
263 sqlite3 *db = pParse->db;
264 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
265 char saveBuf[SAVE_SZ];
267 if( pParse->nErr ) return;
268 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
269 va_start(ap, zFormat);
270 zSql = sqlite3VMPrintf(db, zFormat, ap);
271 va_end(ap);
272 if( zSql==0 ){
273 return; /* A malloc must have failed */
275 pParse->nested++;
276 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
277 memset(&pParse->nVar, 0, SAVE_SZ);
278 sqlite3RunParser(pParse, zSql, &zErrMsg);
279 sqlite3DbFree(db, zErrMsg);
280 sqlite3DbFree(db, zSql);
281 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
282 pParse->nested--;
285 #if SQLITE_USER_AUTHENTICATION
287 ** Return TRUE if zTable is the name of the system table that stores the
288 ** list of users and their access credentials.
290 int sqlite3UserAuthTable(const char *zTable){
291 return sqlite3_stricmp(zTable, "sqlite_user")==0;
293 #endif
296 ** Locate the in-memory structure that describes a particular database
297 ** table given the name of that table and (optionally) the name of the
298 ** database containing the table. Return NULL if not found.
300 ** If zDatabase is 0, all databases are searched for the table and the
301 ** first matching table is returned. (No checking for duplicate table
302 ** names is done.) The search order is TEMP first, then MAIN, then any
303 ** auxiliary databases added using the ATTACH command.
305 ** See also sqlite3LocateTable().
307 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
308 Table *p = 0;
309 int i;
310 assert( zName!=0 );
311 /* All mutexes are required for schema access. Make sure we hold them. */
312 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
313 #if SQLITE_USER_AUTHENTICATION
314 /* Only the admin user is allowed to know that the sqlite_user table
315 ** exists */
316 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
317 return 0;
319 #endif
320 for(i=OMIT_TEMPDB; i<db->nDb; i++){
321 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
322 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
323 assert( sqlite3SchemaMutexHeld(db, j, 0) );
324 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
325 if( p ) break;
327 return p;
331 ** Locate the in-memory structure that describes a particular database
332 ** table given the name of that table and (optionally) the name of the
333 ** database containing the table. Return NULL if not found. Also leave an
334 ** error message in pParse->zErrMsg.
336 ** The difference between this routine and sqlite3FindTable() is that this
337 ** routine leaves an error message in pParse->zErrMsg where
338 ** sqlite3FindTable() does not.
340 Table *sqlite3LocateTable(
341 Parse *pParse, /* context in which to report errors */
342 int isView, /* True if looking for a VIEW rather than a TABLE */
343 const char *zName, /* Name of the table we are looking for */
344 const char *zDbase /* Name of the database. Might be NULL */
346 Table *p;
348 /* Read the database schema. If an error occurs, leave an error message
349 ** and code in pParse and return NULL. */
350 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
351 return 0;
354 p = sqlite3FindTable(pParse->db, zName, zDbase);
355 if( p==0 ){
356 const char *zMsg = isView ? "no such view" : "no such table";
357 if( zDbase ){
358 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
359 }else{
360 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
362 pParse->checkSchema = 1;
364 #if SQLITE_USER_AUTHENICATION
365 else if( pParse->db->auth.authLevel<UAUTH_User ){
366 sqlite3ErrorMsg(pParse, "user not authenticated");
367 p = 0;
369 #endif
370 return p;
374 ** Locate the table identified by *p.
376 ** This is a wrapper around sqlite3LocateTable(). The difference between
377 ** sqlite3LocateTable() and this function is that this function restricts
378 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
379 ** non-NULL if it is part of a view or trigger program definition. See
380 ** sqlite3FixSrcList() for details.
382 Table *sqlite3LocateTableItem(
383 Parse *pParse,
384 int isView,
385 struct SrcList_item *p
387 const char *zDb;
388 assert( p->pSchema==0 || p->zDatabase==0 );
389 if( p->pSchema ){
390 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
391 zDb = pParse->db->aDb[iDb].zName;
392 }else{
393 zDb = p->zDatabase;
395 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
399 ** Locate the in-memory structure that describes
400 ** a particular index given the name of that index
401 ** and the name of the database that contains the index.
402 ** Return NULL if not found.
404 ** If zDatabase is 0, all databases are searched for the
405 ** table and the first matching index is returned. (No checking
406 ** for duplicate index names is done.) The search order is
407 ** TEMP first, then MAIN, then any auxiliary databases added
408 ** using the ATTACH command.
410 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
411 Index *p = 0;
412 int i;
413 /* All mutexes are required for schema access. Make sure we hold them. */
414 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
415 for(i=OMIT_TEMPDB; i<db->nDb; i++){
416 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
417 Schema *pSchema = db->aDb[j].pSchema;
418 assert( pSchema );
419 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
420 assert( sqlite3SchemaMutexHeld(db, j, 0) );
421 p = sqlite3HashFind(&pSchema->idxHash, zName);
422 if( p ) break;
424 return p;
428 ** Reclaim the memory used by an index
430 static void freeIndex(sqlite3 *db, Index *p){
431 #ifndef SQLITE_OMIT_ANALYZE
432 sqlite3DeleteIndexSamples(db, p);
433 #endif
434 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
435 sqlite3ExprDelete(db, p->pPartIdxWhere);
436 sqlite3DbFree(db, p->zColAff);
437 if( p->isResized ) sqlite3DbFree(db, p->azColl);
438 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
439 sqlite3_free(p->aiRowEst);
440 #endif
441 sqlite3DbFree(db, p);
445 ** For the index called zIdxName which is found in the database iDb,
446 ** unlike that index from its Table then remove the index from
447 ** the index hash table and free all memory structures associated
448 ** with the index.
450 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
451 Index *pIndex;
452 Hash *pHash;
454 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
455 pHash = &db->aDb[iDb].pSchema->idxHash;
456 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
457 if( ALWAYS(pIndex) ){
458 if( pIndex->pTable->pIndex==pIndex ){
459 pIndex->pTable->pIndex = pIndex->pNext;
460 }else{
461 Index *p;
462 /* Justification of ALWAYS(); The index must be on the list of
463 ** indices. */
464 p = pIndex->pTable->pIndex;
465 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
466 if( ALWAYS(p && p->pNext==pIndex) ){
467 p->pNext = pIndex->pNext;
470 freeIndex(db, pIndex);
472 db->flags |= SQLITE_InternChanges;
476 ** Look through the list of open database files in db->aDb[] and if
477 ** any have been closed, remove them from the list. Reallocate the
478 ** db->aDb[] structure to a smaller size, if possible.
480 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
481 ** are never candidates for being collapsed.
483 void sqlite3CollapseDatabaseArray(sqlite3 *db){
484 int i, j;
485 for(i=j=2; i<db->nDb; i++){
486 struct Db *pDb = &db->aDb[i];
487 if( pDb->pBt==0 ){
488 sqlite3DbFree(db, pDb->zName);
489 pDb->zName = 0;
490 continue;
492 if( j<i ){
493 db->aDb[j] = db->aDb[i];
495 j++;
497 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
498 db->nDb = j;
499 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
500 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
501 sqlite3DbFree(db, db->aDb);
502 db->aDb = db->aDbStatic;
507 ** Reset the schema for the database at index iDb. Also reset the
508 ** TEMP schema.
510 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
511 Db *pDb;
512 assert( iDb<db->nDb );
514 /* Case 1: Reset the single schema identified by iDb */
515 pDb = &db->aDb[iDb];
516 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
517 assert( pDb->pSchema!=0 );
518 sqlite3SchemaClear(pDb->pSchema);
520 /* If any database other than TEMP is reset, then also reset TEMP
521 ** since TEMP might be holding triggers that reference tables in the
522 ** other database.
524 if( iDb!=1 ){
525 pDb = &db->aDb[1];
526 assert( pDb->pSchema!=0 );
527 sqlite3SchemaClear(pDb->pSchema);
529 return;
533 ** Erase all schema information from all attached databases (including
534 ** "main" and "temp") for a single database connection.
536 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
537 int i;
538 sqlite3BtreeEnterAll(db);
539 for(i=0; i<db->nDb; i++){
540 Db *pDb = &db->aDb[i];
541 if( pDb->pSchema ){
542 sqlite3SchemaClear(pDb->pSchema);
545 db->flags &= ~SQLITE_InternChanges;
546 sqlite3VtabUnlockList(db);
547 sqlite3BtreeLeaveAll(db);
548 sqlite3CollapseDatabaseArray(db);
552 ** This routine is called when a commit occurs.
554 void sqlite3CommitInternalChanges(sqlite3 *db){
555 db->flags &= ~SQLITE_InternChanges;
559 ** Delete memory allocated for the column names of a table or view (the
560 ** Table.aCol[] array).
562 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
563 int i;
564 Column *pCol;
565 assert( pTable!=0 );
566 if( (pCol = pTable->aCol)!=0 ){
567 for(i=0; i<pTable->nCol; i++, pCol++){
568 sqlite3DbFree(db, pCol->zName);
569 sqlite3ExprDelete(db, pCol->pDflt);
570 sqlite3DbFree(db, pCol->zDflt);
571 sqlite3DbFree(db, pCol->zType);
572 sqlite3DbFree(db, pCol->zColl);
574 sqlite3DbFree(db, pTable->aCol);
579 ** Remove the memory data structures associated with the given
580 ** Table. No changes are made to disk by this routine.
582 ** This routine just deletes the data structure. It does not unlink
583 ** the table data structure from the hash table. But it does destroy
584 ** memory structures of the indices and foreign keys associated with
585 ** the table.
587 ** The db parameter is optional. It is needed if the Table object
588 ** contains lookaside memory. (Table objects in the schema do not use
589 ** lookaside memory, but some ephemeral Table objects do.) Or the
590 ** db parameter can be used with db->pnBytesFreed to measure the memory
591 ** used by the Table object.
593 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
594 Index *pIndex, *pNext;
595 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
597 assert( !pTable || pTable->nRef>0 );
599 /* Do not delete the table until the reference count reaches zero. */
600 if( !pTable ) return;
601 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
603 /* Record the number of outstanding lookaside allocations in schema Tables
604 ** prior to doing any free() operations. Since schema Tables do not use
605 ** lookaside, this number should not change. */
606 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
607 db->lookaside.nOut : 0 );
609 /* Delete all indices associated with this table. */
610 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
611 pNext = pIndex->pNext;
612 assert( pIndex->pSchema==pTable->pSchema );
613 if( !db || db->pnBytesFreed==0 ){
614 char *zName = pIndex->zName;
615 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
616 &pIndex->pSchema->idxHash, zName, 0
618 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
619 assert( pOld==pIndex || pOld==0 );
621 freeIndex(db, pIndex);
624 /* Delete any foreign keys attached to this table. */
625 sqlite3FkDelete(db, pTable);
627 /* Delete the Table structure itself.
629 sqliteDeleteColumnNames(db, pTable);
630 sqlite3DbFree(db, pTable->zName);
631 sqlite3DbFree(db, pTable->zColAff);
632 sqlite3SelectDelete(db, pTable->pSelect);
633 #ifndef SQLITE_OMIT_CHECK
634 sqlite3ExprListDelete(db, pTable->pCheck);
635 #endif
636 #ifndef SQLITE_OMIT_VIRTUALTABLE
637 sqlite3VtabClear(db, pTable);
638 #endif
639 sqlite3DbFree(db, pTable);
641 /* Verify that no lookaside memory was used by schema tables */
642 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
646 ** Unlink the given table from the hash tables and the delete the
647 ** table structure with all its indices and foreign keys.
649 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
650 Table *p;
651 Db *pDb;
653 assert( db!=0 );
654 assert( iDb>=0 && iDb<db->nDb );
655 assert( zTabName );
656 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
657 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
658 pDb = &db->aDb[iDb];
659 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
660 sqlite3DeleteTable(db, p);
661 db->flags |= SQLITE_InternChanges;
665 ** Given a token, return a string that consists of the text of that
666 ** token. Space to hold the returned string
667 ** is obtained from sqliteMalloc() and must be freed by the calling
668 ** function.
670 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
671 ** surround the body of the token are removed.
673 ** Tokens are often just pointers into the original SQL text and so
674 ** are not \000 terminated and are not persistent. The returned string
675 ** is \000 terminated and is persistent.
677 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
678 char *zName;
679 if( pName ){
680 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
681 sqlite3Dequote(zName);
682 }else{
683 zName = 0;
685 return zName;
689 ** Open the sqlite_master table stored in database number iDb for
690 ** writing. The table is opened using cursor 0.
692 void sqlite3OpenMasterTable(Parse *p, int iDb){
693 Vdbe *v = sqlite3GetVdbe(p);
694 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
695 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
696 if( p->nTab==0 ){
697 p->nTab = 1;
702 ** Parameter zName points to a nul-terminated buffer containing the name
703 ** of a database ("main", "temp" or the name of an attached db). This
704 ** function returns the index of the named database in db->aDb[], or
705 ** -1 if the named db cannot be found.
707 int sqlite3FindDbName(sqlite3 *db, const char *zName){
708 int i = -1; /* Database number */
709 if( zName ){
710 Db *pDb;
711 int n = sqlite3Strlen30(zName);
712 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
713 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
714 0==sqlite3StrICmp(pDb->zName, zName) ){
715 break;
719 return i;
723 ** The token *pName contains the name of a database (either "main" or
724 ** "temp" or the name of an attached db). This routine returns the
725 ** index of the named database in db->aDb[], or -1 if the named db
726 ** does not exist.
728 int sqlite3FindDb(sqlite3 *db, Token *pName){
729 int i; /* Database number */
730 char *zName; /* Name we are searching for */
731 zName = sqlite3NameFromToken(db, pName);
732 i = sqlite3FindDbName(db, zName);
733 sqlite3DbFree(db, zName);
734 return i;
737 /* The table or view or trigger name is passed to this routine via tokens
738 ** pName1 and pName2. If the table name was fully qualified, for example:
740 ** CREATE TABLE xxx.yyy (...);
742 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
743 ** the table name is not fully qualified, i.e.:
745 ** CREATE TABLE yyy(...);
747 ** Then pName1 is set to "yyy" and pName2 is "".
749 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
750 ** pName2) that stores the unqualified table name. The index of the
751 ** database "xxx" is returned.
753 int sqlite3TwoPartName(
754 Parse *pParse, /* Parsing and code generating context */
755 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
756 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
757 Token **pUnqual /* Write the unqualified object name here */
759 int iDb; /* Database holding the object */
760 sqlite3 *db = pParse->db;
762 if( ALWAYS(pName2!=0) && pName2->n>0 ){
763 if( db->init.busy ) {
764 sqlite3ErrorMsg(pParse, "corrupt database");
765 pParse->nErr++;
766 return -1;
768 *pUnqual = pName2;
769 iDb = sqlite3FindDb(db, pName1);
770 if( iDb<0 ){
771 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
772 pParse->nErr++;
773 return -1;
775 }else{
776 assert( db->init.iDb==0 || db->init.busy );
777 iDb = db->init.iDb;
778 *pUnqual = pName1;
780 return iDb;
784 ** This routine is used to check if the UTF-8 string zName is a legal
785 ** unqualified name for a new schema object (table, index, view or
786 ** trigger). All names are legal except those that begin with the string
787 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
788 ** is reserved for internal use.
790 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
791 if( !pParse->db->init.busy && pParse->nested==0
792 && (pParse->db->flags & SQLITE_WriteSchema)==0
793 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
794 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
795 return SQLITE_ERROR;
797 return SQLITE_OK;
801 ** Return the PRIMARY KEY index of a table
803 Index *sqlite3PrimaryKeyIndex(Table *pTab){
804 Index *p;
805 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
806 return p;
810 ** Return the column of index pIdx that corresponds to table
811 ** column iCol. Return -1 if not found.
813 i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
814 int i;
815 for(i=0; i<pIdx->nColumn; i++){
816 if( iCol==pIdx->aiColumn[i] ) return i;
818 return -1;
822 ** Begin constructing a new table representation in memory. This is
823 ** the first of several action routines that get called in response
824 ** to a CREATE TABLE statement. In particular, this routine is called
825 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
826 ** flag is true if the table should be stored in the auxiliary database
827 ** file instead of in the main database file. This is normally the case
828 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
829 ** CREATE and TABLE.
831 ** The new table record is initialized and put in pParse->pNewTable.
832 ** As more of the CREATE TABLE statement is parsed, additional action
833 ** routines will be called to add more information to this record.
834 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
835 ** is called to complete the construction of the new table record.
837 void sqlite3StartTable(
838 Parse *pParse, /* Parser context */
839 Token *pName1, /* First part of the name of the table or view */
840 Token *pName2, /* Second part of the name of the table or view */
841 int isTemp, /* True if this is a TEMP table */
842 int isView, /* True if this is a VIEW */
843 int isVirtual, /* True if this is a VIRTUAL table */
844 int noErr /* Do nothing if table already exists */
846 Table *pTable;
847 char *zName = 0; /* The name of the new table */
848 sqlite3 *db = pParse->db;
849 Vdbe *v;
850 int iDb; /* Database number to create the table in */
851 Token *pName; /* Unqualified name of the table to create */
853 /* The table or view name to create is passed to this routine via tokens
854 ** pName1 and pName2. If the table name was fully qualified, for example:
856 ** CREATE TABLE xxx.yyy (...);
858 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
859 ** the table name is not fully qualified, i.e.:
861 ** CREATE TABLE yyy(...);
863 ** Then pName1 is set to "yyy" and pName2 is "".
865 ** The call below sets the pName pointer to point at the token (pName1 or
866 ** pName2) that stores the unqualified table name. The variable iDb is
867 ** set to the index of the database that the table or view is to be
868 ** created in.
870 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
871 if( iDb<0 ) return;
872 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
873 /* If creating a temp table, the name may not be qualified. Unless
874 ** the database name is "temp" anyway. */
875 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
876 return;
878 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
880 pParse->sNameToken = *pName;
881 zName = sqlite3NameFromToken(db, pName);
882 if( zName==0 ) return;
883 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
884 goto begin_table_error;
886 if( db->init.iDb==1 ) isTemp = 1;
887 #ifndef SQLITE_OMIT_AUTHORIZATION
888 assert( (isTemp & 1)==isTemp );
890 int code;
891 char *zDb = db->aDb[iDb].zName;
892 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
893 goto begin_table_error;
895 if( isView ){
896 if( !OMIT_TEMPDB && isTemp ){
897 code = SQLITE_CREATE_TEMP_VIEW;
898 }else{
899 code = SQLITE_CREATE_VIEW;
901 }else{
902 if( !OMIT_TEMPDB && isTemp ){
903 code = SQLITE_CREATE_TEMP_TABLE;
904 }else{
905 code = SQLITE_CREATE_TABLE;
908 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
909 goto begin_table_error;
912 #endif
914 /* Make sure the new table name does not collide with an existing
915 ** index or table name in the same database. Issue an error message if
916 ** it does. The exception is if the statement being parsed was passed
917 ** to an sqlite3_declare_vtab() call. In that case only the column names
918 ** and types will be used, so there is no need to test for namespace
919 ** collisions.
921 if( !IN_DECLARE_VTAB ){
922 char *zDb = db->aDb[iDb].zName;
923 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
924 goto begin_table_error;
926 pTable = sqlite3FindTable(db, zName, zDb);
927 if( pTable ){
928 if( !noErr ){
929 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
930 }else{
931 assert( !db->init.busy );
932 sqlite3CodeVerifySchema(pParse, iDb);
934 goto begin_table_error;
936 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
937 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
938 goto begin_table_error;
942 pTable = sqlite3DbMallocZero(db, sizeof(Table));
943 if( pTable==0 ){
944 db->mallocFailed = 1;
945 pParse->rc = SQLITE_NOMEM;
946 pParse->nErr++;
947 goto begin_table_error;
949 pTable->zName = zName;
950 pTable->iPKey = -1;
951 pTable->pSchema = db->aDb[iDb].pSchema;
952 pTable->nRef = 1;
953 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
954 assert( pParse->pNewTable==0 );
955 pParse->pNewTable = pTable;
957 /* If this is the magic sqlite_sequence table used by autoincrement,
958 ** then record a pointer to this table in the main database structure
959 ** so that INSERT can find the table easily.
961 #ifndef SQLITE_OMIT_AUTOINCREMENT
962 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
963 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
964 pTable->pSchema->pSeqTab = pTable;
966 #endif
968 /* Begin generating the code that will insert the table record into
969 ** the SQLITE_MASTER table. Note in particular that we must go ahead
970 ** and allocate the record number for the table entry now. Before any
971 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
972 ** indices to be created and the table record must come before the
973 ** indices. Hence, the record number for the table must be allocated
974 ** now.
976 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
977 int j1;
978 int fileFormat;
979 int reg1, reg2, reg3;
980 sqlite3BeginWriteOperation(pParse, 0, iDb);
982 #ifndef SQLITE_OMIT_VIRTUALTABLE
983 if( isVirtual ){
984 sqlite3VdbeAddOp0(v, OP_VBegin);
986 #endif
988 /* If the file format and encoding in the database have not been set,
989 ** set them now.
991 reg1 = pParse->regRowid = ++pParse->nMem;
992 reg2 = pParse->regRoot = ++pParse->nMem;
993 reg3 = ++pParse->nMem;
994 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
995 sqlite3VdbeUsesBtree(v, iDb);
996 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
997 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
998 1 : SQLITE_MAX_FILE_FORMAT;
999 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
1000 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
1001 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
1002 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
1003 sqlite3VdbeJumpHere(v, j1);
1005 /* This just creates a place-holder record in the sqlite_master table.
1006 ** The record created does not contain anything yet. It will be replaced
1007 ** by the real entry in code generated at sqlite3EndTable().
1009 ** The rowid for the new entry is left in register pParse->regRowid.
1010 ** The root page number of the new table is left in reg pParse->regRoot.
1011 ** The rowid and root page number values are needed by the code that
1012 ** sqlite3EndTable will generate.
1014 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1015 if( isView || isVirtual ){
1016 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1017 }else
1018 #endif
1020 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
1022 sqlite3OpenMasterTable(pParse, iDb);
1023 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1024 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1025 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1026 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1027 sqlite3VdbeAddOp0(v, OP_Close);
1030 /* Normal (non-error) return. */
1031 return;
1033 /* If an error occurs, we jump here */
1034 begin_table_error:
1035 sqlite3DbFree(db, zName);
1036 return;
1040 ** This macro is used to compare two strings in a case-insensitive manner.
1041 ** It is slightly faster than calling sqlite3StrICmp() directly, but
1042 ** produces larger code.
1044 ** WARNING: This macro is not compatible with the strcmp() family. It
1045 ** returns true if the two strings are equal, otherwise false.
1047 #define STRICMP(x, y) (\
1048 sqlite3UpperToLower[*(unsigned char *)(x)]== \
1049 sqlite3UpperToLower[*(unsigned char *)(y)] \
1050 && sqlite3StrICmp((x)+1,(y)+1)==0 )
1053 ** Add a new column to the table currently being constructed.
1055 ** The parser calls this routine once for each column declaration
1056 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1057 ** first to get things going. Then this routine is called for each
1058 ** column.
1060 void sqlite3AddColumn(Parse *pParse, Token *pName){
1061 Table *p;
1062 int i;
1063 char *z;
1064 Column *pCol;
1065 sqlite3 *db = pParse->db;
1066 if( (p = pParse->pNewTable)==0 ) return;
1067 #if SQLITE_MAX_COLUMN
1068 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1069 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1070 return;
1072 #endif
1073 z = sqlite3NameFromToken(db, pName);
1074 if( z==0 ) return;
1075 for(i=0; i<p->nCol; i++){
1076 if( STRICMP(z, p->aCol[i].zName) ){
1077 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1078 sqlite3DbFree(db, z);
1079 return;
1082 if( (p->nCol & 0x7)==0 ){
1083 Column *aNew;
1084 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
1085 if( aNew==0 ){
1086 sqlite3DbFree(db, z);
1087 return;
1089 p->aCol = aNew;
1091 pCol = &p->aCol[p->nCol];
1092 memset(pCol, 0, sizeof(p->aCol[0]));
1093 pCol->zName = z;
1095 /* If there is no type specified, columns have the default affinity
1096 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1097 ** be called next to set pCol->affinity correctly.
1099 pCol->affinity = SQLITE_AFF_NONE;
1100 pCol->szEst = 1;
1101 p->nCol++;
1105 ** This routine is called by the parser while in the middle of
1106 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1107 ** been seen on a column. This routine sets the notNull flag on
1108 ** the column currently under construction.
1110 void sqlite3AddNotNull(Parse *pParse, int onError){
1111 Table *p;
1112 p = pParse->pNewTable;
1113 if( p==0 || NEVER(p->nCol<1) ) return;
1114 p->aCol[p->nCol-1].notNull = (u8)onError;
1118 ** Scan the column type name zType (length nType) and return the
1119 ** associated affinity type.
1121 ** This routine does a case-independent search of zType for the
1122 ** substrings in the following table. If one of the substrings is
1123 ** found, the corresponding affinity is returned. If zType contains
1124 ** more than one of the substrings, entries toward the top of
1125 ** the table take priority. For example, if zType is 'BLOBINT',
1126 ** SQLITE_AFF_INTEGER is returned.
1128 ** Substring | Affinity
1129 ** --------------------------------
1130 ** 'INT' | SQLITE_AFF_INTEGER
1131 ** 'CHAR' | SQLITE_AFF_TEXT
1132 ** 'CLOB' | SQLITE_AFF_TEXT
1133 ** 'TEXT' | SQLITE_AFF_TEXT
1134 ** 'BLOB' | SQLITE_AFF_NONE
1135 ** 'REAL' | SQLITE_AFF_REAL
1136 ** 'FLOA' | SQLITE_AFF_REAL
1137 ** 'DOUB' | SQLITE_AFF_REAL
1139 ** If none of the substrings in the above table are found,
1140 ** SQLITE_AFF_NUMERIC is returned.
1142 char sqlite3AffinityType(const char *zIn, u8 *pszEst){
1143 u32 h = 0;
1144 char aff = SQLITE_AFF_NUMERIC;
1145 const char *zChar = 0;
1147 if( zIn==0 ) return aff;
1148 while( zIn[0] ){
1149 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1150 zIn++;
1151 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1152 aff = SQLITE_AFF_TEXT;
1153 zChar = zIn;
1154 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1155 aff = SQLITE_AFF_TEXT;
1156 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1157 aff = SQLITE_AFF_TEXT;
1158 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1159 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1160 aff = SQLITE_AFF_NONE;
1161 if( zIn[0]=='(' ) zChar = zIn;
1162 #ifndef SQLITE_OMIT_FLOATING_POINT
1163 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1164 && aff==SQLITE_AFF_NUMERIC ){
1165 aff = SQLITE_AFF_REAL;
1166 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1167 && aff==SQLITE_AFF_NUMERIC ){
1168 aff = SQLITE_AFF_REAL;
1169 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1170 && aff==SQLITE_AFF_NUMERIC ){
1171 aff = SQLITE_AFF_REAL;
1172 #endif
1173 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1174 aff = SQLITE_AFF_INTEGER;
1175 break;
1179 /* If pszEst is not NULL, store an estimate of the field size. The
1180 ** estimate is scaled so that the size of an integer is 1. */
1181 if( pszEst ){
1182 *pszEst = 1; /* default size is approx 4 bytes */
1183 if( aff<SQLITE_AFF_NUMERIC ){
1184 if( zChar ){
1185 while( zChar[0] ){
1186 if( sqlite3Isdigit(zChar[0]) ){
1187 int v = 0;
1188 sqlite3GetInt32(zChar, &v);
1189 v = v/4 + 1;
1190 if( v>255 ) v = 255;
1191 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1192 break;
1194 zChar++;
1196 }else{
1197 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1201 return aff;
1205 ** This routine is called by the parser while in the middle of
1206 ** parsing a CREATE TABLE statement. The pFirst token is the first
1207 ** token in the sequence of tokens that describe the type of the
1208 ** column currently under construction. pLast is the last token
1209 ** in the sequence. Use this information to construct a string
1210 ** that contains the typename of the column and store that string
1211 ** in zType.
1213 void sqlite3AddColumnType(Parse *pParse, Token *pType){
1214 Table *p;
1215 Column *pCol;
1217 p = pParse->pNewTable;
1218 if( p==0 || NEVER(p->nCol<1) ) return;
1219 pCol = &p->aCol[p->nCol-1];
1220 assert( pCol->zType==0 );
1221 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
1222 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
1226 ** The expression is the default value for the most recently added column
1227 ** of the table currently under construction.
1229 ** Default value expressions must be constant. Raise an exception if this
1230 ** is not the case.
1232 ** This routine is called by the parser while in the middle of
1233 ** parsing a CREATE TABLE statement.
1235 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
1236 Table *p;
1237 Column *pCol;
1238 sqlite3 *db = pParse->db;
1239 p = pParse->pNewTable;
1240 if( p!=0 ){
1241 pCol = &(p->aCol[p->nCol-1]);
1242 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
1243 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1244 pCol->zName);
1245 }else{
1246 /* A copy of pExpr is used instead of the original, as pExpr contains
1247 ** tokens that point to volatile memory. The 'span' of the expression
1248 ** is required by pragma table_info.
1250 sqlite3ExprDelete(db, pCol->pDflt);
1251 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1252 sqlite3DbFree(db, pCol->zDflt);
1253 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1254 (int)(pSpan->zEnd - pSpan->zStart));
1257 sqlite3ExprDelete(db, pSpan->pExpr);
1261 ** Designate the PRIMARY KEY for the table. pList is a list of names
1262 ** of columns that form the primary key. If pList is NULL, then the
1263 ** most recently added column of the table is the primary key.
1265 ** A table can have at most one primary key. If the table already has
1266 ** a primary key (and this is the second primary key) then create an
1267 ** error.
1269 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1270 ** then we will try to use that column as the rowid. Set the Table.iPKey
1271 ** field of the table under construction to be the index of the
1272 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1273 ** no INTEGER PRIMARY KEY.
1275 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1276 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1278 void sqlite3AddPrimaryKey(
1279 Parse *pParse, /* Parsing context */
1280 ExprList *pList, /* List of field names to be indexed */
1281 int onError, /* What to do with a uniqueness conflict */
1282 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1283 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1285 Table *pTab = pParse->pNewTable;
1286 char *zType = 0;
1287 int iCol = -1, i;
1288 int nTerm;
1289 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
1290 if( pTab->tabFlags & TF_HasPrimaryKey ){
1291 sqlite3ErrorMsg(pParse,
1292 "table \"%s\" has more than one primary key", pTab->zName);
1293 goto primary_key_exit;
1295 pTab->tabFlags |= TF_HasPrimaryKey;
1296 if( pList==0 ){
1297 iCol = pTab->nCol - 1;
1298 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1299 zType = pTab->aCol[iCol].zType;
1300 nTerm = 1;
1301 }else{
1302 nTerm = pList->nExpr;
1303 for(i=0; i<nTerm; i++){
1304 for(iCol=0; iCol<pTab->nCol; iCol++){
1305 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1306 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1307 zType = pTab->aCol[iCol].zType;
1308 break;
1313 if( nTerm==1
1314 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1315 && sortOrder==SQLITE_SO_ASC
1317 pTab->iPKey = iCol;
1318 pTab->keyConf = (u8)onError;
1319 assert( autoInc==0 || autoInc==1 );
1320 pTab->tabFlags |= autoInc*TF_Autoincrement;
1321 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
1322 }else if( autoInc ){
1323 #ifndef SQLITE_OMIT_AUTOINCREMENT
1324 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1325 "INTEGER PRIMARY KEY");
1326 #endif
1327 }else{
1328 Vdbe *v = pParse->pVdbe;
1329 Index *p;
1330 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
1331 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1332 0, sortOrder, 0);
1333 if( p ){
1334 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
1335 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
1337 pList = 0;
1340 primary_key_exit:
1341 sqlite3ExprListDelete(pParse->db, pList);
1342 return;
1346 ** Add a new CHECK constraint to the table currently under construction.
1348 void sqlite3AddCheckConstraint(
1349 Parse *pParse, /* Parsing context */
1350 Expr *pCheckExpr /* The check expression */
1352 #ifndef SQLITE_OMIT_CHECK
1353 Table *pTab = pParse->pNewTable;
1354 sqlite3 *db = pParse->db;
1355 if( pTab && !IN_DECLARE_VTAB
1356 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1358 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1359 if( pParse->constraintName.n ){
1360 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1362 }else
1363 #endif
1365 sqlite3ExprDelete(pParse->db, pCheckExpr);
1370 ** Set the collation function of the most recently parsed table column
1371 ** to the CollSeq given.
1373 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1374 Table *p;
1375 int i;
1376 char *zColl; /* Dequoted name of collation sequence */
1377 sqlite3 *db;
1379 if( (p = pParse->pNewTable)==0 ) return;
1380 i = p->nCol-1;
1381 db = pParse->db;
1382 zColl = sqlite3NameFromToken(db, pToken);
1383 if( !zColl ) return;
1385 if( sqlite3LocateCollSeq(pParse, zColl) ){
1386 Index *pIdx;
1387 sqlite3DbFree(db, p->aCol[i].zColl);
1388 p->aCol[i].zColl = zColl;
1390 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1391 ** then an index may have been created on this column before the
1392 ** collation type was added. Correct this if it is the case.
1394 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1395 assert( pIdx->nKeyCol==1 );
1396 if( pIdx->aiColumn[0]==i ){
1397 pIdx->azColl[0] = p->aCol[i].zColl;
1400 }else{
1401 sqlite3DbFree(db, zColl);
1406 ** This function returns the collation sequence for database native text
1407 ** encoding identified by the string zName, length nName.
1409 ** If the requested collation sequence is not available, or not available
1410 ** in the database native encoding, the collation factory is invoked to
1411 ** request it. If the collation factory does not supply such a sequence,
1412 ** and the sequence is available in another text encoding, then that is
1413 ** returned instead.
1415 ** If no versions of the requested collations sequence are available, or
1416 ** another error occurs, NULL is returned and an error message written into
1417 ** pParse.
1419 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1420 ** invokes the collation factory if the named collation cannot be found
1421 ** and generates an error message.
1423 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1425 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
1426 sqlite3 *db = pParse->db;
1427 u8 enc = ENC(db);
1428 u8 initbusy = db->init.busy;
1429 CollSeq *pColl;
1431 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
1432 if( !initbusy && (!pColl || !pColl->xCmp) ){
1433 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
1436 return pColl;
1441 ** Generate code that will increment the schema cookie.
1443 ** The schema cookie is used to determine when the schema for the
1444 ** database changes. After each schema change, the cookie value
1445 ** changes. When a process first reads the schema it records the
1446 ** cookie. Thereafter, whenever it goes to access the database,
1447 ** it checks the cookie to make sure the schema has not changed
1448 ** since it was last read.
1450 ** This plan is not completely bullet-proof. It is possible for
1451 ** the schema to change multiple times and for the cookie to be
1452 ** set back to prior value. But schema changes are infrequent
1453 ** and the probability of hitting the same cookie value is only
1454 ** 1 chance in 2^32. So we're safe enough.
1456 void sqlite3ChangeCookie(Parse *pParse, int iDb){
1457 int r1 = sqlite3GetTempReg(pParse);
1458 sqlite3 *db = pParse->db;
1459 Vdbe *v = pParse->pVdbe;
1460 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1461 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
1462 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
1463 sqlite3ReleaseTempReg(pParse, r1);
1467 ** Measure the number of characters needed to output the given
1468 ** identifier. The number returned includes any quotes used
1469 ** but does not include the null terminator.
1471 ** The estimate is conservative. It might be larger that what is
1472 ** really needed.
1474 static int identLength(const char *z){
1475 int n;
1476 for(n=0; *z; n++, z++){
1477 if( *z=='"' ){ n++; }
1479 return n + 2;
1483 ** The first parameter is a pointer to an output buffer. The second
1484 ** parameter is a pointer to an integer that contains the offset at
1485 ** which to write into the output buffer. This function copies the
1486 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1487 ** to the specified offset in the buffer and updates *pIdx to refer
1488 ** to the first byte after the last byte written before returning.
1490 ** If the string zSignedIdent consists entirely of alpha-numeric
1491 ** characters, does not begin with a digit and is not an SQL keyword,
1492 ** then it is copied to the output buffer exactly as it is. Otherwise,
1493 ** it is quoted using double-quotes.
1495 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1496 unsigned char *zIdent = (unsigned char*)zSignedIdent;
1497 int i, j, needQuote;
1498 i = *pIdx;
1500 for(j=0; zIdent[j]; j++){
1501 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1503 needQuote = sqlite3Isdigit(zIdent[0])
1504 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1505 || zIdent[j]!=0
1506 || j==0;
1508 if( needQuote ) z[i++] = '"';
1509 for(j=0; zIdent[j]; j++){
1510 z[i++] = zIdent[j];
1511 if( zIdent[j]=='"' ) z[i++] = '"';
1513 if( needQuote ) z[i++] = '"';
1514 z[i] = 0;
1515 *pIdx = i;
1519 ** Generate a CREATE TABLE statement appropriate for the given
1520 ** table. Memory to hold the text of the statement is obtained
1521 ** from sqliteMalloc() and must be freed by the calling function.
1523 static char *createTableStmt(sqlite3 *db, Table *p){
1524 int i, k, n;
1525 char *zStmt;
1526 char *zSep, *zSep2, *zEnd;
1527 Column *pCol;
1528 n = 0;
1529 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1530 n += identLength(pCol->zName) + 5;
1532 n += identLength(p->zName);
1533 if( n<50 ){
1534 zSep = "";
1535 zSep2 = ",";
1536 zEnd = ")";
1537 }else{
1538 zSep = "\n ";
1539 zSep2 = ",\n ";
1540 zEnd = "\n)";
1542 n += 35 + 6*p->nCol;
1543 zStmt = sqlite3DbMallocRaw(0, n);
1544 if( zStmt==0 ){
1545 db->mallocFailed = 1;
1546 return 0;
1548 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1549 k = sqlite3Strlen30(zStmt);
1550 identPut(zStmt, &k, p->zName);
1551 zStmt[k++] = '(';
1552 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1553 static const char * const azType[] = {
1554 /* SQLITE_AFF_NONE */ "",
1555 /* SQLITE_AFF_TEXT */ " TEXT",
1556 /* SQLITE_AFF_NUMERIC */ " NUM",
1557 /* SQLITE_AFF_INTEGER */ " INT",
1558 /* SQLITE_AFF_REAL */ " REAL"
1560 int len;
1561 const char *zType;
1563 sqlite3_snprintf(n-k, &zStmt[k], zSep);
1564 k += sqlite3Strlen30(&zStmt[k]);
1565 zSep = zSep2;
1566 identPut(zStmt, &k, pCol->zName);
1567 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
1568 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
1569 testcase( pCol->affinity==SQLITE_AFF_NONE );
1570 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1571 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1572 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1573 testcase( pCol->affinity==SQLITE_AFF_REAL );
1575 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
1576 len = sqlite3Strlen30(zType);
1577 assert( pCol->affinity==SQLITE_AFF_NONE
1578 || pCol->affinity==sqlite3AffinityType(zType, 0) );
1579 memcpy(&zStmt[k], zType, len);
1580 k += len;
1581 assert( k<=n );
1583 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1584 return zStmt;
1588 ** Resize an Index object to hold N columns total. Return SQLITE_OK
1589 ** on success and SQLITE_NOMEM on an OOM error.
1591 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1592 char *zExtra;
1593 int nByte;
1594 if( pIdx->nColumn>=N ) return SQLITE_OK;
1595 assert( pIdx->isResized==0 );
1596 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1597 zExtra = sqlite3DbMallocZero(db, nByte);
1598 if( zExtra==0 ) return SQLITE_NOMEM;
1599 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1600 pIdx->azColl = (char**)zExtra;
1601 zExtra += sizeof(char*)*N;
1602 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1603 pIdx->aiColumn = (i16*)zExtra;
1604 zExtra += sizeof(i16)*N;
1605 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1606 pIdx->aSortOrder = (u8*)zExtra;
1607 pIdx->nColumn = N;
1608 pIdx->isResized = 1;
1609 return SQLITE_OK;
1613 ** Estimate the total row width for a table.
1615 static void estimateTableWidth(Table *pTab){
1616 unsigned wTable = 0;
1617 const Column *pTabCol;
1618 int i;
1619 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1620 wTable += pTabCol->szEst;
1622 if( pTab->iPKey<0 ) wTable++;
1623 pTab->szTabRow = sqlite3LogEst(wTable*4);
1627 ** Estimate the average size of a row for an index.
1629 static void estimateIndexWidth(Index *pIdx){
1630 unsigned wIndex = 0;
1631 int i;
1632 const Column *aCol = pIdx->pTable->aCol;
1633 for(i=0; i<pIdx->nColumn; i++){
1634 i16 x = pIdx->aiColumn[i];
1635 assert( x<pIdx->pTable->nCol );
1636 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
1638 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
1641 /* Return true if value x is found any of the first nCol entries of aiCol[]
1643 static int hasColumn(const i16 *aiCol, int nCol, int x){
1644 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1645 return 0;
1649 ** This routine runs at the end of parsing a CREATE TABLE statement that
1650 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
1651 ** internal schema data structures and the generated VDBE code so that they
1652 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1653 ** Changes include:
1655 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1656 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1657 ** data storage is a covering index btree.
1658 ** (2) Bypass the creation of the sqlite_master table entry
1659 ** for the PRIMARY KEY as the primary key index is now
1660 ** identified by the sqlite_master table entry of the table itself.
1661 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1662 ** schema to the rootpage from the main table.
1663 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1664 ** (5) Add all table columns to the PRIMARY KEY Index object
1665 ** so that the PRIMARY KEY is a covering index. The surplus
1666 ** columns are part of KeyInfo.nXField and are not used for
1667 ** sorting or lookup or uniqueness checks.
1668 ** (6) Replace the rowid tail on all automatically generated UNIQUE
1669 ** indices with the PRIMARY KEY columns.
1671 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1672 Index *pIdx;
1673 Index *pPk;
1674 int nPk;
1675 int i, j;
1676 sqlite3 *db = pParse->db;
1677 Vdbe *v = pParse->pVdbe;
1679 /* Convert the OP_CreateTable opcode that would normally create the
1680 ** root-page for the table into an OP_CreateIndex opcode. The index
1681 ** created will become the PRIMARY KEY index.
1683 if( pParse->addrCrTab ){
1684 assert( v );
1685 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1688 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1689 ** table entry.
1691 if( pParse->addrSkipPK ){
1692 assert( v );
1693 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
1696 /* Locate the PRIMARY KEY index. Or, if this table was originally
1697 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1699 if( pTab->iPKey>=0 ){
1700 ExprList *pList;
1701 pList = sqlite3ExprListAppend(pParse, 0, 0);
1702 if( pList==0 ) return;
1703 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1704 pTab->aCol[pTab->iPKey].zName);
1705 pList->a[0].sortOrder = pParse->iPkSortOrder;
1706 assert( pParse->pNewTable==pTab );
1707 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1708 if( pPk==0 ) return;
1709 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
1710 pTab->iPKey = -1;
1711 }else{
1712 pPk = sqlite3PrimaryKeyIndex(pTab);
1714 pPk->isCovering = 1;
1715 assert( pPk!=0 );
1716 nPk = pPk->nKeyCol;
1718 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1719 for(i=0; i<nPk; i++){
1720 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1722 pPk->uniqNotNull = 1;
1724 /* The root page of the PRIMARY KEY is the table root page */
1725 pPk->tnum = pTab->tnum;
1727 /* Update the in-memory representation of all UNIQUE indices by converting
1728 ** the final rowid column into one or more columns of the PRIMARY KEY.
1730 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1731 int n;
1732 if( IsPrimaryKeyIndex(pIdx) ) continue;
1733 for(i=n=0; i<nPk; i++){
1734 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1736 if( n==0 ){
1737 /* This index is a superset of the primary key */
1738 pIdx->nColumn = pIdx->nKeyCol;
1739 continue;
1741 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1742 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
1743 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
1744 pIdx->aiColumn[j] = pPk->aiColumn[i];
1745 pIdx->azColl[j] = pPk->azColl[i];
1746 j++;
1749 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1750 assert( pIdx->nColumn>=j );
1753 /* Add all table columns to the PRIMARY KEY index
1755 if( nPk<pTab->nCol ){
1756 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1757 for(i=0, j=nPk; i<pTab->nCol; i++){
1758 if( !hasColumn(pPk->aiColumn, j, i) ){
1759 assert( j<pPk->nColumn );
1760 pPk->aiColumn[j] = i;
1761 pPk->azColl[j] = "BINARY";
1762 j++;
1765 assert( pPk->nColumn==j );
1766 assert( pTab->nCol==j );
1767 }else{
1768 pPk->nColumn = pTab->nCol;
1773 ** This routine is called to report the final ")" that terminates
1774 ** a CREATE TABLE statement.
1776 ** The table structure that other action routines have been building
1777 ** is added to the internal hash tables, assuming no errors have
1778 ** occurred.
1780 ** An entry for the table is made in the master table on disk, unless
1781 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1782 ** it means we are reading the sqlite_master table because we just
1783 ** connected to the database or because the sqlite_master table has
1784 ** recently changed, so the entry for this table already exists in
1785 ** the sqlite_master table. We do not want to create it again.
1787 ** If the pSelect argument is not NULL, it means that this routine
1788 ** was called to create a table generated from a
1789 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1790 ** the new table will match the result set of the SELECT.
1792 void sqlite3EndTable(
1793 Parse *pParse, /* Parse context */
1794 Token *pCons, /* The ',' token after the last column defn. */
1795 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1796 u8 tabOpts, /* Extra table options. Usually 0. */
1797 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1799 Table *p; /* The new table */
1800 sqlite3 *db = pParse->db; /* The database connection */
1801 int iDb; /* Database in which the table lives */
1802 Index *pIdx; /* An implied index of the table */
1804 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1805 return;
1807 p = pParse->pNewTable;
1808 if( p==0 ) return;
1810 assert( !db->init.busy || !pSelect );
1812 /* If the db->init.busy is 1 it means we are reading the SQL off the
1813 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1814 ** So do not write to the disk again. Extract the root page number
1815 ** for the table from the db->init.newTnum field. (The page number
1816 ** should have been put there by the sqliteOpenCb routine.)
1818 if( db->init.busy ){
1819 p->tnum = db->init.newTnum;
1822 /* Special processing for WITHOUT ROWID Tables */
1823 if( tabOpts & TF_WithoutRowid ){
1824 if( (p->tabFlags & TF_Autoincrement) ){
1825 sqlite3ErrorMsg(pParse,
1826 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1827 return;
1829 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
1830 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
1831 }else{
1832 p->tabFlags |= TF_WithoutRowid;
1833 convertToWithoutRowidTable(pParse, p);
1837 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1839 #ifndef SQLITE_OMIT_CHECK
1840 /* Resolve names in all CHECK constraint expressions.
1842 if( p->pCheck ){
1843 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
1845 #endif /* !defined(SQLITE_OMIT_CHECK) */
1847 /* Estimate the average row size for the table and for all implied indices */
1848 estimateTableWidth(p);
1849 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1850 estimateIndexWidth(pIdx);
1853 /* If not initializing, then create a record for the new table
1854 ** in the SQLITE_MASTER table of the database.
1856 ** If this is a TEMPORARY table, write the entry into the auxiliary
1857 ** file instead of into the main database file.
1859 if( !db->init.busy ){
1860 int n;
1861 Vdbe *v;
1862 char *zType; /* "view" or "table" */
1863 char *zType2; /* "VIEW" or "TABLE" */
1864 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
1866 v = sqlite3GetVdbe(pParse);
1867 if( NEVER(v==0) ) return;
1869 sqlite3VdbeAddOp1(v, OP_Close, 0);
1872 ** Initialize zType for the new view or table.
1874 if( p->pSelect==0 ){
1875 /* A regular table */
1876 zType = "table";
1877 zType2 = "TABLE";
1878 #ifndef SQLITE_OMIT_VIEW
1879 }else{
1880 /* A view */
1881 zType = "view";
1882 zType2 = "VIEW";
1883 #endif
1886 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1887 ** statement to populate the new table. The root-page number for the
1888 ** new table is in register pParse->regRoot.
1890 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1891 ** suitable state to query for the column names and types to be used
1892 ** by the new table.
1894 ** A shared-cache write-lock is not required to write to the new table,
1895 ** as a schema-lock must have already been obtained to create it. Since
1896 ** a schema-lock excludes all other database users, the write-lock would
1897 ** be redundant.
1899 if( pSelect ){
1900 SelectDest dest;
1901 Table *pSelTab;
1903 assert(pParse->nTab==1);
1904 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
1905 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
1906 pParse->nTab = 2;
1907 sqlite3SelectDestInit(&dest, SRT_Table, 1);
1908 sqlite3Select(pParse, pSelect, &dest);
1909 sqlite3VdbeAddOp1(v, OP_Close, 1);
1910 if( pParse->nErr==0 ){
1911 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1912 if( pSelTab==0 ) return;
1913 assert( p->aCol==0 );
1914 p->nCol = pSelTab->nCol;
1915 p->aCol = pSelTab->aCol;
1916 pSelTab->nCol = 0;
1917 pSelTab->aCol = 0;
1918 sqlite3DeleteTable(db, pSelTab);
1922 /* Compute the complete text of the CREATE statement */
1923 if( pSelect ){
1924 zStmt = createTableStmt(db, p);
1925 }else{
1926 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1927 n = (int)(pEnd2->z - pParse->sNameToken.z);
1928 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
1929 zStmt = sqlite3MPrintf(db,
1930 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1934 /* A slot for the record has already been allocated in the
1935 ** SQLITE_MASTER table. We just need to update that slot with all
1936 ** the information we've collected.
1938 sqlite3NestedParse(pParse,
1939 "UPDATE %Q.%s "
1940 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1941 "WHERE rowid=#%d",
1942 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1943 zType,
1944 p->zName,
1945 p->zName,
1946 pParse->regRoot,
1947 zStmt,
1948 pParse->regRowid
1950 sqlite3DbFree(db, zStmt);
1951 sqlite3ChangeCookie(pParse, iDb);
1953 #ifndef SQLITE_OMIT_AUTOINCREMENT
1954 /* Check to see if we need to create an sqlite_sequence table for
1955 ** keeping track of autoincrement keys.
1957 if( p->tabFlags & TF_Autoincrement ){
1958 Db *pDb = &db->aDb[iDb];
1959 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1960 if( pDb->pSchema->pSeqTab==0 ){
1961 sqlite3NestedParse(pParse,
1962 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1963 pDb->zName
1967 #endif
1969 /* Reparse everything to update our internal data structures */
1970 sqlite3VdbeAddParseSchemaOp(v, iDb,
1971 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
1975 /* Add the table to the in-memory representation of the database.
1977 if( db->init.busy ){
1978 Table *pOld;
1979 Schema *pSchema = p->pSchema;
1980 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1981 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
1982 if( pOld ){
1983 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1984 db->mallocFailed = 1;
1985 return;
1987 pParse->pNewTable = 0;
1988 db->flags |= SQLITE_InternChanges;
1990 #ifndef SQLITE_OMIT_ALTERTABLE
1991 if( !p->pSelect ){
1992 const char *zName = (const char *)pParse->sNameToken.z;
1993 int nName;
1994 assert( !pSelect && pCons && pEnd );
1995 if( pCons->z==0 ){
1996 pCons = pEnd;
1998 nName = (int)((const char *)pCons->z - zName);
1999 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
2001 #endif
2005 #ifndef SQLITE_OMIT_VIEW
2007 ** The parser calls this routine in order to create a new VIEW
2009 void sqlite3CreateView(
2010 Parse *pParse, /* The parsing context */
2011 Token *pBegin, /* The CREATE token that begins the statement */
2012 Token *pName1, /* The token that holds the name of the view */
2013 Token *pName2, /* The token that holds the name of the view */
2014 Select *pSelect, /* A SELECT statement that will become the new view */
2015 int isTemp, /* TRUE for a TEMPORARY view */
2016 int noErr /* Suppress error messages if VIEW already exists */
2018 Table *p;
2019 int n;
2020 const char *z;
2021 Token sEnd;
2022 DbFixer sFix;
2023 Token *pName = 0;
2024 int iDb;
2025 sqlite3 *db = pParse->db;
2027 if( pParse->nVar>0 ){
2028 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2029 sqlite3SelectDelete(db, pSelect);
2030 return;
2032 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2033 p = pParse->pNewTable;
2034 if( p==0 || pParse->nErr ){
2035 sqlite3SelectDelete(db, pSelect);
2036 return;
2038 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2039 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2040 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2041 if( sqlite3FixSelect(&sFix, pSelect) ){
2042 sqlite3SelectDelete(db, pSelect);
2043 return;
2046 /* Make a copy of the entire SELECT statement that defines the view.
2047 ** This will force all the Expr.token.z values to be dynamically
2048 ** allocated rather than point to the input string - which means that
2049 ** they will persist after the current sqlite3_exec() call returns.
2051 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
2052 sqlite3SelectDelete(db, pSelect);
2053 if( db->mallocFailed ){
2054 return;
2056 if( !db->init.busy ){
2057 sqlite3ViewGetColumnNames(pParse, p);
2060 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2061 ** the end.
2063 sEnd = pParse->sLastToken;
2064 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
2065 sEnd.z += sEnd.n;
2067 sEnd.n = 0;
2068 n = (int)(sEnd.z - pBegin->z);
2069 z = pBegin->z;
2070 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
2071 sEnd.z = &z[n-1];
2072 sEnd.n = 1;
2074 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
2075 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
2076 return;
2078 #endif /* SQLITE_OMIT_VIEW */
2080 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2082 ** The Table structure pTable is really a VIEW. Fill in the names of
2083 ** the columns of the view in the pTable structure. Return the number
2084 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
2086 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
2087 Table *pSelTab; /* A fake table from which we get the result set */
2088 Select *pSel; /* Copy of the SELECT that implements the view */
2089 int nErr = 0; /* Number of errors encountered */
2090 int n; /* Temporarily holds the number of cursors assigned */
2091 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
2092 sqlite3_xauth xAuth; /* Saved xAuth pointer */
2094 assert( pTable );
2096 #ifndef SQLITE_OMIT_VIRTUALTABLE
2097 if( sqlite3VtabCallConnect(pParse, pTable) ){
2098 return SQLITE_ERROR;
2100 if( IsVirtual(pTable) ) return 0;
2101 #endif
2103 #ifndef SQLITE_OMIT_VIEW
2104 /* A positive nCol means the columns names for this view are
2105 ** already known.
2107 if( pTable->nCol>0 ) return 0;
2109 /* A negative nCol is a special marker meaning that we are currently
2110 ** trying to compute the column names. If we enter this routine with
2111 ** a negative nCol, it means two or more views form a loop, like this:
2113 ** CREATE VIEW one AS SELECT * FROM two;
2114 ** CREATE VIEW two AS SELECT * FROM one;
2116 ** Actually, the error above is now caught prior to reaching this point.
2117 ** But the following test is still important as it does come up
2118 ** in the following:
2120 ** CREATE TABLE main.ex1(a);
2121 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2122 ** SELECT * FROM temp.ex1;
2124 if( pTable->nCol<0 ){
2125 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
2126 return 1;
2128 assert( pTable->nCol>=0 );
2130 /* If we get this far, it means we need to compute the table names.
2131 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2132 ** "*" elements in the results set of the view and will assign cursors
2133 ** to the elements of the FROM clause. But we do not want these changes
2134 ** to be permanent. So the computation is done on a copy of the SELECT
2135 ** statement that defines the view.
2137 assert( pTable->pSelect );
2138 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2139 if( pSel ){
2140 u8 enableLookaside = db->lookaside.bEnabled;
2141 n = pParse->nTab;
2142 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2143 pTable->nCol = -1;
2144 db->lookaside.bEnabled = 0;
2145 #ifndef SQLITE_OMIT_AUTHORIZATION
2146 xAuth = db->xAuth;
2147 db->xAuth = 0;
2148 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2149 db->xAuth = xAuth;
2150 #else
2151 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2152 #endif
2153 db->lookaside.bEnabled = enableLookaside;
2154 pParse->nTab = n;
2155 if( pSelTab ){
2156 assert( pTable->aCol==0 );
2157 pTable->nCol = pSelTab->nCol;
2158 pTable->aCol = pSelTab->aCol;
2159 pSelTab->nCol = 0;
2160 pSelTab->aCol = 0;
2161 sqlite3DeleteTable(db, pSelTab);
2162 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2163 pTable->pSchema->schemaFlags |= DB_UnresetViews;
2164 }else{
2165 pTable->nCol = 0;
2166 nErr++;
2168 sqlite3SelectDelete(db, pSel);
2169 } else {
2170 nErr++;
2172 #endif /* SQLITE_OMIT_VIEW */
2173 return nErr;
2175 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2177 #ifndef SQLITE_OMIT_VIEW
2179 ** Clear the column names from every VIEW in database idx.
2181 static void sqliteViewResetAll(sqlite3 *db, int idx){
2182 HashElem *i;
2183 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
2184 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
2185 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
2186 Table *pTab = sqliteHashData(i);
2187 if( pTab->pSelect ){
2188 sqliteDeleteColumnNames(db, pTab);
2189 pTab->aCol = 0;
2190 pTab->nCol = 0;
2193 DbClearProperty(db, idx, DB_UnresetViews);
2195 #else
2196 # define sqliteViewResetAll(A,B)
2197 #endif /* SQLITE_OMIT_VIEW */
2200 ** This function is called by the VDBE to adjust the internal schema
2201 ** used by SQLite when the btree layer moves a table root page. The
2202 ** root-page of a table or index in database iDb has changed from iFrom
2203 ** to iTo.
2205 ** Ticket #1728: The symbol table might still contain information
2206 ** on tables and/or indices that are the process of being deleted.
2207 ** If you are unlucky, one of those deleted indices or tables might
2208 ** have the same rootpage number as the real table or index that is
2209 ** being moved. So we cannot stop searching after the first match
2210 ** because the first match might be for one of the deleted indices
2211 ** or tables and not the table/index that is actually being moved.
2212 ** We must continue looping until all tables and indices with
2213 ** rootpage==iFrom have been converted to have a rootpage of iTo
2214 ** in order to be certain that we got the right one.
2216 #ifndef SQLITE_OMIT_AUTOVACUUM
2217 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
2218 HashElem *pElem;
2219 Hash *pHash;
2220 Db *pDb;
2222 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2223 pDb = &db->aDb[iDb];
2224 pHash = &pDb->pSchema->tblHash;
2225 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2226 Table *pTab = sqliteHashData(pElem);
2227 if( pTab->tnum==iFrom ){
2228 pTab->tnum = iTo;
2231 pHash = &pDb->pSchema->idxHash;
2232 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2233 Index *pIdx = sqliteHashData(pElem);
2234 if( pIdx->tnum==iFrom ){
2235 pIdx->tnum = iTo;
2239 #endif
2242 ** Write code to erase the table with root-page iTable from database iDb.
2243 ** Also write code to modify the sqlite_master table and internal schema
2244 ** if a root-page of another table is moved by the btree-layer whilst
2245 ** erasing iTable (this can happen with an auto-vacuum database).
2247 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2248 Vdbe *v = sqlite3GetVdbe(pParse);
2249 int r1 = sqlite3GetTempReg(pParse);
2250 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
2251 sqlite3MayAbort(pParse);
2252 #ifndef SQLITE_OMIT_AUTOVACUUM
2253 /* OP_Destroy stores an in integer r1. If this integer
2254 ** is non-zero, then it is the root page number of a table moved to
2255 ** location iTable. The following code modifies the sqlite_master table to
2256 ** reflect this.
2258 ** The "#NNN" in the SQL is a special constant that means whatever value
2259 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2260 ** token for additional information.
2262 sqlite3NestedParse(pParse,
2263 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2264 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
2265 #endif
2266 sqlite3ReleaseTempReg(pParse, r1);
2270 ** Write VDBE code to erase table pTab and all associated indices on disk.
2271 ** Code to update the sqlite_master tables and internal schema definitions
2272 ** in case a root-page belonging to another table is moved by the btree layer
2273 ** is also added (this can happen with an auto-vacuum database).
2275 static void destroyTable(Parse *pParse, Table *pTab){
2276 #ifdef SQLITE_OMIT_AUTOVACUUM
2277 Index *pIdx;
2278 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2279 destroyRootPage(pParse, pTab->tnum, iDb);
2280 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2281 destroyRootPage(pParse, pIdx->tnum, iDb);
2283 #else
2284 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2285 ** is not defined), then it is important to call OP_Destroy on the
2286 ** table and index root-pages in order, starting with the numerically
2287 ** largest root-page number. This guarantees that none of the root-pages
2288 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2289 ** following were coded:
2291 ** OP_Destroy 4 0
2292 ** ...
2293 ** OP_Destroy 5 0
2295 ** and root page 5 happened to be the largest root-page number in the
2296 ** database, then root page 5 would be moved to page 4 by the
2297 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2298 ** a free-list page.
2300 int iTab = pTab->tnum;
2301 int iDestroyed = 0;
2303 while( 1 ){
2304 Index *pIdx;
2305 int iLargest = 0;
2307 if( iDestroyed==0 || iTab<iDestroyed ){
2308 iLargest = iTab;
2310 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2311 int iIdx = pIdx->tnum;
2312 assert( pIdx->pSchema==pTab->pSchema );
2313 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2314 iLargest = iIdx;
2317 if( iLargest==0 ){
2318 return;
2319 }else{
2320 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2321 assert( iDb>=0 && iDb<pParse->db->nDb );
2322 destroyRootPage(pParse, iLargest, iDb);
2323 iDestroyed = iLargest;
2326 #endif
2330 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2331 ** after a DROP INDEX or DROP TABLE command.
2333 static void sqlite3ClearStatTables(
2334 Parse *pParse, /* The parsing context */
2335 int iDb, /* The database number */
2336 const char *zType, /* "idx" or "tbl" */
2337 const char *zName /* Name of index or table */
2339 int i;
2340 const char *zDbName = pParse->db->aDb[iDb].zName;
2341 for(i=1; i<=4; i++){
2342 char zTab[24];
2343 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2344 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
2345 sqlite3NestedParse(pParse,
2346 "DELETE FROM %Q.%s WHERE %s=%Q",
2347 zDbName, zTab, zType, zName
2354 ** Generate code to drop a table.
2356 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2357 Vdbe *v;
2358 sqlite3 *db = pParse->db;
2359 Trigger *pTrigger;
2360 Db *pDb = &db->aDb[iDb];
2362 v = sqlite3GetVdbe(pParse);
2363 assert( v!=0 );
2364 sqlite3BeginWriteOperation(pParse, 1, iDb);
2366 #ifndef SQLITE_OMIT_VIRTUALTABLE
2367 if( IsVirtual(pTab) ){
2368 sqlite3VdbeAddOp0(v, OP_VBegin);
2370 #endif
2372 /* Drop all triggers associated with the table being dropped. Code
2373 ** is generated to remove entries from sqlite_master and/or
2374 ** sqlite_temp_master if required.
2376 pTrigger = sqlite3TriggerList(pParse, pTab);
2377 while( pTrigger ){
2378 assert( pTrigger->pSchema==pTab->pSchema ||
2379 pTrigger->pSchema==db->aDb[1].pSchema );
2380 sqlite3DropTriggerPtr(pParse, pTrigger);
2381 pTrigger = pTrigger->pNext;
2384 #ifndef SQLITE_OMIT_AUTOINCREMENT
2385 /* Remove any entries of the sqlite_sequence table associated with
2386 ** the table being dropped. This is done before the table is dropped
2387 ** at the btree level, in case the sqlite_sequence table needs to
2388 ** move as a result of the drop (can happen in auto-vacuum mode).
2390 if( pTab->tabFlags & TF_Autoincrement ){
2391 sqlite3NestedParse(pParse,
2392 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2393 pDb->zName, pTab->zName
2396 #endif
2398 /* Drop all SQLITE_MASTER table and index entries that refer to the
2399 ** table. The program name loops through the master table and deletes
2400 ** every row that refers to a table of the same name as the one being
2401 ** dropped. Triggers are handled separately because a trigger can be
2402 ** created in the temp database that refers to a table in another
2403 ** database.
2405 sqlite3NestedParse(pParse,
2406 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2407 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2408 if( !isView && !IsVirtual(pTab) ){
2409 destroyTable(pParse, pTab);
2412 /* Remove the table entry from SQLite's internal schema and modify
2413 ** the schema cookie.
2415 if( IsVirtual(pTab) ){
2416 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2418 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2419 sqlite3ChangeCookie(pParse, iDb);
2420 sqliteViewResetAll(db, iDb);
2424 ** This routine is called to do the work of a DROP TABLE statement.
2425 ** pName is the name of the table to be dropped.
2427 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
2428 Table *pTab;
2429 Vdbe *v;
2430 sqlite3 *db = pParse->db;
2431 int iDb;
2433 if( db->mallocFailed ){
2434 goto exit_drop_table;
2436 assert( pParse->nErr==0 );
2437 assert( pName->nSrc==1 );
2438 if( noErr ) db->suppressErr++;
2439 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
2440 if( noErr ) db->suppressErr--;
2442 if( pTab==0 ){
2443 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2444 goto exit_drop_table;
2446 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2447 assert( iDb>=0 && iDb<db->nDb );
2449 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2450 ** it is initialized.
2452 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2453 goto exit_drop_table;
2455 #ifndef SQLITE_OMIT_AUTHORIZATION
2457 int code;
2458 const char *zTab = SCHEMA_TABLE(iDb);
2459 const char *zDb = db->aDb[iDb].zName;
2460 const char *zArg2 = 0;
2461 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
2462 goto exit_drop_table;
2464 if( isView ){
2465 if( !OMIT_TEMPDB && iDb==1 ){
2466 code = SQLITE_DROP_TEMP_VIEW;
2467 }else{
2468 code = SQLITE_DROP_VIEW;
2470 #ifndef SQLITE_OMIT_VIRTUALTABLE
2471 }else if( IsVirtual(pTab) ){
2472 code = SQLITE_DROP_VTABLE;
2473 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
2474 #endif
2475 }else{
2476 if( !OMIT_TEMPDB && iDb==1 ){
2477 code = SQLITE_DROP_TEMP_TABLE;
2478 }else{
2479 code = SQLITE_DROP_TABLE;
2482 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2483 goto exit_drop_table;
2485 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2486 goto exit_drop_table;
2489 #endif
2490 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2491 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
2492 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2493 goto exit_drop_table;
2496 #ifndef SQLITE_OMIT_VIEW
2497 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2498 ** on a table.
2500 if( isView && pTab->pSelect==0 ){
2501 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2502 goto exit_drop_table;
2504 if( !isView && pTab->pSelect ){
2505 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2506 goto exit_drop_table;
2508 #endif
2510 /* Generate code to remove the table from the master table
2511 ** on disk.
2513 v = sqlite3GetVdbe(pParse);
2514 if( v ){
2515 sqlite3BeginWriteOperation(pParse, 1, iDb);
2516 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
2517 sqlite3FkDropTable(pParse, pName, pTab);
2518 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
2521 exit_drop_table:
2522 sqlite3SrcListDelete(db, pName);
2526 ** This routine is called to create a new foreign key on the table
2527 ** currently under construction. pFromCol determines which columns
2528 ** in the current table point to the foreign key. If pFromCol==0 then
2529 ** connect the key to the last column inserted. pTo is the name of
2530 ** the table referred to (a.k.a the "parent" table). pToCol is a list
2531 ** of tables in the parent pTo table. flags contains all
2532 ** information about the conflict resolution algorithms specified
2533 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2535 ** An FKey structure is created and added to the table currently
2536 ** under construction in the pParse->pNewTable field.
2538 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2539 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2541 void sqlite3CreateForeignKey(
2542 Parse *pParse, /* Parsing context */
2543 ExprList *pFromCol, /* Columns in this table that point to other table */
2544 Token *pTo, /* Name of the other table */
2545 ExprList *pToCol, /* Columns in the other table */
2546 int flags /* Conflict resolution algorithms. */
2548 sqlite3 *db = pParse->db;
2549 #ifndef SQLITE_OMIT_FOREIGN_KEY
2550 FKey *pFKey = 0;
2551 FKey *pNextTo;
2552 Table *p = pParse->pNewTable;
2553 int nByte;
2554 int i;
2555 int nCol;
2556 char *z;
2558 assert( pTo!=0 );
2559 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2560 if( pFromCol==0 ){
2561 int iCol = p->nCol-1;
2562 if( NEVER(iCol<0) ) goto fk_end;
2563 if( pToCol && pToCol->nExpr!=1 ){
2564 sqlite3ErrorMsg(pParse, "foreign key on %s"
2565 " should reference only one column of table %T",
2566 p->aCol[iCol].zName, pTo);
2567 goto fk_end;
2569 nCol = 1;
2570 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2571 sqlite3ErrorMsg(pParse,
2572 "number of columns in foreign key does not match the number of "
2573 "columns in the referenced table");
2574 goto fk_end;
2575 }else{
2576 nCol = pFromCol->nExpr;
2578 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2579 if( pToCol ){
2580 for(i=0; i<pToCol->nExpr; i++){
2581 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2584 pFKey = sqlite3DbMallocZero(db, nByte );
2585 if( pFKey==0 ){
2586 goto fk_end;
2588 pFKey->pFrom = p;
2589 pFKey->pNextFrom = p->pFKey;
2590 z = (char*)&pFKey->aCol[nCol];
2591 pFKey->zTo = z;
2592 memcpy(z, pTo->z, pTo->n);
2593 z[pTo->n] = 0;
2594 sqlite3Dequote(z);
2595 z += pTo->n+1;
2596 pFKey->nCol = nCol;
2597 if( pFromCol==0 ){
2598 pFKey->aCol[0].iFrom = p->nCol-1;
2599 }else{
2600 for(i=0; i<nCol; i++){
2601 int j;
2602 for(j=0; j<p->nCol; j++){
2603 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2604 pFKey->aCol[i].iFrom = j;
2605 break;
2608 if( j>=p->nCol ){
2609 sqlite3ErrorMsg(pParse,
2610 "unknown column \"%s\" in foreign key definition",
2611 pFromCol->a[i].zName);
2612 goto fk_end;
2616 if( pToCol ){
2617 for(i=0; i<nCol; i++){
2618 int n = sqlite3Strlen30(pToCol->a[i].zName);
2619 pFKey->aCol[i].zCol = z;
2620 memcpy(z, pToCol->a[i].zName, n);
2621 z[n] = 0;
2622 z += n+1;
2625 pFKey->isDeferred = 0;
2626 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2627 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
2629 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2630 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2631 pFKey->zTo, (void *)pFKey
2633 if( pNextTo==pFKey ){
2634 db->mallocFailed = 1;
2635 goto fk_end;
2637 if( pNextTo ){
2638 assert( pNextTo->pPrevTo==0 );
2639 pFKey->pNextTo = pNextTo;
2640 pNextTo->pPrevTo = pFKey;
2643 /* Link the foreign key to the table as the last step.
2645 p->pFKey = pFKey;
2646 pFKey = 0;
2648 fk_end:
2649 sqlite3DbFree(db, pFKey);
2650 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2651 sqlite3ExprListDelete(db, pFromCol);
2652 sqlite3ExprListDelete(db, pToCol);
2656 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2657 ** clause is seen as part of a foreign key definition. The isDeferred
2658 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2659 ** The behavior of the most recently created foreign key is adjusted
2660 ** accordingly.
2662 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2663 #ifndef SQLITE_OMIT_FOREIGN_KEY
2664 Table *pTab;
2665 FKey *pFKey;
2666 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2667 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
2668 pFKey->isDeferred = (u8)isDeferred;
2669 #endif
2673 ** Generate code that will erase and refill index *pIdx. This is
2674 ** used to initialize a newly created index or to recompute the
2675 ** content of an index in response to a REINDEX command.
2677 ** if memRootPage is not negative, it means that the index is newly
2678 ** created. The register specified by memRootPage contains the
2679 ** root page number of the index. If memRootPage is negative, then
2680 ** the index already exists and must be cleared before being refilled and
2681 ** the root page number of the index is taken from pIndex->tnum.
2683 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2684 Table *pTab = pIndex->pTable; /* The table that is indexed */
2685 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2686 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
2687 int iSorter; /* Cursor opened by OpenSorter (if in use) */
2688 int addr1; /* Address of top of loop */
2689 int addr2; /* Address to jump to for next iteration */
2690 int tnum; /* Root page of index */
2691 int iPartIdxLabel; /* Jump to this label to skip a row */
2692 Vdbe *v; /* Generate code into this virtual machine */
2693 KeyInfo *pKey; /* KeyInfo for index */
2694 int regRecord; /* Register holding assembled index record */
2695 sqlite3 *db = pParse->db; /* The database connection */
2696 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2698 #ifndef SQLITE_OMIT_AUTHORIZATION
2699 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2700 db->aDb[iDb].zName ) ){
2701 return;
2703 #endif
2705 /* Require a write-lock on the table to perform this operation */
2706 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2708 v = sqlite3GetVdbe(pParse);
2709 if( v==0 ) return;
2710 if( memRootPage>=0 ){
2711 tnum = memRootPage;
2712 }else{
2713 tnum = pIndex->tnum;
2715 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
2717 /* Open the sorter cursor if we are to use one. */
2718 iSorter = pParse->nTab++;
2719 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
2720 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
2722 /* Open the table. Loop through all rows of the table, inserting index
2723 ** records into the sorter. */
2724 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2725 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
2726 regRecord = sqlite3GetTempReg(pParse);
2728 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
2729 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
2730 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
2731 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
2732 sqlite3VdbeJumpHere(v, addr1);
2733 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2734 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
2735 (char *)pKey, P4_KEYINFO);
2736 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2738 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
2739 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
2740 if( IsUniqueIndex(pIndex) && pKey!=0 ){
2741 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2742 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2743 addr2 = sqlite3VdbeCurrentAddr(v);
2744 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
2745 pIndex->nKeyCol); VdbeCoverage(v);
2746 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
2747 }else{
2748 addr2 = sqlite3VdbeCurrentAddr(v);
2750 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
2751 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2752 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2753 sqlite3ReleaseTempReg(pParse, regRecord);
2754 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
2755 sqlite3VdbeJumpHere(v, addr1);
2757 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2758 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
2759 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
2763 ** Allocate heap space to hold an Index object with nCol columns.
2765 ** Increase the allocation size to provide an extra nExtra bytes
2766 ** of 8-byte aligned space after the Index object and return a
2767 ** pointer to this extra space in *ppExtra.
2769 Index *sqlite3AllocateIndexObject(
2770 sqlite3 *db, /* Database connection */
2771 i16 nCol, /* Total number of columns in the index */
2772 int nExtra, /* Number of bytes of extra space to alloc */
2773 char **ppExtra /* Pointer to the "extra" space */
2775 Index *p; /* Allocated index object */
2776 int nByte; /* Bytes of space for Index object + arrays */
2778 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2779 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
2780 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
2781 sizeof(i16)*nCol + /* Index.aiColumn */
2782 sizeof(u8)*nCol); /* Index.aSortOrder */
2783 p = sqlite3DbMallocZero(db, nByte + nExtra);
2784 if( p ){
2785 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
2786 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2787 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2788 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
2789 p->aSortOrder = (u8*)pExtra;
2790 p->nColumn = nCol;
2791 p->nKeyCol = nCol - 1;
2792 *ppExtra = ((char*)p) + nByte;
2794 return p;
2798 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2799 ** and pTblList is the name of the table that is to be indexed. Both will
2800 ** be NULL for a primary key or an index that is created to satisfy a
2801 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2802 ** as the table to be indexed. pParse->pNewTable is a table that is
2803 ** currently being constructed by a CREATE TABLE statement.
2805 ** pList is a list of columns to be indexed. pList will be NULL if this
2806 ** is a primary key or unique-constraint on the most recent column added
2807 ** to the table currently under construction.
2809 ** If the index is created successfully, return a pointer to the new Index
2810 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2811 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
2813 Index *sqlite3CreateIndex(
2814 Parse *pParse, /* All information about this parse */
2815 Token *pName1, /* First part of index name. May be NULL */
2816 Token *pName2, /* Second part of index name. May be NULL */
2817 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2818 ExprList *pList, /* A list of columns to be indexed */
2819 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2820 Token *pStart, /* The CREATE token that begins this statement */
2821 Expr *pPIWhere, /* WHERE clause for partial indices */
2822 int sortOrder, /* Sort order of primary key when pList==NULL */
2823 int ifNotExist /* Omit error if index already exists */
2825 Index *pRet = 0; /* Pointer to return */
2826 Table *pTab = 0; /* Table to be indexed */
2827 Index *pIndex = 0; /* The index to be created */
2828 char *zName = 0; /* Name of the index */
2829 int nName; /* Number of characters in zName */
2830 int i, j;
2831 DbFixer sFix; /* For assigning database names to pTable */
2832 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
2833 sqlite3 *db = pParse->db;
2834 Db *pDb; /* The specific table containing the indexed database */
2835 int iDb; /* Index of the database that is being written */
2836 Token *pName = 0; /* Unqualified name of the index to create */
2837 struct ExprList_item *pListItem; /* For looping over pList */
2838 const Column *pTabCol; /* A column in the table */
2839 int nExtra = 0; /* Space allocated for zExtra[] */
2840 int nExtraCol; /* Number of extra columns needed */
2841 char *zExtra = 0; /* Extra space after the Index object */
2842 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
2844 assert( pParse->nErr==0 ); /* Never called with prior errors */
2845 if( db->mallocFailed || IN_DECLARE_VTAB ){
2846 goto exit_create_index;
2848 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2849 goto exit_create_index;
2853 ** Find the table that is to be indexed. Return early if not found.
2855 if( pTblName!=0 ){
2857 /* Use the two-part index name to determine the database
2858 ** to search for the table. 'Fix' the table name to this db
2859 ** before looking up the table.
2861 assert( pName1 && pName2 );
2862 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2863 if( iDb<0 ) goto exit_create_index;
2864 assert( pName && pName->z );
2866 #ifndef SQLITE_OMIT_TEMPDB
2867 /* If the index name was unqualified, check if the table
2868 ** is a temp table. If so, set the database to 1. Do not do this
2869 ** if initialising a database schema.
2871 if( !db->init.busy ){
2872 pTab = sqlite3SrcListLookup(pParse, pTblName);
2873 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2874 iDb = 1;
2877 #endif
2879 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2880 if( sqlite3FixSrcList(&sFix, pTblName) ){
2881 /* Because the parser constructs pTblName from a single identifier,
2882 ** sqlite3FixSrcList can never fail. */
2883 assert(0);
2885 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
2886 assert( db->mallocFailed==0 || pTab==0 );
2887 if( pTab==0 ) goto exit_create_index;
2888 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2889 sqlite3ErrorMsg(pParse,
2890 "cannot create a TEMP index on non-TEMP table \"%s\"",
2891 pTab->zName);
2892 goto exit_create_index;
2894 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
2895 }else{
2896 assert( pName==0 );
2897 assert( pStart==0 );
2898 pTab = pParse->pNewTable;
2899 if( !pTab ) goto exit_create_index;
2900 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2902 pDb = &db->aDb[iDb];
2904 assert( pTab!=0 );
2905 assert( pParse->nErr==0 );
2906 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2907 && db->init.busy==0
2908 #if SQLITE_USER_AUTHENTICATION
2909 && sqlite3UserAuthTable(pTab->zName)==0
2910 #endif
2911 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
2912 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2913 goto exit_create_index;
2915 #ifndef SQLITE_OMIT_VIEW
2916 if( pTab->pSelect ){
2917 sqlite3ErrorMsg(pParse, "views may not be indexed");
2918 goto exit_create_index;
2920 #endif
2921 #ifndef SQLITE_OMIT_VIRTUALTABLE
2922 if( IsVirtual(pTab) ){
2923 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2924 goto exit_create_index;
2926 #endif
2929 ** Find the name of the index. Make sure there is not already another
2930 ** index or table with the same name.
2932 ** Exception: If we are reading the names of permanent indices from the
2933 ** sqlite_master table (because some other process changed the schema) and
2934 ** one of the index names collides with the name of a temporary table or
2935 ** index, then we will continue to process this index.
2937 ** If pName==0 it means that we are
2938 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2939 ** own name.
2941 if( pName ){
2942 zName = sqlite3NameFromToken(db, pName);
2943 if( zName==0 ) goto exit_create_index;
2944 assert( pName->z!=0 );
2945 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2946 goto exit_create_index;
2948 if( !db->init.busy ){
2949 if( sqlite3FindTable(db, zName, 0)!=0 ){
2950 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2951 goto exit_create_index;
2954 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2955 if( !ifNotExist ){
2956 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2957 }else{
2958 assert( !db->init.busy );
2959 sqlite3CodeVerifySchema(pParse, iDb);
2961 goto exit_create_index;
2963 }else{
2964 int n;
2965 Index *pLoop;
2966 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2967 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
2968 if( zName==0 ){
2969 goto exit_create_index;
2973 /* Check for authorization to create an index.
2975 #ifndef SQLITE_OMIT_AUTHORIZATION
2977 const char *zDb = pDb->zName;
2978 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
2979 goto exit_create_index;
2981 i = SQLITE_CREATE_INDEX;
2982 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2983 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
2984 goto exit_create_index;
2987 #endif
2989 /* If pList==0, it means this routine was called to make a primary
2990 ** key out of the last column added to the table under construction.
2991 ** So create a fake list to simulate this.
2993 if( pList==0 ){
2994 pList = sqlite3ExprListAppend(pParse, 0, 0);
2995 if( pList==0 ) goto exit_create_index;
2996 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2997 pTab->aCol[pTab->nCol-1].zName);
2998 pList->a[0].sortOrder = (u8)sortOrder;
3001 /* Figure out how many bytes of space are required to store explicitly
3002 ** specified collation sequence names.
3004 for(i=0; i<pList->nExpr; i++){
3005 Expr *pExpr = pList->a[i].pExpr;
3006 if( pExpr ){
3007 assert( pExpr->op==TK_COLLATE );
3008 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
3013 ** Allocate the index structure.
3015 nName = sqlite3Strlen30(zName);
3016 nExtraCol = pPk ? pPk->nKeyCol : 1;
3017 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
3018 nName + nExtra + 1, &zExtra);
3019 if( db->mallocFailed ){
3020 goto exit_create_index;
3022 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
3023 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
3024 pIndex->zName = zExtra;
3025 zExtra += nName + 1;
3026 memcpy(pIndex->zName, zName, nName+1);
3027 pIndex->pTable = pTab;
3028 pIndex->onError = (u8)onError;
3029 pIndex->uniqNotNull = onError!=OE_None;
3030 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
3031 pIndex->pSchema = db->aDb[iDb].pSchema;
3032 pIndex->nKeyCol = pList->nExpr;
3033 if( pPIWhere ){
3034 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3035 pIndex->pPartIdxWhere = pPIWhere;
3036 pPIWhere = 0;
3038 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3040 /* Check to see if we should honor DESC requests on index columns
3042 if( pDb->pSchema->file_format>=4 ){
3043 sortOrderMask = -1; /* Honor DESC */
3044 }else{
3045 sortOrderMask = 0; /* Ignore DESC */
3048 /* Scan the names of the columns of the table to be indexed and
3049 ** load the column indices into the Index structure. Report an error
3050 ** if any column is not found.
3052 ** TODO: Add a test to make sure that the same column is not named
3053 ** more than once within the same index. Only the first instance of
3054 ** the column will ever be used by the optimizer. Note that using the
3055 ** same column more than once cannot be an error because that would
3056 ** break backwards compatibility - it needs to be a warning.
3058 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3059 const char *zColName = pListItem->zName;
3060 int requestedSortOrder;
3061 char *zColl; /* Collation sequence name */
3063 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3064 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
3066 if( j>=pTab->nCol ){
3067 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
3068 pTab->zName, zColName);
3069 pParse->checkSchema = 1;
3070 goto exit_create_index;
3072 assert( j<=0x7fff );
3073 pIndex->aiColumn[i] = (i16)j;
3074 if( pListItem->pExpr ){
3075 int nColl;
3076 assert( pListItem->pExpr->op==TK_COLLATE );
3077 zColl = pListItem->pExpr->u.zToken;
3078 nColl = sqlite3Strlen30(zColl) + 1;
3079 assert( nExtra>=nColl );
3080 memcpy(zExtra, zColl, nColl);
3081 zColl = zExtra;
3082 zExtra += nColl;
3083 nExtra -= nColl;
3084 }else{
3085 zColl = pTab->aCol[j].zColl;
3086 if( !zColl ) zColl = "BINARY";
3088 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
3089 goto exit_create_index;
3091 pIndex->azColl[i] = zColl;
3092 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
3093 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3094 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
3096 if( pPk ){
3097 for(j=0; j<pPk->nKeyCol; j++){
3098 int x = pPk->aiColumn[j];
3099 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3100 pIndex->nColumn--;
3101 }else{
3102 pIndex->aiColumn[i] = x;
3103 pIndex->azColl[i] = pPk->azColl[j];
3104 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3105 i++;
3108 assert( i==pIndex->nColumn );
3109 }else{
3110 pIndex->aiColumn[i] = -1;
3111 pIndex->azColl[i] = "BINARY";
3113 sqlite3DefaultRowEst(pIndex);
3114 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
3116 if( pTab==pParse->pNewTable ){
3117 /* This routine has been called to create an automatic index as a
3118 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3119 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3120 ** i.e. one of:
3122 ** CREATE TABLE t(x PRIMARY KEY, y);
3123 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3125 ** Either way, check to see if the table already has such an index. If
3126 ** so, don't bother creating this one. This only applies to
3127 ** automatically created indices. Users can do as they wish with
3128 ** explicit indices.
3130 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3131 ** (and thus suppressing the second one) even if they have different
3132 ** sort orders.
3134 ** If there are different collating sequences or if the columns of
3135 ** the constraint occur in different orders, then the constraints are
3136 ** considered distinct and both result in separate indices.
3138 Index *pIdx;
3139 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3140 int k;
3141 assert( IsUniqueIndex(pIdx) );
3142 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
3143 assert( IsUniqueIndex(pIndex) );
3145 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3146 for(k=0; k<pIdx->nKeyCol; k++){
3147 const char *z1;
3148 const char *z2;
3149 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
3150 z1 = pIdx->azColl[k];
3151 z2 = pIndex->azColl[k];
3152 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
3154 if( k==pIdx->nKeyCol ){
3155 if( pIdx->onError!=pIndex->onError ){
3156 /* This constraint creates the same index as a previous
3157 ** constraint specified somewhere in the CREATE TABLE statement.
3158 ** However the ON CONFLICT clauses are different. If both this
3159 ** constraint and the previous equivalent constraint have explicit
3160 ** ON CONFLICT clauses this is an error. Otherwise, use the
3161 ** explicitly specified behavior for the index.
3163 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3164 sqlite3ErrorMsg(pParse,
3165 "conflicting ON CONFLICT clauses specified", 0);
3167 if( pIdx->onError==OE_Default ){
3168 pIdx->onError = pIndex->onError;
3171 goto exit_create_index;
3176 /* Link the new Index structure to its table and to the other
3177 ** in-memory database structures.
3179 if( db->init.busy ){
3180 Index *p;
3181 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
3182 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
3183 pIndex->zName, pIndex);
3184 if( p ){
3185 assert( p==pIndex ); /* Malloc must have failed */
3186 db->mallocFailed = 1;
3187 goto exit_create_index;
3189 db->flags |= SQLITE_InternChanges;
3190 if( pTblName!=0 ){
3191 pIndex->tnum = db->init.newTnum;
3195 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3196 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3197 ** emit code to allocate the index rootpage on disk and make an entry for
3198 ** the index in the sqlite_master table and populate the index with
3199 ** content. But, do not do this if we are simply reading the sqlite_master
3200 ** table to parse the schema, or if this index is the PRIMARY KEY index
3201 ** of a WITHOUT ROWID table.
3203 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3204 ** or UNIQUE index in a CREATE TABLE statement. Since the table
3205 ** has just been created, it contains no data and the index initialization
3206 ** step can be skipped.
3208 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
3209 Vdbe *v;
3210 char *zStmt;
3211 int iMem = ++pParse->nMem;
3213 v = sqlite3GetVdbe(pParse);
3214 if( v==0 ) goto exit_create_index;
3217 /* Create the rootpage for the index
3219 sqlite3BeginWriteOperation(pParse, 1, iDb);
3220 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
3222 /* Gather the complete text of the CREATE INDEX statement into
3223 ** the zStmt variable
3225 if( pStart ){
3226 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
3227 if( pName->z[n-1]==';' ) n--;
3228 /* A named index with an explicit CREATE INDEX statement */
3229 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
3230 onError==OE_None ? "" : " UNIQUE", n, pName->z);
3231 }else{
3232 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3233 /* zStmt = sqlite3MPrintf(""); */
3234 zStmt = 0;
3237 /* Add an entry in sqlite_master for this index
3239 sqlite3NestedParse(pParse,
3240 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3241 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3242 pIndex->zName,
3243 pTab->zName,
3244 iMem,
3245 zStmt
3247 sqlite3DbFree(db, zStmt);
3249 /* Fill the index with data and reparse the schema. Code an OP_Expire
3250 ** to invalidate all pre-compiled statements.
3252 if( pTblName ){
3253 sqlite3RefillIndex(pParse, pIndex, iMem);
3254 sqlite3ChangeCookie(pParse, iDb);
3255 sqlite3VdbeAddParseSchemaOp(v, iDb,
3256 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
3257 sqlite3VdbeAddOp1(v, OP_Expire, 0);
3261 /* When adding an index to the list of indices for a table, make
3262 ** sure all indices labeled OE_Replace come after all those labeled
3263 ** OE_Ignore. This is necessary for the correct constraint check
3264 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3265 ** UPDATE and INSERT statements.
3267 if( db->init.busy || pTblName==0 ){
3268 if( onError!=OE_Replace || pTab->pIndex==0
3269 || pTab->pIndex->onError==OE_Replace){
3270 pIndex->pNext = pTab->pIndex;
3271 pTab->pIndex = pIndex;
3272 }else{
3273 Index *pOther = pTab->pIndex;
3274 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3275 pOther = pOther->pNext;
3277 pIndex->pNext = pOther->pNext;
3278 pOther->pNext = pIndex;
3280 pRet = pIndex;
3281 pIndex = 0;
3284 /* Clean up before exiting */
3285 exit_create_index:
3286 if( pIndex ) freeIndex(db, pIndex);
3287 sqlite3ExprDelete(db, pPIWhere);
3288 sqlite3ExprListDelete(db, pList);
3289 sqlite3SrcListDelete(db, pTblName);
3290 sqlite3DbFree(db, zName);
3291 return pRet;
3295 ** Fill the Index.aiRowEst[] array with default information - information
3296 ** to be used when we have not run the ANALYZE command.
3298 ** aiRowEst[0] is supposed to contain the number of elements in the index.
3299 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3300 ** number of rows in the table that match any particular value of the
3301 ** first column of the index. aiRowEst[2] is an estimate of the number
3302 ** of rows that match any particular combination of the first 2 columns
3303 ** of the index. And so forth. It must always be the case that
3305 ** aiRowEst[N]<=aiRowEst[N-1]
3306 ** aiRowEst[N]>=1
3308 ** Apart from that, we have little to go on besides intuition as to
3309 ** how aiRowEst[] should be initialized. The numbers generated here
3310 ** are based on typical values found in actual indices.
3312 void sqlite3DefaultRowEst(Index *pIdx){
3313 /* 10, 9, 8, 7, 6 */
3314 LogEst aVal[] = { 33, 32, 30, 28, 26 };
3315 LogEst *a = pIdx->aiRowLogEst;
3316 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
3317 int i;
3319 /* Set the first entry (number of rows in the index) to the estimated
3320 ** number of rows in the table. Or 10, if the estimated number of rows
3321 ** in the table is less than that. */
3322 a[0] = pIdx->pTable->nRowLogEst;
3323 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3325 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3326 ** 6 and each subsequent value (if any) is 5. */
3327 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
3328 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3329 a[i] = 23; assert( 23==sqlite3LogEst(5) );
3332 assert( 0==sqlite3LogEst(1) );
3333 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
3337 ** This routine will drop an existing named index. This routine
3338 ** implements the DROP INDEX statement.
3340 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
3341 Index *pIndex;
3342 Vdbe *v;
3343 sqlite3 *db = pParse->db;
3344 int iDb;
3346 assert( pParse->nErr==0 ); /* Never called with prior errors */
3347 if( db->mallocFailed ){
3348 goto exit_drop_index;
3350 assert( pName->nSrc==1 );
3351 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3352 goto exit_drop_index;
3354 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
3355 if( pIndex==0 ){
3356 if( !ifExists ){
3357 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
3358 }else{
3359 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3361 pParse->checkSchema = 1;
3362 goto exit_drop_index;
3364 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
3365 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
3366 "or PRIMARY KEY constraint cannot be dropped", 0);
3367 goto exit_drop_index;
3369 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3370 #ifndef SQLITE_OMIT_AUTHORIZATION
3372 int code = SQLITE_DROP_INDEX;
3373 Table *pTab = pIndex->pTable;
3374 const char *zDb = db->aDb[iDb].zName;
3375 const char *zTab = SCHEMA_TABLE(iDb);
3376 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
3377 goto exit_drop_index;
3379 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
3380 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
3381 goto exit_drop_index;
3384 #endif
3386 /* Generate code to remove the index and from the master table */
3387 v = sqlite3GetVdbe(pParse);
3388 if( v ){
3389 sqlite3BeginWriteOperation(pParse, 1, iDb);
3390 sqlite3NestedParse(pParse,
3391 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3392 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
3394 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
3395 sqlite3ChangeCookie(pParse, iDb);
3396 destroyRootPage(pParse, pIndex->tnum, iDb);
3397 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
3400 exit_drop_index:
3401 sqlite3SrcListDelete(db, pName);
3405 ** pArray is a pointer to an array of objects. Each object in the
3406 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3407 ** to extend the array so that there is space for a new object at the end.
3409 ** When this function is called, *pnEntry contains the current size of
3410 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3411 ** in total).
3413 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3414 ** space allocated for the new object is zeroed, *pnEntry updated to
3415 ** reflect the new size of the array and a pointer to the new allocation
3416 ** returned. *pIdx is set to the index of the new array entry in this case.
3418 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3419 ** unchanged and a copy of pArray returned.
3421 void *sqlite3ArrayAllocate(
3422 sqlite3 *db, /* Connection to notify of malloc failures */
3423 void *pArray, /* Array of objects. Might be reallocated */
3424 int szEntry, /* Size of each object in the array */
3425 int *pnEntry, /* Number of objects currently in use */
3426 int *pIdx /* Write the index of a new slot here */
3428 char *z;
3429 int n = *pnEntry;
3430 if( (n & (n-1))==0 ){
3431 int sz = (n==0) ? 1 : 2*n;
3432 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
3433 if( pNew==0 ){
3434 *pIdx = -1;
3435 return pArray;
3437 pArray = pNew;
3439 z = (char*)pArray;
3440 memset(&z[n * szEntry], 0, szEntry);
3441 *pIdx = n;
3442 ++*pnEntry;
3443 return pArray;
3447 ** Append a new element to the given IdList. Create a new IdList if
3448 ** need be.
3450 ** A new IdList is returned, or NULL if malloc() fails.
3452 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
3453 int i;
3454 if( pList==0 ){
3455 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3456 if( pList==0 ) return 0;
3458 pList->a = sqlite3ArrayAllocate(
3460 pList->a,
3461 sizeof(pList->a[0]),
3462 &pList->nId,
3465 if( i<0 ){
3466 sqlite3IdListDelete(db, pList);
3467 return 0;
3469 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3470 return pList;
3474 ** Delete an IdList.
3476 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
3477 int i;
3478 if( pList==0 ) return;
3479 for(i=0; i<pList->nId; i++){
3480 sqlite3DbFree(db, pList->a[i].zName);
3482 sqlite3DbFree(db, pList->a);
3483 sqlite3DbFree(db, pList);
3487 ** Return the index in pList of the identifier named zId. Return -1
3488 ** if not found.
3490 int sqlite3IdListIndex(IdList *pList, const char *zName){
3491 int i;
3492 if( pList==0 ) return -1;
3493 for(i=0; i<pList->nId; i++){
3494 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3496 return -1;
3500 ** Expand the space allocated for the given SrcList object by
3501 ** creating nExtra new slots beginning at iStart. iStart is zero based.
3502 ** New slots are zeroed.
3504 ** For example, suppose a SrcList initially contains two entries: A,B.
3505 ** To append 3 new entries onto the end, do this:
3507 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3509 ** After the call above it would contain: A, B, nil, nil, nil.
3510 ** If the iStart argument had been 1 instead of 2, then the result
3511 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
3512 ** the iStart value would be 0. The result then would
3513 ** be: nil, nil, nil, A, B.
3515 ** If a memory allocation fails the SrcList is unchanged. The
3516 ** db->mallocFailed flag will be set to true.
3518 SrcList *sqlite3SrcListEnlarge(
3519 sqlite3 *db, /* Database connection to notify of OOM errors */
3520 SrcList *pSrc, /* The SrcList to be enlarged */
3521 int nExtra, /* Number of new slots to add to pSrc->a[] */
3522 int iStart /* Index in pSrc->a[] of first new slot */
3524 int i;
3526 /* Sanity checking on calling parameters */
3527 assert( iStart>=0 );
3528 assert( nExtra>=1 );
3529 assert( pSrc!=0 );
3530 assert( iStart<=pSrc->nSrc );
3532 /* Allocate additional space if needed */
3533 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
3534 SrcList *pNew;
3535 int nAlloc = pSrc->nSrc+nExtra;
3536 int nGot;
3537 pNew = sqlite3DbRealloc(db, pSrc,
3538 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3539 if( pNew==0 ){
3540 assert( db->mallocFailed );
3541 return pSrc;
3543 pSrc = pNew;
3544 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3545 pSrc->nAlloc = nGot;
3548 /* Move existing slots that come after the newly inserted slots
3549 ** out of the way */
3550 for(i=pSrc->nSrc-1; i>=iStart; i--){
3551 pSrc->a[i+nExtra] = pSrc->a[i];
3553 pSrc->nSrc += nExtra;
3555 /* Zero the newly allocated slots */
3556 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3557 for(i=iStart; i<iStart+nExtra; i++){
3558 pSrc->a[i].iCursor = -1;
3561 /* Return a pointer to the enlarged SrcList */
3562 return pSrc;
3567 ** Append a new table name to the given SrcList. Create a new SrcList if
3568 ** need be. A new entry is created in the SrcList even if pTable is NULL.
3570 ** A SrcList is returned, or NULL if there is an OOM error. The returned
3571 ** SrcList might be the same as the SrcList that was input or it might be
3572 ** a new one. If an OOM error does occurs, then the prior value of pList
3573 ** that is input to this routine is automatically freed.
3575 ** If pDatabase is not null, it means that the table has an optional
3576 ** database name prefix. Like this: "database.table". The pDatabase
3577 ** points to the table name and the pTable points to the database name.
3578 ** The SrcList.a[].zName field is filled with the table name which might
3579 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3580 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3581 ** or with NULL if no database is specified.
3583 ** In other words, if call like this:
3585 ** sqlite3SrcListAppend(D,A,B,0);
3587 ** Then B is a table name and the database name is unspecified. If called
3588 ** like this:
3590 ** sqlite3SrcListAppend(D,A,B,C);
3592 ** Then C is the table name and B is the database name. If C is defined
3593 ** then so is B. In other words, we never have a case where:
3595 ** sqlite3SrcListAppend(D,A,0,C);
3597 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3598 ** before being added to the SrcList.
3600 SrcList *sqlite3SrcListAppend(
3601 sqlite3 *db, /* Connection to notify of malloc failures */
3602 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3603 Token *pTable, /* Table to append */
3604 Token *pDatabase /* Database of the table */
3606 struct SrcList_item *pItem;
3607 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
3608 if( pList==0 ){
3609 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
3610 if( pList==0 ) return 0;
3611 pList->nAlloc = 1;
3613 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3614 if( db->mallocFailed ){
3615 sqlite3SrcListDelete(db, pList);
3616 return 0;
3618 pItem = &pList->a[pList->nSrc-1];
3619 if( pDatabase && pDatabase->z==0 ){
3620 pDatabase = 0;
3622 if( pDatabase ){
3623 Token *pTemp = pDatabase;
3624 pDatabase = pTable;
3625 pTable = pTemp;
3627 pItem->zName = sqlite3NameFromToken(db, pTable);
3628 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
3629 return pList;
3633 ** Assign VdbeCursor index numbers to all tables in a SrcList
3635 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
3636 int i;
3637 struct SrcList_item *pItem;
3638 assert(pList || pParse->db->mallocFailed );
3639 if( pList ){
3640 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3641 if( pItem->iCursor>=0 ) break;
3642 pItem->iCursor = pParse->nTab++;
3643 if( pItem->pSelect ){
3644 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3651 ** Delete an entire SrcList including all its substructure.
3653 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
3654 int i;
3655 struct SrcList_item *pItem;
3656 if( pList==0 ) return;
3657 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
3658 sqlite3DbFree(db, pItem->zDatabase);
3659 sqlite3DbFree(db, pItem->zName);
3660 sqlite3DbFree(db, pItem->zAlias);
3661 sqlite3DbFree(db, pItem->zIndex);
3662 sqlite3DeleteTable(db, pItem->pTab);
3663 sqlite3SelectDelete(db, pItem->pSelect);
3664 sqlite3ExprDelete(db, pItem->pOn);
3665 sqlite3IdListDelete(db, pItem->pUsing);
3667 sqlite3DbFree(db, pList);
3671 ** This routine is called by the parser to add a new term to the
3672 ** end of a growing FROM clause. The "p" parameter is the part of
3673 ** the FROM clause that has already been constructed. "p" is NULL
3674 ** if this is the first term of the FROM clause. pTable and pDatabase
3675 ** are the name of the table and database named in the FROM clause term.
3676 ** pDatabase is NULL if the database name qualifier is missing - the
3677 ** usual case. If the term has an alias, then pAlias points to the
3678 ** alias token. If the term is a subquery, then pSubquery is the
3679 ** SELECT statement that the subquery encodes. The pTable and
3680 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3681 ** parameters are the content of the ON and USING clauses.
3683 ** Return a new SrcList which encodes is the FROM with the new
3684 ** term added.
3686 SrcList *sqlite3SrcListAppendFromTerm(
3687 Parse *pParse, /* Parsing context */
3688 SrcList *p, /* The left part of the FROM clause already seen */
3689 Token *pTable, /* Name of the table to add to the FROM clause */
3690 Token *pDatabase, /* Name of the database containing pTable */
3691 Token *pAlias, /* The right-hand side of the AS subexpression */
3692 Select *pSubquery, /* A subquery used in place of a table name */
3693 Expr *pOn, /* The ON clause of a join */
3694 IdList *pUsing /* The USING clause of a join */
3696 struct SrcList_item *pItem;
3697 sqlite3 *db = pParse->db;
3698 if( !p && (pOn || pUsing) ){
3699 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3700 (pOn ? "ON" : "USING")
3702 goto append_from_error;
3704 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
3705 if( p==0 || NEVER(p->nSrc==0) ){
3706 goto append_from_error;
3708 pItem = &p->a[p->nSrc-1];
3709 assert( pAlias!=0 );
3710 if( pAlias->n ){
3711 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
3713 pItem->pSelect = pSubquery;
3714 pItem->pOn = pOn;
3715 pItem->pUsing = pUsing;
3716 return p;
3718 append_from_error:
3719 assert( p==0 );
3720 sqlite3ExprDelete(db, pOn);
3721 sqlite3IdListDelete(db, pUsing);
3722 sqlite3SelectDelete(db, pSubquery);
3723 return 0;
3727 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3728 ** element of the source-list passed as the second argument.
3730 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3731 assert( pIndexedBy!=0 );
3732 if( p && ALWAYS(p->nSrc>0) ){
3733 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3734 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3735 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3736 /* A "NOT INDEXED" clause was supplied. See parse.y
3737 ** construct "indexed_opt" for details. */
3738 pItem->notIndexed = 1;
3739 }else{
3740 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3746 ** When building up a FROM clause in the parser, the join operator
3747 ** is initially attached to the left operand. But the code generator
3748 ** expects the join operator to be on the right operand. This routine
3749 ** Shifts all join operators from left to right for an entire FROM
3750 ** clause.
3752 ** Example: Suppose the join is like this:
3754 ** A natural cross join B
3756 ** The operator is "natural cross join". The A and B operands are stored
3757 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
3758 ** operator with A. This routine shifts that operator over to B.
3760 void sqlite3SrcListShiftJoinType(SrcList *p){
3761 if( p ){
3762 int i;
3763 assert( p->a || p->nSrc==0 );
3764 for(i=p->nSrc-1; i>0; i--){
3765 p->a[i].jointype = p->a[i-1].jointype;
3767 p->a[0].jointype = 0;
3772 ** Begin a transaction
3774 void sqlite3BeginTransaction(Parse *pParse, int type){
3775 sqlite3 *db;
3776 Vdbe *v;
3777 int i;
3779 assert( pParse!=0 );
3780 db = pParse->db;
3781 assert( db!=0 );
3782 /* if( db->aDb[0].pBt==0 ) return; */
3783 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3784 return;
3786 v = sqlite3GetVdbe(pParse);
3787 if( !v ) return;
3788 if( type!=TK_DEFERRED ){
3789 for(i=0; i<db->nDb; i++){
3790 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
3791 sqlite3VdbeUsesBtree(v, i);
3794 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
3798 ** Commit a transaction
3800 void sqlite3CommitTransaction(Parse *pParse){
3801 Vdbe *v;
3803 assert( pParse!=0 );
3804 assert( pParse->db!=0 );
3805 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3806 return;
3808 v = sqlite3GetVdbe(pParse);
3809 if( v ){
3810 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
3815 ** Rollback a transaction
3817 void sqlite3RollbackTransaction(Parse *pParse){
3818 Vdbe *v;
3820 assert( pParse!=0 );
3821 assert( pParse->db!=0 );
3822 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3823 return;
3825 v = sqlite3GetVdbe(pParse);
3826 if( v ){
3827 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
3832 ** This function is called by the parser when it parses a command to create,
3833 ** release or rollback an SQL savepoint.
3835 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
3836 char *zName = sqlite3NameFromToken(pParse->db, pName);
3837 if( zName ){
3838 Vdbe *v = sqlite3GetVdbe(pParse);
3839 #ifndef SQLITE_OMIT_AUTHORIZATION
3840 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3841 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3842 #endif
3843 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3844 sqlite3DbFree(pParse->db, zName);
3845 return;
3847 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
3852 ** Make sure the TEMP database is open and available for use. Return
3853 ** the number of errors. Leave any error messages in the pParse structure.
3855 int sqlite3OpenTempDatabase(Parse *pParse){
3856 sqlite3 *db = pParse->db;
3857 if( db->aDb[1].pBt==0 && !pParse->explain ){
3858 int rc;
3859 Btree *pBt;
3860 static const int flags =
3861 SQLITE_OPEN_READWRITE |
3862 SQLITE_OPEN_CREATE |
3863 SQLITE_OPEN_EXCLUSIVE |
3864 SQLITE_OPEN_DELETEONCLOSE |
3865 SQLITE_OPEN_TEMP_DB;
3867 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
3868 if( rc!=SQLITE_OK ){
3869 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3870 "file for storing temporary tables");
3871 pParse->rc = rc;
3872 return 1;
3874 db->aDb[1].pBt = pBt;
3875 assert( db->aDb[1].pSchema );
3876 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3877 db->mallocFailed = 1;
3878 return 1;
3881 return 0;
3885 ** Record the fact that the schema cookie will need to be verified
3886 ** for database iDb. The code to actually verify the schema cookie
3887 ** will occur at the end of the top-level VDBE and will be generated
3888 ** later, by sqlite3FinishCoding().
3890 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3891 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3892 sqlite3 *db = pToplevel->db;
3894 assert( iDb>=0 && iDb<db->nDb );
3895 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3896 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3897 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3898 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3899 DbMaskSet(pToplevel->cookieMask, iDb);
3900 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3901 if( !OMIT_TEMPDB && iDb==1 ){
3902 sqlite3OpenTempDatabase(pToplevel);
3908 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3909 ** attached database. Otherwise, invoke it for the database named zDb only.
3911 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3912 sqlite3 *db = pParse->db;
3913 int i;
3914 for(i=0; i<db->nDb; i++){
3915 Db *pDb = &db->aDb[i];
3916 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3917 sqlite3CodeVerifySchema(pParse, i);
3923 ** Generate VDBE code that prepares for doing an operation that
3924 ** might change the database.
3926 ** This routine starts a new transaction if we are not already within
3927 ** a transaction. If we are already within a transaction, then a checkpoint
3928 ** is set if the setStatement parameter is true. A checkpoint should
3929 ** be set for operations that might fail (due to a constraint) part of
3930 ** the way through and which will need to undo some writes without having to
3931 ** rollback the whole transaction. For operations where all constraints
3932 ** can be checked before any changes are made to the database, it is never
3933 ** necessary to undo a write and the checkpoint should not be set.
3935 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3936 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3937 sqlite3CodeVerifySchema(pParse, iDb);
3938 DbMaskSet(pToplevel->writeMask, iDb);
3939 pToplevel->isMultiWrite |= setStatement;
3943 ** Indicate that the statement currently under construction might write
3944 ** more than one entry (example: deleting one row then inserting another,
3945 ** inserting multiple rows in a table, or inserting a row and index entries.)
3946 ** If an abort occurs after some of these writes have completed, then it will
3947 ** be necessary to undo the completed writes.
3949 void sqlite3MultiWrite(Parse *pParse){
3950 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3951 pToplevel->isMultiWrite = 1;
3955 ** The code generator calls this routine if is discovers that it is
3956 ** possible to abort a statement prior to completion. In order to
3957 ** perform this abort without corrupting the database, we need to make
3958 ** sure that the statement is protected by a statement transaction.
3960 ** Technically, we only need to set the mayAbort flag if the
3961 ** isMultiWrite flag was previously set. There is a time dependency
3962 ** such that the abort must occur after the multiwrite. This makes
3963 ** some statements involving the REPLACE conflict resolution algorithm
3964 ** go a little faster. But taking advantage of this time dependency
3965 ** makes it more difficult to prove that the code is correct (in
3966 ** particular, it prevents us from writing an effective
3967 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
3968 ** to take the safe route and skip the optimization.
3970 void sqlite3MayAbort(Parse *pParse){
3971 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3972 pToplevel->mayAbort = 1;
3976 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3977 ** error. The onError parameter determines which (if any) of the statement
3978 ** and/or current transaction is rolled back.
3980 void sqlite3HaltConstraint(
3981 Parse *pParse, /* Parsing context */
3982 int errCode, /* extended error code */
3983 int onError, /* Constraint type */
3984 char *p4, /* Error message */
3985 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3986 u8 p5Errmsg /* P5_ErrMsg type */
3988 Vdbe *v = sqlite3GetVdbe(pParse);
3989 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
3990 if( onError==OE_Abort ){
3991 sqlite3MayAbort(pParse);
3993 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
3994 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3998 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4000 void sqlite3UniqueConstraint(
4001 Parse *pParse, /* Parsing context */
4002 int onError, /* Constraint type */
4003 Index *pIdx /* The index that triggers the constraint */
4005 char *zErr;
4006 int j;
4007 StrAccum errMsg;
4008 Table *pTab = pIdx->pTable;
4010 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
4011 errMsg.db = pParse->db;
4012 for(j=0; j<pIdx->nKeyCol; j++){
4013 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4014 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
4015 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
4016 sqlite3StrAccumAppend(&errMsg, ".", 1);
4017 sqlite3StrAccumAppendAll(&errMsg, zCol);
4019 zErr = sqlite3StrAccumFinish(&errMsg);
4020 sqlite3HaltConstraint(pParse,
4021 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4022 : SQLITE_CONSTRAINT_UNIQUE,
4023 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
4028 ** Code an OP_Halt due to non-unique rowid.
4030 void sqlite3RowidConstraint(
4031 Parse *pParse, /* Parsing context */
4032 int onError, /* Conflict resolution algorithm */
4033 Table *pTab /* The table with the non-unique rowid */
4035 char *zMsg;
4036 int rc;
4037 if( pTab->iPKey>=0 ){
4038 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4039 pTab->aCol[pTab->iPKey].zName);
4040 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4041 }else{
4042 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4043 rc = SQLITE_CONSTRAINT_ROWID;
4045 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4046 P5_ConstraintUnique);
4050 ** Check to see if pIndex uses the collating sequence pColl. Return
4051 ** true if it does and false if it does not.
4053 #ifndef SQLITE_OMIT_REINDEX
4054 static int collationMatch(const char *zColl, Index *pIndex){
4055 int i;
4056 assert( zColl!=0 );
4057 for(i=0; i<pIndex->nColumn; i++){
4058 const char *z = pIndex->azColl[i];
4059 assert( z!=0 || pIndex->aiColumn[i]<0 );
4060 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
4061 return 1;
4064 return 0;
4066 #endif
4069 ** Recompute all indices of pTab that use the collating sequence pColl.
4070 ** If pColl==0 then recompute all indices of pTab.
4072 #ifndef SQLITE_OMIT_REINDEX
4073 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
4074 Index *pIndex; /* An index associated with pTab */
4076 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
4077 if( zColl==0 || collationMatch(zColl, pIndex) ){
4078 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4079 sqlite3BeginWriteOperation(pParse, 0, iDb);
4080 sqlite3RefillIndex(pParse, pIndex, -1);
4084 #endif
4087 ** Recompute all indices of all tables in all databases where the
4088 ** indices use the collating sequence pColl. If pColl==0 then recompute
4089 ** all indices everywhere.
4091 #ifndef SQLITE_OMIT_REINDEX
4092 static void reindexDatabases(Parse *pParse, char const *zColl){
4093 Db *pDb; /* A single database */
4094 int iDb; /* The database index number */
4095 sqlite3 *db = pParse->db; /* The database connection */
4096 HashElem *k; /* For looping over tables in pDb */
4097 Table *pTab; /* A table in the database */
4099 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
4100 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
4101 assert( pDb!=0 );
4102 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
4103 pTab = (Table*)sqliteHashData(k);
4104 reindexTable(pParse, pTab, zColl);
4108 #endif
4111 ** Generate code for the REINDEX command.
4113 ** REINDEX -- 1
4114 ** REINDEX <collation> -- 2
4115 ** REINDEX ?<database>.?<tablename> -- 3
4116 ** REINDEX ?<database>.?<indexname> -- 4
4118 ** Form 1 causes all indices in all attached databases to be rebuilt.
4119 ** Form 2 rebuilds all indices in all databases that use the named
4120 ** collating function. Forms 3 and 4 rebuild the named index or all
4121 ** indices associated with the named table.
4123 #ifndef SQLITE_OMIT_REINDEX
4124 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4125 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4126 char *z; /* Name of a table or index */
4127 const char *zDb; /* Name of the database */
4128 Table *pTab; /* A table in the database */
4129 Index *pIndex; /* An index associated with pTab */
4130 int iDb; /* The database index number */
4131 sqlite3 *db = pParse->db; /* The database connection */
4132 Token *pObjName; /* Name of the table or index to be reindexed */
4134 /* Read the database schema. If an error occurs, leave an error message
4135 ** and code in pParse and return NULL. */
4136 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4137 return;
4140 if( pName1==0 ){
4141 reindexDatabases(pParse, 0);
4142 return;
4143 }else if( NEVER(pName2==0) || pName2->z==0 ){
4144 char *zColl;
4145 assert( pName1->z );
4146 zColl = sqlite3NameFromToken(pParse->db, pName1);
4147 if( !zColl ) return;
4148 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
4149 if( pColl ){
4150 reindexDatabases(pParse, zColl);
4151 sqlite3DbFree(db, zColl);
4152 return;
4154 sqlite3DbFree(db, zColl);
4156 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4157 if( iDb<0 ) return;
4158 z = sqlite3NameFromToken(db, pObjName);
4159 if( z==0 ) return;
4160 zDb = db->aDb[iDb].zName;
4161 pTab = sqlite3FindTable(db, z, zDb);
4162 if( pTab ){
4163 reindexTable(pParse, pTab, 0);
4164 sqlite3DbFree(db, z);
4165 return;
4167 pIndex = sqlite3FindIndex(db, z, zDb);
4168 sqlite3DbFree(db, z);
4169 if( pIndex ){
4170 sqlite3BeginWriteOperation(pParse, 0, iDb);
4171 sqlite3RefillIndex(pParse, pIndex, -1);
4172 return;
4174 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4176 #endif
4179 ** Return a KeyInfo structure that is appropriate for the given Index.
4181 ** The KeyInfo structure for an index is cached in the Index object.
4182 ** So there might be multiple references to the returned pointer. The
4183 ** caller should not try to modify the KeyInfo object.
4185 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4186 ** when it has finished using it.
4188 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
4189 if( pParse->nErr ) return 0;
4190 #ifndef SQLITE_OMIT_SHARED_CACHE
4191 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4192 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4193 pIdx->pKeyInfo = 0;
4195 #endif
4196 if( pIdx->pKeyInfo==0 ){
4197 int i;
4198 int nCol = pIdx->nColumn;
4199 int nKey = pIdx->nKeyCol;
4200 KeyInfo *pKey;
4201 if( pIdx->uniqNotNull ){
4202 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4203 }else{
4204 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4206 if( pKey ){
4207 assert( sqlite3KeyInfoIsWriteable(pKey) );
4208 for(i=0; i<nCol; i++){
4209 char *zColl = pIdx->azColl[i];
4210 assert( zColl!=0 );
4211 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4212 sqlite3LocateCollSeq(pParse, zColl);
4213 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4215 if( pParse->nErr ){
4216 sqlite3KeyInfoUnref(pKey);
4217 }else{
4218 pIdx->pKeyInfo = pKey;
4222 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
4225 #ifndef SQLITE_OMIT_CTE
4227 ** This routine is invoked once per CTE by the parser while parsing a
4228 ** WITH clause.
4230 With *sqlite3WithAdd(
4231 Parse *pParse, /* Parsing context */
4232 With *pWith, /* Existing WITH clause, or NULL */
4233 Token *pName, /* Name of the common-table */
4234 ExprList *pArglist, /* Optional column name list for the table */
4235 Select *pQuery /* Query used to initialize the table */
4237 sqlite3 *db = pParse->db;
4238 With *pNew;
4239 char *zName;
4241 /* Check that the CTE name is unique within this WITH clause. If
4242 ** not, store an error in the Parse structure. */
4243 zName = sqlite3NameFromToken(pParse->db, pName);
4244 if( zName && pWith ){
4245 int i;
4246 for(i=0; i<pWith->nCte; i++){
4247 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
4248 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
4253 if( pWith ){
4254 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4255 pNew = sqlite3DbRealloc(db, pWith, nByte);
4256 }else{
4257 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4259 assert( zName!=0 || pNew==0 );
4260 assert( db->mallocFailed==0 || pNew==0 );
4262 if( pNew==0 ){
4263 sqlite3ExprListDelete(db, pArglist);
4264 sqlite3SelectDelete(db, pQuery);
4265 sqlite3DbFree(db, zName);
4266 pNew = pWith;
4267 }else{
4268 pNew->a[pNew->nCte].pSelect = pQuery;
4269 pNew->a[pNew->nCte].pCols = pArglist;
4270 pNew->a[pNew->nCte].zName = zName;
4271 pNew->a[pNew->nCte].zErr = 0;
4272 pNew->nCte++;
4275 return pNew;
4279 ** Free the contents of the With object passed as the second argument.
4281 void sqlite3WithDelete(sqlite3 *db, With *pWith){
4282 if( pWith ){
4283 int i;
4284 for(i=0; i<pWith->nCte; i++){
4285 struct Cte *pCte = &pWith->a[i];
4286 sqlite3ExprListDelete(db, pCte->pCols);
4287 sqlite3SelectDelete(db, pCte->pSelect);
4288 sqlite3DbFree(db, pCte->zName);
4290 sqlite3DbFree(db, pWith);
4293 #endif /* !defined(SQLITE_OMIT_CTE) */