fix output of integrity check on big endian platforms
[sqlcipher.git] / src / build.c
blob53314593bd5f23e0f784ef50cdd53d05e1955db9
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"
27 #ifndef SQLITE_OMIT_SHARED_CACHE
29 ** The TableLock structure is only used by the sqlite3TableLock() and
30 ** codeTableLocks() functions.
32 struct TableLock {
33 int iDb; /* The database containing the table to be locked */
34 int iTab; /* The root page of the table to be locked */
35 u8 isWriteLock; /* True for write lock. False for a read lock */
36 const char *zLockName; /* Name of the table */
40 ** Record the fact that we want to lock a table at run-time.
42 ** The table to be locked has root page iTab and is found in database iDb.
43 ** A read or a write lock can be taken depending on isWritelock.
45 ** This routine just records the fact that the lock is desired. The
46 ** code to make the lock occur is generated by a later call to
47 ** codeTableLocks() which occurs during sqlite3FinishCoding().
49 void sqlite3TableLock(
50 Parse *pParse, /* Parsing context */
51 int iDb, /* Index of the database containing the table to lock */
52 int iTab, /* Root page number of the table to be locked */
53 u8 isWriteLock, /* True for a write lock */
54 const char *zName /* Name of the table to be locked */
56 Parse *pToplevel = sqlite3ParseToplevel(pParse);
57 int i;
58 int nBytes;
59 TableLock *p;
60 assert( iDb>=0 );
62 if( iDb==1 ) return;
63 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
64 for(i=0; i<pToplevel->nTableLock; i++){
65 p = &pToplevel->aTableLock[i];
66 if( p->iDb==iDb && p->iTab==iTab ){
67 p->isWriteLock = (p->isWriteLock || isWriteLock);
68 return;
72 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
73 pToplevel->aTableLock =
74 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
75 if( pToplevel->aTableLock ){
76 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
77 p->iDb = iDb;
78 p->iTab = iTab;
79 p->isWriteLock = isWriteLock;
80 p->zLockName = zName;
81 }else{
82 pToplevel->nTableLock = 0;
83 sqlite3OomFault(pToplevel->db);
88 ** Code an OP_TableLock instruction for each table locked by the
89 ** statement (configured by calls to sqlite3TableLock()).
91 static void codeTableLocks(Parse *pParse){
92 int i;
93 Vdbe *pVdbe;
95 pVdbe = sqlite3GetVdbe(pParse);
96 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
98 for(i=0; i<pParse->nTableLock; i++){
99 TableLock *p = &pParse->aTableLock[i];
100 int p1 = p->iDb;
101 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
102 p->zLockName, P4_STATIC);
105 #else
106 #define codeTableLocks(x)
107 #endif
110 ** Return TRUE if the given yDbMask object is empty - if it contains no
111 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
112 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
114 #if SQLITE_MAX_ATTACHED>30
115 int sqlite3DbMaskAllZero(yDbMask m){
116 int i;
117 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
118 return 1;
120 #endif
123 ** This routine is called after a single SQL statement has been
124 ** parsed and a VDBE program to execute that statement has been
125 ** prepared. This routine puts the finishing touches on the
126 ** VDBE program and resets the pParse structure for the next
127 ** parse.
129 ** Note that if an error occurred, it might be the case that
130 ** no VDBE code was generated.
132 void sqlite3FinishCoding(Parse *pParse){
133 sqlite3 *db;
134 Vdbe *v;
136 assert( pParse->pToplevel==0 );
137 db = pParse->db;
138 if( pParse->nested ) return;
139 if( db->mallocFailed || pParse->nErr ){
140 if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
141 return;
144 /* Begin by generating some termination code at the end of the
145 ** vdbe program
147 v = sqlite3GetVdbe(pParse);
148 assert( !pParse->isMultiWrite
149 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
150 if( v ){
151 sqlite3VdbeAddOp0(v, OP_Halt);
153 #if SQLITE_USER_AUTHENTICATION
154 if( pParse->nTableLock>0 && db->init.busy==0 ){
155 sqlite3UserAuthInit(db);
156 if( db->auth.authLevel<UAUTH_User ){
157 sqlite3ErrorMsg(pParse, "user not authenticated");
158 pParse->rc = SQLITE_AUTH_USER;
159 return;
162 #endif
164 /* The cookie mask contains one bit for each database file open.
165 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
166 ** set for each database that is used. Generate code to start a
167 ** transaction on each used database and to verify the schema cookie
168 ** on each used database.
170 if( db->mallocFailed==0
171 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
173 int iDb, i;
174 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
175 sqlite3VdbeJumpHere(v, 0);
176 for(iDb=0; iDb<db->nDb; iDb++){
177 Schema *pSchema;
178 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
179 sqlite3VdbeUsesBtree(v, iDb);
180 pSchema = db->aDb[iDb].pSchema;
181 sqlite3VdbeAddOp4Int(v,
182 OP_Transaction, /* Opcode */
183 iDb, /* P1 */
184 DbMaskTest(pParse->writeMask,iDb), /* P2 */
185 pSchema->schema_cookie, /* P3 */
186 pSchema->iGeneration /* P4 */
188 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
189 VdbeComment((v,
190 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
192 #ifndef SQLITE_OMIT_VIRTUALTABLE
193 for(i=0; i<pParse->nVtabLock; i++){
194 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
195 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
197 pParse->nVtabLock = 0;
198 #endif
200 /* Once all the cookies have been verified and transactions opened,
201 ** obtain the required table-locks. This is a no-op unless the
202 ** shared-cache feature is enabled.
204 codeTableLocks(pParse);
206 /* Initialize any AUTOINCREMENT data structures required.
208 sqlite3AutoincrementBegin(pParse);
210 /* Code constant expressions that where factored out of inner loops */
211 if( pParse->pConstExpr ){
212 ExprList *pEL = pParse->pConstExpr;
213 pParse->okConstFactor = 0;
214 for(i=0; i<pEL->nExpr; i++){
215 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
219 /* Finally, jump back to the beginning of the executable code. */
220 sqlite3VdbeGoto(v, 1);
225 /* Get the VDBE program ready for execution
227 if( v && pParse->nErr==0 && !db->mallocFailed ){
228 /* A minimum of one cursor is required if autoincrement is used
229 * See ticket [a696379c1f08866] */
230 assert( pParse->pAinc==0 || pParse->nTab>0 );
231 sqlite3VdbeMakeReady(v, pParse);
232 pParse->rc = SQLITE_DONE;
233 }else{
234 pParse->rc = SQLITE_ERROR;
239 ** Run the parser and code generator recursively in order to generate
240 ** code for the SQL statement given onto the end of the pParse context
241 ** currently under construction. When the parser is run recursively
242 ** this way, the final OP_Halt is not appended and other initialization
243 ** and finalization steps are omitted because those are handling by the
244 ** outermost parser.
246 ** Not everything is nestable. This facility is designed to permit
247 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
248 ** care if you decide to try to use this routine for some other purposes.
250 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
251 va_list ap;
252 char *zSql;
253 char *zErrMsg = 0;
254 sqlite3 *db = pParse->db;
255 char saveBuf[PARSE_TAIL_SZ];
257 if( pParse->nErr ) return;
258 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
259 va_start(ap, zFormat);
260 zSql = sqlite3VMPrintf(db, zFormat, ap);
261 va_end(ap);
262 if( zSql==0 ){
263 /* This can result either from an OOM or because the formatted string
264 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
265 ** an error */
266 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
267 pParse->nErr++;
268 return;
270 pParse->nested++;
271 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
272 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
273 sqlite3RunParser(pParse, zSql, &zErrMsg);
274 sqlite3DbFree(db, zErrMsg);
275 sqlite3DbFree(db, zSql);
276 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
277 pParse->nested--;
280 #if SQLITE_USER_AUTHENTICATION
282 ** Return TRUE if zTable is the name of the system table that stores the
283 ** list of users and their access credentials.
285 int sqlite3UserAuthTable(const char *zTable){
286 return sqlite3_stricmp(zTable, "sqlite_user")==0;
288 #endif
291 ** Locate the in-memory structure that describes a particular database
292 ** table given the name of that table and (optionally) the name of the
293 ** database containing the table. Return NULL if not found.
295 ** If zDatabase is 0, all databases are searched for the table and the
296 ** first matching table is returned. (No checking for duplicate table
297 ** names is done.) The search order is TEMP first, then MAIN, then any
298 ** auxiliary databases added using the ATTACH command.
300 ** See also sqlite3LocateTable().
302 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
303 Table *p = 0;
304 int i;
306 /* All mutexes are required for schema access. Make sure we hold them. */
307 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
308 #if SQLITE_USER_AUTHENTICATION
309 /* Only the admin user is allowed to know that the sqlite_user table
310 ** exists */
311 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
312 return 0;
314 #endif
315 while(1){
316 for(i=OMIT_TEMPDB; i<db->nDb; i++){
317 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
318 if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
319 assert( sqlite3SchemaMutexHeld(db, j, 0) );
320 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
321 if( p ) return p;
324 /* Not found. If the name we were looking for was temp.sqlite_master
325 ** then change the name to sqlite_temp_master and try again. */
326 if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
327 if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
328 zName = TEMP_MASTER_NAME;
330 return 0;
334 ** Locate the in-memory structure that describes a particular database
335 ** table given the name of that table and (optionally) the name of the
336 ** database containing the table. Return NULL if not found. Also leave an
337 ** error message in pParse->zErrMsg.
339 ** The difference between this routine and sqlite3FindTable() is that this
340 ** routine leaves an error message in pParse->zErrMsg where
341 ** sqlite3FindTable() does not.
343 Table *sqlite3LocateTable(
344 Parse *pParse, /* context in which to report errors */
345 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
346 const char *zName, /* Name of the table we are looking for */
347 const char *zDbase /* Name of the database. Might be NULL */
349 Table *p;
350 sqlite3 *db = pParse->db;
352 /* Read the database schema. If an error occurs, leave an error message
353 ** and code in pParse and return NULL. */
354 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
355 && SQLITE_OK!=sqlite3ReadSchema(pParse)
357 return 0;
360 p = sqlite3FindTable(db, zName, zDbase);
361 if( p==0 ){
362 #ifndef SQLITE_OMIT_VIRTUALTABLE
363 /* If zName is the not the name of a table in the schema created using
364 ** CREATE, then check to see if it is the name of an virtual table that
365 ** can be an eponymous virtual table. */
366 if( pParse->disableVtab==0 ){
367 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
368 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
369 pMod = sqlite3PragmaVtabRegister(db, zName);
371 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
372 return pMod->pEpoTab;
375 #endif
376 if( flags & LOCATE_NOERR ) return 0;
377 pParse->checkSchema = 1;
378 }else if( IsVirtual(p) && pParse->disableVtab ){
379 p = 0;
382 if( p==0 ){
383 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
384 if( zDbase ){
385 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
386 }else{
387 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
391 return p;
395 ** Locate the table identified by *p.
397 ** This is a wrapper around sqlite3LocateTable(). The difference between
398 ** sqlite3LocateTable() and this function is that this function restricts
399 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
400 ** non-NULL if it is part of a view or trigger program definition. See
401 ** sqlite3FixSrcList() for details.
403 Table *sqlite3LocateTableItem(
404 Parse *pParse,
405 u32 flags,
406 struct SrcList_item *p
408 const char *zDb;
409 assert( p->pSchema==0 || p->zDatabase==0 );
410 if( p->pSchema ){
411 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
412 zDb = pParse->db->aDb[iDb].zDbSName;
413 }else{
414 zDb = p->zDatabase;
416 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
420 ** Locate the in-memory structure that describes
421 ** a particular index given the name of that index
422 ** and the name of the database that contains the index.
423 ** Return NULL if not found.
425 ** If zDatabase is 0, all databases are searched for the
426 ** table and the first matching index is returned. (No checking
427 ** for duplicate index names is done.) The search order is
428 ** TEMP first, then MAIN, then any auxiliary databases added
429 ** using the ATTACH command.
431 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
432 Index *p = 0;
433 int i;
434 /* All mutexes are required for schema access. Make sure we hold them. */
435 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
436 for(i=OMIT_TEMPDB; i<db->nDb; i++){
437 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
438 Schema *pSchema = db->aDb[j].pSchema;
439 assert( pSchema );
440 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
441 assert( sqlite3SchemaMutexHeld(db, j, 0) );
442 p = sqlite3HashFind(&pSchema->idxHash, zName);
443 if( p ) break;
445 return p;
449 ** Reclaim the memory used by an index
451 void sqlite3FreeIndex(sqlite3 *db, Index *p){
452 #ifndef SQLITE_OMIT_ANALYZE
453 sqlite3DeleteIndexSamples(db, p);
454 #endif
455 sqlite3ExprDelete(db, p->pPartIdxWhere);
456 sqlite3ExprListDelete(db, p->aColExpr);
457 sqlite3DbFree(db, p->zColAff);
458 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
459 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
460 sqlite3_free(p->aiRowEst);
461 #endif
462 sqlite3DbFree(db, p);
466 ** For the index called zIdxName which is found in the database iDb,
467 ** unlike that index from its Table then remove the index from
468 ** the index hash table and free all memory structures associated
469 ** with the index.
471 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
472 Index *pIndex;
473 Hash *pHash;
475 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
476 pHash = &db->aDb[iDb].pSchema->idxHash;
477 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
478 if( ALWAYS(pIndex) ){
479 if( pIndex->pTable->pIndex==pIndex ){
480 pIndex->pTable->pIndex = pIndex->pNext;
481 }else{
482 Index *p;
483 /* Justification of ALWAYS(); The index must be on the list of
484 ** indices. */
485 p = pIndex->pTable->pIndex;
486 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
487 if( ALWAYS(p && p->pNext==pIndex) ){
488 p->pNext = pIndex->pNext;
491 sqlite3FreeIndex(db, pIndex);
493 db->mDbFlags |= DBFLAG_SchemaChange;
497 ** Look through the list of open database files in db->aDb[] and if
498 ** any have been closed, remove them from the list. Reallocate the
499 ** db->aDb[] structure to a smaller size, if possible.
501 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
502 ** are never candidates for being collapsed.
504 void sqlite3CollapseDatabaseArray(sqlite3 *db){
505 int i, j;
506 for(i=j=2; i<db->nDb; i++){
507 struct Db *pDb = &db->aDb[i];
508 if( pDb->pBt==0 ){
509 sqlite3DbFree(db, pDb->zDbSName);
510 pDb->zDbSName = 0;
511 continue;
513 if( j<i ){
514 db->aDb[j] = db->aDb[i];
516 j++;
518 db->nDb = j;
519 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
520 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
521 sqlite3DbFree(db, db->aDb);
522 db->aDb = db->aDbStatic;
527 ** Reset the schema for the database at index iDb. Also reset the
528 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
529 ** Deferred resets may be run by calling with iDb<0.
531 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
532 int i;
533 assert( iDb<db->nDb );
535 if( iDb>=0 ){
536 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
537 DbSetProperty(db, iDb, DB_ResetWanted);
538 DbSetProperty(db, 1, DB_ResetWanted);
539 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
542 if( db->nSchemaLock==0 ){
543 for(i=0; i<db->nDb; i++){
544 if( DbHasProperty(db, i, DB_ResetWanted) ){
545 sqlite3SchemaClear(db->aDb[i].pSchema);
552 ** Erase all schema information from all attached databases (including
553 ** "main" and "temp") for a single database connection.
555 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
556 int i;
557 sqlite3BtreeEnterAll(db);
558 for(i=0; i<db->nDb; i++){
559 Db *pDb = &db->aDb[i];
560 if( pDb->pSchema ){
561 if( db->nSchemaLock==0 ){
562 sqlite3SchemaClear(pDb->pSchema);
563 }else{
564 DbSetProperty(db, i, DB_ResetWanted);
568 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
569 sqlite3VtabUnlockList(db);
570 sqlite3BtreeLeaveAll(db);
571 if( db->nSchemaLock==0 ){
572 sqlite3CollapseDatabaseArray(db);
577 ** This routine is called when a commit occurs.
579 void sqlite3CommitInternalChanges(sqlite3 *db){
580 db->mDbFlags &= ~DBFLAG_SchemaChange;
584 ** Delete memory allocated for the column names of a table or view (the
585 ** Table.aCol[] array).
587 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
588 int i;
589 Column *pCol;
590 assert( pTable!=0 );
591 if( (pCol = pTable->aCol)!=0 ){
592 for(i=0; i<pTable->nCol; i++, pCol++){
593 sqlite3DbFree(db, pCol->zName);
594 sqlite3ExprDelete(db, pCol->pDflt);
595 sqlite3DbFree(db, pCol->zColl);
597 sqlite3DbFree(db, pTable->aCol);
602 ** Remove the memory data structures associated with the given
603 ** Table. No changes are made to disk by this routine.
605 ** This routine just deletes the data structure. It does not unlink
606 ** the table data structure from the hash table. But it does destroy
607 ** memory structures of the indices and foreign keys associated with
608 ** the table.
610 ** The db parameter is optional. It is needed if the Table object
611 ** contains lookaside memory. (Table objects in the schema do not use
612 ** lookaside memory, but some ephemeral Table objects do.) Or the
613 ** db parameter can be used with db->pnBytesFreed to measure the memory
614 ** used by the Table object.
616 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
617 Index *pIndex, *pNext;
619 #ifdef SQLITE_DEBUG
620 /* Record the number of outstanding lookaside allocations in schema Tables
621 ** prior to doing any free() operations. Since schema Tables do not use
622 ** lookaside, this number should not change.
624 ** If malloc has already failed, it may be that it failed while allocating
625 ** a Table object that was going to be marked ephemeral. So do not check
626 ** that no lookaside memory is used in this case either. */
627 int nLookaside = 0;
628 if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
629 nLookaside = sqlite3LookasideUsed(db, 0);
631 #endif
633 /* Delete all indices associated with this table. */
634 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
635 pNext = pIndex->pNext;
636 assert( pIndex->pSchema==pTable->pSchema
637 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
638 if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
639 char *zName = pIndex->zName;
640 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
641 &pIndex->pSchema->idxHash, zName, 0
643 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
644 assert( pOld==pIndex || pOld==0 );
646 sqlite3FreeIndex(db, pIndex);
649 /* Delete any foreign keys attached to this table. */
650 sqlite3FkDelete(db, pTable);
652 /* Delete the Table structure itself.
654 sqlite3DeleteColumnNames(db, pTable);
655 sqlite3DbFree(db, pTable->zName);
656 sqlite3DbFree(db, pTable->zColAff);
657 sqlite3SelectDelete(db, pTable->pSelect);
658 sqlite3ExprListDelete(db, pTable->pCheck);
659 #ifndef SQLITE_OMIT_VIRTUALTABLE
660 sqlite3VtabClear(db, pTable);
661 #endif
662 sqlite3DbFree(db, pTable);
664 /* Verify that no lookaside memory was used by schema tables */
665 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
667 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
668 /* Do not delete the table until the reference count reaches zero. */
669 if( !pTable ) return;
670 if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
671 deleteTable(db, pTable);
676 ** Unlink the given table from the hash tables and the delete the
677 ** table structure with all its indices and foreign keys.
679 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
680 Table *p;
681 Db *pDb;
683 assert( db!=0 );
684 assert( iDb>=0 && iDb<db->nDb );
685 assert( zTabName );
686 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
687 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
688 pDb = &db->aDb[iDb];
689 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
690 sqlite3DeleteTable(db, p);
691 db->mDbFlags |= DBFLAG_SchemaChange;
695 ** Given a token, return a string that consists of the text of that
696 ** token. Space to hold the returned string
697 ** is obtained from sqliteMalloc() and must be freed by the calling
698 ** function.
700 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
701 ** surround the body of the token are removed.
703 ** Tokens are often just pointers into the original SQL text and so
704 ** are not \000 terminated and are not persistent. The returned string
705 ** is \000 terminated and is persistent.
707 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
708 char *zName;
709 if( pName ){
710 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
711 sqlite3Dequote(zName);
712 }else{
713 zName = 0;
715 return zName;
719 ** Open the sqlite_master table stored in database number iDb for
720 ** writing. The table is opened using cursor 0.
722 void sqlite3OpenMasterTable(Parse *p, int iDb){
723 Vdbe *v = sqlite3GetVdbe(p);
724 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
725 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
726 if( p->nTab==0 ){
727 p->nTab = 1;
732 ** Parameter zName points to a nul-terminated buffer containing the name
733 ** of a database ("main", "temp" or the name of an attached db). This
734 ** function returns the index of the named database in db->aDb[], or
735 ** -1 if the named db cannot be found.
737 int sqlite3FindDbName(sqlite3 *db, const char *zName){
738 int i = -1; /* Database number */
739 if( zName ){
740 Db *pDb;
741 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
742 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
743 /* "main" is always an acceptable alias for the primary database
744 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
745 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
748 return i;
752 ** The token *pName contains the name of a database (either "main" or
753 ** "temp" or the name of an attached db). This routine returns the
754 ** index of the named database in db->aDb[], or -1 if the named db
755 ** does not exist.
757 int sqlite3FindDb(sqlite3 *db, Token *pName){
758 int i; /* Database number */
759 char *zName; /* Name we are searching for */
760 zName = sqlite3NameFromToken(db, pName);
761 i = sqlite3FindDbName(db, zName);
762 sqlite3DbFree(db, zName);
763 return i;
766 /* The table or view or trigger name is passed to this routine via tokens
767 ** pName1 and pName2. If the table name was fully qualified, for example:
769 ** CREATE TABLE xxx.yyy (...);
771 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
772 ** the table name is not fully qualified, i.e.:
774 ** CREATE TABLE yyy(...);
776 ** Then pName1 is set to "yyy" and pName2 is "".
778 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
779 ** pName2) that stores the unqualified table name. The index of the
780 ** database "xxx" is returned.
782 int sqlite3TwoPartName(
783 Parse *pParse, /* Parsing and code generating context */
784 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
785 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
786 Token **pUnqual /* Write the unqualified object name here */
788 int iDb; /* Database holding the object */
789 sqlite3 *db = pParse->db;
791 assert( pName2!=0 );
792 if( pName2->n>0 ){
793 if( db->init.busy ) {
794 sqlite3ErrorMsg(pParse, "corrupt database");
795 return -1;
797 *pUnqual = pName2;
798 iDb = sqlite3FindDb(db, pName1);
799 if( iDb<0 ){
800 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
801 return -1;
803 }else{
804 assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
805 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
806 iDb = db->init.iDb;
807 *pUnqual = pName1;
809 return iDb;
813 ** True if PRAGMA writable_schema is ON
815 int sqlite3WritableSchema(sqlite3 *db){
816 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
817 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
818 SQLITE_WriteSchema );
819 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
820 SQLITE_Defensive );
821 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
822 (SQLITE_WriteSchema|SQLITE_Defensive) );
823 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
827 ** This routine is used to check if the UTF-8 string zName is a legal
828 ** unqualified name for a new schema object (table, index, view or
829 ** trigger). All names are legal except those that begin with the string
830 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
831 ** is reserved for internal use.
833 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
834 if( !pParse->db->init.busy && pParse->nested==0
835 && sqlite3WritableSchema(pParse->db)==0
836 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
837 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
838 return SQLITE_ERROR;
840 return SQLITE_OK;
844 ** Return the PRIMARY KEY index of a table
846 Index *sqlite3PrimaryKeyIndex(Table *pTab){
847 Index *p;
848 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
849 return p;
853 ** Return the column of index pIdx that corresponds to table
854 ** column iCol. Return -1 if not found.
856 i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
857 int i;
858 for(i=0; i<pIdx->nColumn; i++){
859 if( iCol==pIdx->aiColumn[i] ) return i;
861 return -1;
865 ** Begin constructing a new table representation in memory. This is
866 ** the first of several action routines that get called in response
867 ** to a CREATE TABLE statement. In particular, this routine is called
868 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
869 ** flag is true if the table should be stored in the auxiliary database
870 ** file instead of in the main database file. This is normally the case
871 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
872 ** CREATE and TABLE.
874 ** The new table record is initialized and put in pParse->pNewTable.
875 ** As more of the CREATE TABLE statement is parsed, additional action
876 ** routines will be called to add more information to this record.
877 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
878 ** is called to complete the construction of the new table record.
880 void sqlite3StartTable(
881 Parse *pParse, /* Parser context */
882 Token *pName1, /* First part of the name of the table or view */
883 Token *pName2, /* Second part of the name of the table or view */
884 int isTemp, /* True if this is a TEMP table */
885 int isView, /* True if this is a VIEW */
886 int isVirtual, /* True if this is a VIRTUAL table */
887 int noErr /* Do nothing if table already exists */
889 Table *pTable;
890 char *zName = 0; /* The name of the new table */
891 sqlite3 *db = pParse->db;
892 Vdbe *v;
893 int iDb; /* Database number to create the table in */
894 Token *pName; /* Unqualified name of the table to create */
896 if( db->init.busy && db->init.newTnum==1 ){
897 /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
898 iDb = db->init.iDb;
899 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
900 pName = pName1;
901 }else{
902 /* The common case */
903 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
904 if( iDb<0 ) return;
905 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
906 /* If creating a temp table, the name may not be qualified. Unless
907 ** the database name is "temp" anyway. */
908 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
909 return;
911 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
912 zName = sqlite3NameFromToken(db, pName);
913 if( IN_RENAME_OBJECT ){
914 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
917 pParse->sNameToken = *pName;
918 if( zName==0 ) return;
919 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
920 goto begin_table_error;
922 if( db->init.iDb==1 ) isTemp = 1;
923 #ifndef SQLITE_OMIT_AUTHORIZATION
924 assert( isTemp==0 || isTemp==1 );
925 assert( isView==0 || isView==1 );
927 static const u8 aCode[] = {
928 SQLITE_CREATE_TABLE,
929 SQLITE_CREATE_TEMP_TABLE,
930 SQLITE_CREATE_VIEW,
931 SQLITE_CREATE_TEMP_VIEW
933 char *zDb = db->aDb[iDb].zDbSName;
934 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
935 goto begin_table_error;
937 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
938 zName, 0, zDb) ){
939 goto begin_table_error;
942 #endif
944 /* Make sure the new table name does not collide with an existing
945 ** index or table name in the same database. Issue an error message if
946 ** it does. The exception is if the statement being parsed was passed
947 ** to an sqlite3_declare_vtab() call. In that case only the column names
948 ** and types will be used, so there is no need to test for namespace
949 ** collisions.
951 if( !IN_SPECIAL_PARSE ){
952 char *zDb = db->aDb[iDb].zDbSName;
953 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
954 goto begin_table_error;
956 pTable = sqlite3FindTable(db, zName, zDb);
957 if( pTable ){
958 if( !noErr ){
959 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
960 }else{
961 assert( !db->init.busy || CORRUPT_DB );
962 sqlite3CodeVerifySchema(pParse, iDb);
964 goto begin_table_error;
966 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
967 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
968 goto begin_table_error;
972 pTable = sqlite3DbMallocZero(db, sizeof(Table));
973 if( pTable==0 ){
974 assert( db->mallocFailed );
975 pParse->rc = SQLITE_NOMEM_BKPT;
976 pParse->nErr++;
977 goto begin_table_error;
979 pTable->zName = zName;
980 pTable->iPKey = -1;
981 pTable->pSchema = db->aDb[iDb].pSchema;
982 pTable->nTabRef = 1;
983 #ifdef SQLITE_DEFAULT_ROWEST
984 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
985 #else
986 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
987 #endif
988 assert( pParse->pNewTable==0 );
989 pParse->pNewTable = pTable;
991 /* If this is the magic sqlite_sequence table used by autoincrement,
992 ** then record a pointer to this table in the main database structure
993 ** so that INSERT can find the table easily.
995 #ifndef SQLITE_OMIT_AUTOINCREMENT
996 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
997 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
998 pTable->pSchema->pSeqTab = pTable;
1000 #endif
1002 /* Begin generating the code that will insert the table record into
1003 ** the SQLITE_MASTER table. Note in particular that we must go ahead
1004 ** and allocate the record number for the table entry now. Before any
1005 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
1006 ** indices to be created and the table record must come before the
1007 ** indices. Hence, the record number for the table must be allocated
1008 ** now.
1010 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1011 int addr1;
1012 int fileFormat;
1013 int reg1, reg2, reg3;
1014 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
1015 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
1016 sqlite3BeginWriteOperation(pParse, 1, iDb);
1018 #ifndef SQLITE_OMIT_VIRTUALTABLE
1019 if( isVirtual ){
1020 sqlite3VdbeAddOp0(v, OP_VBegin);
1022 #endif
1024 /* If the file format and encoding in the database have not been set,
1025 ** set them now.
1027 reg1 = pParse->regRowid = ++pParse->nMem;
1028 reg2 = pParse->regRoot = ++pParse->nMem;
1029 reg3 = ++pParse->nMem;
1030 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
1031 sqlite3VdbeUsesBtree(v, iDb);
1032 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
1033 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1034 1 : SQLITE_MAX_FILE_FORMAT;
1035 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
1036 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
1037 sqlite3VdbeJumpHere(v, addr1);
1039 /* This just creates a place-holder record in the sqlite_master table.
1040 ** The record created does not contain anything yet. It will be replaced
1041 ** by the real entry in code generated at sqlite3EndTable().
1043 ** The rowid for the new entry is left in register pParse->regRowid.
1044 ** The root page number of the new table is left in reg pParse->regRoot.
1045 ** The rowid and root page number values are needed by the code that
1046 ** sqlite3EndTable will generate.
1048 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1049 if( isView || isVirtual ){
1050 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1051 }else
1052 #endif
1054 pParse->addrCrTab =
1055 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
1057 sqlite3OpenMasterTable(pParse, iDb);
1058 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1059 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
1060 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1061 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1062 sqlite3VdbeAddOp0(v, OP_Close);
1065 /* Normal (non-error) return. */
1066 return;
1068 /* If an error occurs, we jump here */
1069 begin_table_error:
1070 sqlite3DbFree(db, zName);
1071 return;
1074 /* Set properties of a table column based on the (magical)
1075 ** name of the column.
1077 #if SQLITE_ENABLE_HIDDEN_COLUMNS
1078 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
1079 if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
1080 pCol->colFlags |= COLFLAG_HIDDEN;
1081 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
1082 pTab->tabFlags |= TF_OOOHidden;
1085 #endif
1089 ** Add a new column to the table currently being constructed.
1091 ** The parser calls this routine once for each column declaration
1092 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1093 ** first to get things going. Then this routine is called for each
1094 ** column.
1096 void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
1097 Table *p;
1098 int i;
1099 char *z;
1100 char *zType;
1101 Column *pCol;
1102 sqlite3 *db = pParse->db;
1103 if( (p = pParse->pNewTable)==0 ) return;
1104 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1105 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1106 return;
1108 z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
1109 if( z==0 ) return;
1110 if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
1111 memcpy(z, pName->z, pName->n);
1112 z[pName->n] = 0;
1113 sqlite3Dequote(z);
1114 for(i=0; i<p->nCol; i++){
1115 if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
1116 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1117 sqlite3DbFree(db, z);
1118 return;
1121 if( (p->nCol & 0x7)==0 ){
1122 Column *aNew;
1123 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
1124 if( aNew==0 ){
1125 sqlite3DbFree(db, z);
1126 return;
1128 p->aCol = aNew;
1130 pCol = &p->aCol[p->nCol];
1131 memset(pCol, 0, sizeof(p->aCol[0]));
1132 pCol->zName = z;
1133 sqlite3ColumnPropertiesFromName(p, pCol);
1135 if( pType->n==0 ){
1136 /* If there is no type specified, columns have the default affinity
1137 ** 'BLOB' with a default size of 4 bytes. */
1138 pCol->affinity = SQLITE_AFF_BLOB;
1139 pCol->szEst = 1;
1140 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1141 if( 4>=sqlite3GlobalConfig.szSorterRef ){
1142 pCol->colFlags |= COLFLAG_SORTERREF;
1144 #endif
1145 }else{
1146 zType = z + sqlite3Strlen30(z) + 1;
1147 memcpy(zType, pType->z, pType->n);
1148 zType[pType->n] = 0;
1149 sqlite3Dequote(zType);
1150 pCol->affinity = sqlite3AffinityType(zType, pCol);
1151 pCol->colFlags |= COLFLAG_HASTYPE;
1153 p->nCol++;
1154 pParse->constraintName.n = 0;
1158 ** This routine is called by the parser while in the middle of
1159 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1160 ** been seen on a column. This routine sets the notNull flag on
1161 ** the column currently under construction.
1163 void sqlite3AddNotNull(Parse *pParse, int onError){
1164 Table *p;
1165 Column *pCol;
1166 p = pParse->pNewTable;
1167 if( p==0 || NEVER(p->nCol<1) ) return;
1168 pCol = &p->aCol[p->nCol-1];
1169 pCol->notNull = (u8)onError;
1170 p->tabFlags |= TF_HasNotNull;
1172 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1173 ** on this column. */
1174 if( pCol->colFlags & COLFLAG_UNIQUE ){
1175 Index *pIdx;
1176 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1177 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1178 if( pIdx->aiColumn[0]==p->nCol-1 ){
1179 pIdx->uniqNotNull = 1;
1186 ** Scan the column type name zType (length nType) and return the
1187 ** associated affinity type.
1189 ** This routine does a case-independent search of zType for the
1190 ** substrings in the following table. If one of the substrings is
1191 ** found, the corresponding affinity is returned. If zType contains
1192 ** more than one of the substrings, entries toward the top of
1193 ** the table take priority. For example, if zType is 'BLOBINT',
1194 ** SQLITE_AFF_INTEGER is returned.
1196 ** Substring | Affinity
1197 ** --------------------------------
1198 ** 'INT' | SQLITE_AFF_INTEGER
1199 ** 'CHAR' | SQLITE_AFF_TEXT
1200 ** 'CLOB' | SQLITE_AFF_TEXT
1201 ** 'TEXT' | SQLITE_AFF_TEXT
1202 ** 'BLOB' | SQLITE_AFF_BLOB
1203 ** 'REAL' | SQLITE_AFF_REAL
1204 ** 'FLOA' | SQLITE_AFF_REAL
1205 ** 'DOUB' | SQLITE_AFF_REAL
1207 ** If none of the substrings in the above table are found,
1208 ** SQLITE_AFF_NUMERIC is returned.
1210 char sqlite3AffinityType(const char *zIn, Column *pCol){
1211 u32 h = 0;
1212 char aff = SQLITE_AFF_NUMERIC;
1213 const char *zChar = 0;
1215 assert( zIn!=0 );
1216 while( zIn[0] ){
1217 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1218 zIn++;
1219 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1220 aff = SQLITE_AFF_TEXT;
1221 zChar = zIn;
1222 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1223 aff = SQLITE_AFF_TEXT;
1224 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1225 aff = SQLITE_AFF_TEXT;
1226 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1227 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1228 aff = SQLITE_AFF_BLOB;
1229 if( zIn[0]=='(' ) zChar = zIn;
1230 #ifndef SQLITE_OMIT_FLOATING_POINT
1231 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1232 && aff==SQLITE_AFF_NUMERIC ){
1233 aff = SQLITE_AFF_REAL;
1234 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1235 && aff==SQLITE_AFF_NUMERIC ){
1236 aff = SQLITE_AFF_REAL;
1237 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1238 && aff==SQLITE_AFF_NUMERIC ){
1239 aff = SQLITE_AFF_REAL;
1240 #endif
1241 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1242 aff = SQLITE_AFF_INTEGER;
1243 break;
1247 /* If pCol is not NULL, store an estimate of the field size. The
1248 ** estimate is scaled so that the size of an integer is 1. */
1249 if( pCol ){
1250 int v = 0; /* default size is approx 4 bytes */
1251 if( aff<SQLITE_AFF_NUMERIC ){
1252 if( zChar ){
1253 while( zChar[0] ){
1254 if( sqlite3Isdigit(zChar[0]) ){
1255 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1256 sqlite3GetInt32(zChar, &v);
1257 break;
1259 zChar++;
1261 }else{
1262 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1265 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1266 if( v>=sqlite3GlobalConfig.szSorterRef ){
1267 pCol->colFlags |= COLFLAG_SORTERREF;
1269 #endif
1270 v = v/4 + 1;
1271 if( v>255 ) v = 255;
1272 pCol->szEst = v;
1274 return aff;
1278 ** The expression is the default value for the most recently added column
1279 ** of the table currently under construction.
1281 ** Default value expressions must be constant. Raise an exception if this
1282 ** is not the case.
1284 ** This routine is called by the parser while in the middle of
1285 ** parsing a CREATE TABLE statement.
1287 void sqlite3AddDefaultValue(
1288 Parse *pParse, /* Parsing context */
1289 Expr *pExpr, /* The parsed expression of the default value */
1290 const char *zStart, /* Start of the default value text */
1291 const char *zEnd /* First character past end of defaut value text */
1293 Table *p;
1294 Column *pCol;
1295 sqlite3 *db = pParse->db;
1296 p = pParse->pNewTable;
1297 if( p!=0 ){
1298 pCol = &(p->aCol[p->nCol-1]);
1299 if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
1300 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1301 pCol->zName);
1302 }else{
1303 /* A copy of pExpr is used instead of the original, as pExpr contains
1304 ** tokens that point to volatile memory.
1306 Expr x;
1307 sqlite3ExprDelete(db, pCol->pDflt);
1308 memset(&x, 0, sizeof(x));
1309 x.op = TK_SPAN;
1310 x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1311 x.pLeft = pExpr;
1312 x.flags = EP_Skip;
1313 pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1314 sqlite3DbFree(db, x.u.zToken);
1317 if( IN_RENAME_OBJECT ){
1318 sqlite3RenameExprUnmap(pParse, pExpr);
1320 sqlite3ExprDelete(db, pExpr);
1324 ** Backwards Compatibility Hack:
1326 ** Historical versions of SQLite accepted strings as column names in
1327 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1329 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1330 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1332 ** This is goofy. But to preserve backwards compatibility we continue to
1333 ** accept it. This routine does the necessary conversion. It converts
1334 ** the expression given in its argument from a TK_STRING into a TK_ID
1335 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1336 ** If the expression is anything other than TK_STRING, the expression is
1337 ** unchanged.
1339 static void sqlite3StringToId(Expr *p){
1340 if( p->op==TK_STRING ){
1341 p->op = TK_ID;
1342 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1343 p->pLeft->op = TK_ID;
1348 ** Designate the PRIMARY KEY for the table. pList is a list of names
1349 ** of columns that form the primary key. If pList is NULL, then the
1350 ** most recently added column of the table is the primary key.
1352 ** A table can have at most one primary key. If the table already has
1353 ** a primary key (and this is the second primary key) then create an
1354 ** error.
1356 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1357 ** then we will try to use that column as the rowid. Set the Table.iPKey
1358 ** field of the table under construction to be the index of the
1359 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1360 ** no INTEGER PRIMARY KEY.
1362 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1363 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1365 void sqlite3AddPrimaryKey(
1366 Parse *pParse, /* Parsing context */
1367 ExprList *pList, /* List of field names to be indexed */
1368 int onError, /* What to do with a uniqueness conflict */
1369 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1370 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1372 Table *pTab = pParse->pNewTable;
1373 Column *pCol = 0;
1374 int iCol = -1, i;
1375 int nTerm;
1376 if( pTab==0 ) goto primary_key_exit;
1377 if( pTab->tabFlags & TF_HasPrimaryKey ){
1378 sqlite3ErrorMsg(pParse,
1379 "table \"%s\" has more than one primary key", pTab->zName);
1380 goto primary_key_exit;
1382 pTab->tabFlags |= TF_HasPrimaryKey;
1383 if( pList==0 ){
1384 iCol = pTab->nCol - 1;
1385 pCol = &pTab->aCol[iCol];
1386 pCol->colFlags |= COLFLAG_PRIMKEY;
1387 nTerm = 1;
1388 }else{
1389 nTerm = pList->nExpr;
1390 for(i=0; i<nTerm; i++){
1391 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1392 assert( pCExpr!=0 );
1393 sqlite3StringToId(pCExpr);
1394 if( pCExpr->op==TK_ID ){
1395 const char *zCName = pCExpr->u.zToken;
1396 for(iCol=0; iCol<pTab->nCol; iCol++){
1397 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1398 pCol = &pTab->aCol[iCol];
1399 pCol->colFlags |= COLFLAG_PRIMKEY;
1400 break;
1406 if( nTerm==1
1407 && pCol
1408 && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
1409 && sortOrder!=SQLITE_SO_DESC
1411 if( IN_RENAME_OBJECT && pList ){
1412 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1413 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1415 pTab->iPKey = iCol;
1416 pTab->keyConf = (u8)onError;
1417 assert( autoInc==0 || autoInc==1 );
1418 pTab->tabFlags |= autoInc*TF_Autoincrement;
1419 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
1420 }else if( autoInc ){
1421 #ifndef SQLITE_OMIT_AUTOINCREMENT
1422 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1423 "INTEGER PRIMARY KEY");
1424 #endif
1425 }else{
1426 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1427 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1428 pList = 0;
1431 primary_key_exit:
1432 sqlite3ExprListDelete(pParse->db, pList);
1433 return;
1437 ** Add a new CHECK constraint to the table currently under construction.
1439 void sqlite3AddCheckConstraint(
1440 Parse *pParse, /* Parsing context */
1441 Expr *pCheckExpr /* The check expression */
1443 #ifndef SQLITE_OMIT_CHECK
1444 Table *pTab = pParse->pNewTable;
1445 sqlite3 *db = pParse->db;
1446 if( pTab && !IN_DECLARE_VTAB
1447 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1449 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1450 if( pParse->constraintName.n ){
1451 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1453 }else
1454 #endif
1456 sqlite3ExprDelete(pParse->db, pCheckExpr);
1461 ** Set the collation function of the most recently parsed table column
1462 ** to the CollSeq given.
1464 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1465 Table *p;
1466 int i;
1467 char *zColl; /* Dequoted name of collation sequence */
1468 sqlite3 *db;
1470 if( (p = pParse->pNewTable)==0 ) return;
1471 i = p->nCol-1;
1472 db = pParse->db;
1473 zColl = sqlite3NameFromToken(db, pToken);
1474 if( !zColl ) return;
1476 if( sqlite3LocateCollSeq(pParse, zColl) ){
1477 Index *pIdx;
1478 sqlite3DbFree(db, p->aCol[i].zColl);
1479 p->aCol[i].zColl = zColl;
1481 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1482 ** then an index may have been created on this column before the
1483 ** collation type was added. Correct this if it is the case.
1485 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1486 assert( pIdx->nKeyCol==1 );
1487 if( pIdx->aiColumn[0]==i ){
1488 pIdx->azColl[0] = p->aCol[i].zColl;
1491 }else{
1492 sqlite3DbFree(db, zColl);
1497 ** This function returns the collation sequence for database native text
1498 ** encoding identified by the string zName, length nName.
1500 ** If the requested collation sequence is not available, or not available
1501 ** in the database native encoding, the collation factory is invoked to
1502 ** request it. If the collation factory does not supply such a sequence,
1503 ** and the sequence is available in another text encoding, then that is
1504 ** returned instead.
1506 ** If no versions of the requested collations sequence are available, or
1507 ** another error occurs, NULL is returned and an error message written into
1508 ** pParse.
1510 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1511 ** invokes the collation factory if the named collation cannot be found
1512 ** and generates an error message.
1514 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1516 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
1517 sqlite3 *db = pParse->db;
1518 u8 enc = ENC(db);
1519 u8 initbusy = db->init.busy;
1520 CollSeq *pColl;
1522 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
1523 if( !initbusy && (!pColl || !pColl->xCmp) ){
1524 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
1527 return pColl;
1532 ** Generate code that will increment the schema cookie.
1534 ** The schema cookie is used to determine when the schema for the
1535 ** database changes. After each schema change, the cookie value
1536 ** changes. When a process first reads the schema it records the
1537 ** cookie. Thereafter, whenever it goes to access the database,
1538 ** it checks the cookie to make sure the schema has not changed
1539 ** since it was last read.
1541 ** This plan is not completely bullet-proof. It is possible for
1542 ** the schema to change multiple times and for the cookie to be
1543 ** set back to prior value. But schema changes are infrequent
1544 ** and the probability of hitting the same cookie value is only
1545 ** 1 chance in 2^32. So we're safe enough.
1547 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
1548 ** the schema-version whenever the schema changes.
1550 void sqlite3ChangeCookie(Parse *pParse, int iDb){
1551 sqlite3 *db = pParse->db;
1552 Vdbe *v = pParse->pVdbe;
1553 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1554 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
1555 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
1559 ** Measure the number of characters needed to output the given
1560 ** identifier. The number returned includes any quotes used
1561 ** but does not include the null terminator.
1563 ** The estimate is conservative. It might be larger that what is
1564 ** really needed.
1566 static int identLength(const char *z){
1567 int n;
1568 for(n=0; *z; n++, z++){
1569 if( *z=='"' ){ n++; }
1571 return n + 2;
1575 ** The first parameter is a pointer to an output buffer. The second
1576 ** parameter is a pointer to an integer that contains the offset at
1577 ** which to write into the output buffer. This function copies the
1578 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1579 ** to the specified offset in the buffer and updates *pIdx to refer
1580 ** to the first byte after the last byte written before returning.
1582 ** If the string zSignedIdent consists entirely of alpha-numeric
1583 ** characters, does not begin with a digit and is not an SQL keyword,
1584 ** then it is copied to the output buffer exactly as it is. Otherwise,
1585 ** it is quoted using double-quotes.
1587 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1588 unsigned char *zIdent = (unsigned char*)zSignedIdent;
1589 int i, j, needQuote;
1590 i = *pIdx;
1592 for(j=0; zIdent[j]; j++){
1593 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1595 needQuote = sqlite3Isdigit(zIdent[0])
1596 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1597 || zIdent[j]!=0
1598 || j==0;
1600 if( needQuote ) z[i++] = '"';
1601 for(j=0; zIdent[j]; j++){
1602 z[i++] = zIdent[j];
1603 if( zIdent[j]=='"' ) z[i++] = '"';
1605 if( needQuote ) z[i++] = '"';
1606 z[i] = 0;
1607 *pIdx = i;
1611 ** Generate a CREATE TABLE statement appropriate for the given
1612 ** table. Memory to hold the text of the statement is obtained
1613 ** from sqliteMalloc() and must be freed by the calling function.
1615 static char *createTableStmt(sqlite3 *db, Table *p){
1616 int i, k, n;
1617 char *zStmt;
1618 char *zSep, *zSep2, *zEnd;
1619 Column *pCol;
1620 n = 0;
1621 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1622 n += identLength(pCol->zName) + 5;
1624 n += identLength(p->zName);
1625 if( n<50 ){
1626 zSep = "";
1627 zSep2 = ",";
1628 zEnd = ")";
1629 }else{
1630 zSep = "\n ";
1631 zSep2 = ",\n ";
1632 zEnd = "\n)";
1634 n += 35 + 6*p->nCol;
1635 zStmt = sqlite3DbMallocRaw(0, n);
1636 if( zStmt==0 ){
1637 sqlite3OomFault(db);
1638 return 0;
1640 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1641 k = sqlite3Strlen30(zStmt);
1642 identPut(zStmt, &k, p->zName);
1643 zStmt[k++] = '(';
1644 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1645 static const char * const azType[] = {
1646 /* SQLITE_AFF_BLOB */ "",
1647 /* SQLITE_AFF_TEXT */ " TEXT",
1648 /* SQLITE_AFF_NUMERIC */ " NUM",
1649 /* SQLITE_AFF_INTEGER */ " INT",
1650 /* SQLITE_AFF_REAL */ " REAL"
1652 int len;
1653 const char *zType;
1655 sqlite3_snprintf(n-k, &zStmt[k], zSep);
1656 k += sqlite3Strlen30(&zStmt[k]);
1657 zSep = zSep2;
1658 identPut(zStmt, &k, pCol->zName);
1659 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1660 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1661 testcase( pCol->affinity==SQLITE_AFF_BLOB );
1662 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1663 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1664 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1665 testcase( pCol->affinity==SQLITE_AFF_REAL );
1667 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
1668 len = sqlite3Strlen30(zType);
1669 assert( pCol->affinity==SQLITE_AFF_BLOB
1670 || pCol->affinity==sqlite3AffinityType(zType, 0) );
1671 memcpy(&zStmt[k], zType, len);
1672 k += len;
1673 assert( k<=n );
1675 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1676 return zStmt;
1680 ** Resize an Index object to hold N columns total. Return SQLITE_OK
1681 ** on success and SQLITE_NOMEM on an OOM error.
1683 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1684 char *zExtra;
1685 int nByte;
1686 if( pIdx->nColumn>=N ) return SQLITE_OK;
1687 assert( pIdx->isResized==0 );
1688 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1689 zExtra = sqlite3DbMallocZero(db, nByte);
1690 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
1691 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1692 pIdx->azColl = (const char**)zExtra;
1693 zExtra += sizeof(char*)*N;
1694 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1695 pIdx->aiColumn = (i16*)zExtra;
1696 zExtra += sizeof(i16)*N;
1697 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1698 pIdx->aSortOrder = (u8*)zExtra;
1699 pIdx->nColumn = N;
1700 pIdx->isResized = 1;
1701 return SQLITE_OK;
1705 ** Estimate the total row width for a table.
1707 static void estimateTableWidth(Table *pTab){
1708 unsigned wTable = 0;
1709 const Column *pTabCol;
1710 int i;
1711 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1712 wTable += pTabCol->szEst;
1714 if( pTab->iPKey<0 ) wTable++;
1715 pTab->szTabRow = sqlite3LogEst(wTable*4);
1719 ** Estimate the average size of a row for an index.
1721 static void estimateIndexWidth(Index *pIdx){
1722 unsigned wIndex = 0;
1723 int i;
1724 const Column *aCol = pIdx->pTable->aCol;
1725 for(i=0; i<pIdx->nColumn; i++){
1726 i16 x = pIdx->aiColumn[i];
1727 assert( x<pIdx->pTable->nCol );
1728 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
1730 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
1733 /* Return true if column number x is any of the first nCol entries of aiCol[].
1734 ** This is used to determine if the column number x appears in any of the
1735 ** first nCol entries of an index.
1737 static int hasColumn(const i16 *aiCol, int nCol, int x){
1738 while( nCol-- > 0 ){
1739 assert( aiCol[0]>=0 );
1740 if( x==*(aiCol++) ){
1741 return 1;
1744 return 0;
1748 ** Return true if any of the first nKey entries of index pIdx exactly
1749 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
1750 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
1751 ** or may not be the same index as pPk.
1753 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
1754 ** not a rowid or expression.
1756 ** This routine differs from hasColumn() in that both the column and the
1757 ** collating sequence must match for this routine, but for hasColumn() only
1758 ** the column name must match.
1760 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
1761 int i, j;
1762 assert( nKey<=pIdx->nColumn );
1763 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
1764 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
1765 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
1766 assert( pPk->pTable==pIdx->pTable );
1767 testcase( pPk==pIdx );
1768 j = pPk->aiColumn[iCol];
1769 assert( j!=XN_ROWID && j!=XN_EXPR );
1770 for(i=0; i<nKey; i++){
1771 assert( pIdx->aiColumn[i]>=0 || j>=0 );
1772 if( pIdx->aiColumn[i]==j
1773 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
1775 return 1;
1778 return 0;
1781 /* Recompute the colNotIdxed field of the Index.
1783 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
1784 ** columns that are within the first 63 columns of the table. The
1785 ** high-order bit of colNotIdxed is always 1. All unindexed columns
1786 ** of the table have a 1.
1788 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
1789 ** to determine if the index is covering index.
1791 static void recomputeColumnsNotIndexed(Index *pIdx){
1792 Bitmask m = 0;
1793 int j;
1794 for(j=pIdx->nColumn-1; j>=0; j--){
1795 int x = pIdx->aiColumn[j];
1796 if( x>=0 ){
1797 testcase( x==BMS-1 );
1798 testcase( x==BMS-2 );
1799 if( x<BMS-1 ) m |= MASKBIT(x);
1802 pIdx->colNotIdxed = ~m;
1803 assert( (pIdx->colNotIdxed>>63)==1 );
1807 ** This routine runs at the end of parsing a CREATE TABLE statement that
1808 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
1809 ** internal schema data structures and the generated VDBE code so that they
1810 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1811 ** Changes include:
1813 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1814 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
1815 ** into BTREE_BLOBKEY.
1816 ** (3) Bypass the creation of the sqlite_master table entry
1817 ** for the PRIMARY KEY as the primary key index is now
1818 ** identified by the sqlite_master table entry of the table itself.
1819 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
1820 ** schema to the rootpage from the main table.
1821 ** (5) Add all table columns to the PRIMARY KEY Index object
1822 ** so that the PRIMARY KEY is a covering index. The surplus
1823 ** columns are part of KeyInfo.nAllField and are not used for
1824 ** sorting or lookup or uniqueness checks.
1825 ** (6) Replace the rowid tail on all automatically generated UNIQUE
1826 ** indices with the PRIMARY KEY columns.
1828 ** For virtual tables, only (1) is performed.
1830 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1831 Index *pIdx;
1832 Index *pPk;
1833 int nPk;
1834 int i, j;
1835 sqlite3 *db = pParse->db;
1836 Vdbe *v = pParse->pVdbe;
1838 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
1840 if( !db->init.imposterTable ){
1841 for(i=0; i<pTab->nCol; i++){
1842 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
1843 pTab->aCol[i].notNull = OE_Abort;
1848 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
1849 ** into BTREE_BLOBKEY.
1851 if( pParse->addrCrTab ){
1852 assert( v );
1853 sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
1856 /* Locate the PRIMARY KEY index. Or, if this table was originally
1857 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1859 if( pTab->iPKey>=0 ){
1860 ExprList *pList;
1861 Token ipkToken;
1862 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
1863 pList = sqlite3ExprListAppend(pParse, 0,
1864 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
1865 if( pList==0 ) return;
1866 if( IN_RENAME_OBJECT ){
1867 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
1869 pList->a[0].sortOrder = pParse->iPkSortOrder;
1870 assert( pParse->pNewTable==pTab );
1871 pTab->iPKey = -1;
1872 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
1873 SQLITE_IDXTYPE_PRIMARYKEY);
1874 if( db->mallocFailed || pParse->nErr ) return;
1875 pPk = sqlite3PrimaryKeyIndex(pTab);
1876 }else{
1877 pPk = sqlite3PrimaryKeyIndex(pTab);
1878 assert( pPk!=0 );
1881 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1882 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1883 ** code assumes the PRIMARY KEY contains no repeated columns.
1885 for(i=j=1; i<pPk->nKeyCol; i++){
1886 if( isDupColumn(pPk, j, pPk, i) ){
1887 pPk->nColumn--;
1888 }else{
1889 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
1890 pPk->aiColumn[j++] = pPk->aiColumn[i];
1893 pPk->nKeyCol = j;
1895 assert( pPk!=0 );
1896 pPk->isCovering = 1;
1897 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
1898 nPk = pPk->nKeyCol;
1900 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1901 ** table entry. This is only required if currently generating VDBE
1902 ** code for a CREATE TABLE (not when parsing one as part of reading
1903 ** a database schema). */
1904 if( v && pPk->tnum>0 ){
1905 assert( db->init.busy==0 );
1906 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
1909 /* The root page of the PRIMARY KEY is the table root page */
1910 pPk->tnum = pTab->tnum;
1912 /* Update the in-memory representation of all UNIQUE indices by converting
1913 ** the final rowid column into one or more columns of the PRIMARY KEY.
1915 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1916 int n;
1917 if( IsPrimaryKeyIndex(pIdx) ) continue;
1918 for(i=n=0; i<nPk; i++){
1919 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
1920 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
1921 n++;
1924 if( n==0 ){
1925 /* This index is a superset of the primary key */
1926 pIdx->nColumn = pIdx->nKeyCol;
1927 continue;
1929 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1930 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
1931 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
1932 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
1933 pIdx->aiColumn[j] = pPk->aiColumn[i];
1934 pIdx->azColl[j] = pPk->azColl[i];
1935 if( pPk->aSortOrder[i] ){
1936 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
1937 pIdx->bAscKeyBug = 1;
1939 j++;
1942 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1943 assert( pIdx->nColumn>=j );
1946 /* Add all table columns to the PRIMARY KEY index
1948 if( nPk<pTab->nCol ){
1949 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1950 for(i=0, j=nPk; i<pTab->nCol; i++){
1951 if( !hasColumn(pPk->aiColumn, j, i) ){
1952 assert( j<pPk->nColumn );
1953 pPk->aiColumn[j] = i;
1954 pPk->azColl[j] = sqlite3StrBINARY;
1955 j++;
1958 assert( pPk->nColumn==j );
1959 assert( pTab->nCol==j );
1960 }else{
1961 pPk->nColumn = pTab->nCol;
1963 recomputeColumnsNotIndexed(pPk);
1966 #ifndef SQLITE_OMIT_VIRTUALTABLE
1968 ** Return true if zName is a shadow table name in the current database
1969 ** connection.
1971 ** zName is temporarily modified while this routine is running, but is
1972 ** restored to its original value prior to this routine returning.
1974 static int isShadowTableName(sqlite3 *db, char *zName){
1975 char *zTail; /* Pointer to the last "_" in zName */
1976 Table *pTab; /* Table that zName is a shadow of */
1977 Module *pMod; /* Module for the virtual table */
1979 zTail = strrchr(zName, '_');
1980 if( zTail==0 ) return 0;
1981 *zTail = 0;
1982 pTab = sqlite3FindTable(db, zName, 0);
1983 *zTail = '_';
1984 if( pTab==0 ) return 0;
1985 if( !IsVirtual(pTab) ) return 0;
1986 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
1987 if( pMod==0 ) return 0;
1988 if( pMod->pModule->iVersion<3 ) return 0;
1989 if( pMod->pModule->xShadowName==0 ) return 0;
1990 return pMod->pModule->xShadowName(zTail+1);
1992 #else
1993 # define isShadowTableName(x,y) 0
1994 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
1997 ** This routine is called to report the final ")" that terminates
1998 ** a CREATE TABLE statement.
2000 ** The table structure that other action routines have been building
2001 ** is added to the internal hash tables, assuming no errors have
2002 ** occurred.
2004 ** An entry for the table is made in the master table on disk, unless
2005 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
2006 ** it means we are reading the sqlite_master table because we just
2007 ** connected to the database or because the sqlite_master table has
2008 ** recently changed, so the entry for this table already exists in
2009 ** the sqlite_master table. We do not want to create it again.
2011 ** If the pSelect argument is not NULL, it means that this routine
2012 ** was called to create a table generated from a
2013 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2014 ** the new table will match the result set of the SELECT.
2016 void sqlite3EndTable(
2017 Parse *pParse, /* Parse context */
2018 Token *pCons, /* The ',' token after the last column defn. */
2019 Token *pEnd, /* The ')' before options in the CREATE TABLE */
2020 u8 tabOpts, /* Extra table options. Usually 0. */
2021 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
2023 Table *p; /* The new table */
2024 sqlite3 *db = pParse->db; /* The database connection */
2025 int iDb; /* Database in which the table lives */
2026 Index *pIdx; /* An implied index of the table */
2028 if( pEnd==0 && pSelect==0 ){
2029 return;
2031 assert( !db->mallocFailed );
2032 p = pParse->pNewTable;
2033 if( p==0 ) return;
2035 if( pSelect==0 && isShadowTableName(db, p->zName) ){
2036 p->tabFlags |= TF_Shadow;
2039 /* If the db->init.busy is 1 it means we are reading the SQL off the
2040 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
2041 ** So do not write to the disk again. Extract the root page number
2042 ** for the table from the db->init.newTnum field. (The page number
2043 ** should have been put there by the sqliteOpenCb routine.)
2045 ** If the root page number is 1, that means this is the sqlite_master
2046 ** table itself. So mark it read-only.
2048 if( db->init.busy ){
2049 if( pSelect ){
2050 sqlite3ErrorMsg(pParse, "");
2051 return;
2053 p->tnum = db->init.newTnum;
2054 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2057 assert( (p->tabFlags & TF_HasPrimaryKey)==0
2058 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2059 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2060 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2062 /* Special processing for WITHOUT ROWID Tables */
2063 if( tabOpts & TF_WithoutRowid ){
2064 if( (p->tabFlags & TF_Autoincrement) ){
2065 sqlite3ErrorMsg(pParse,
2066 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2067 return;
2069 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2070 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2071 }else{
2072 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2073 convertToWithoutRowidTable(pParse, p);
2077 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2079 #ifndef SQLITE_OMIT_CHECK
2080 /* Resolve names in all CHECK constraint expressions.
2082 if( p->pCheck ){
2083 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2085 #endif /* !defined(SQLITE_OMIT_CHECK) */
2087 /* Estimate the average row size for the table and for all implied indices */
2088 estimateTableWidth(p);
2089 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2090 estimateIndexWidth(pIdx);
2093 /* If not initializing, then create a record for the new table
2094 ** in the SQLITE_MASTER table of the database.
2096 ** If this is a TEMPORARY table, write the entry into the auxiliary
2097 ** file instead of into the main database file.
2099 if( !db->init.busy ){
2100 int n;
2101 Vdbe *v;
2102 char *zType; /* "view" or "table" */
2103 char *zType2; /* "VIEW" or "TABLE" */
2104 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
2106 v = sqlite3GetVdbe(pParse);
2107 if( NEVER(v==0) ) return;
2109 sqlite3VdbeAddOp1(v, OP_Close, 0);
2112 ** Initialize zType for the new view or table.
2114 if( p->pSelect==0 ){
2115 /* A regular table */
2116 zType = "table";
2117 zType2 = "TABLE";
2118 #ifndef SQLITE_OMIT_VIEW
2119 }else{
2120 /* A view */
2121 zType = "view";
2122 zType2 = "VIEW";
2123 #endif
2126 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2127 ** statement to populate the new table. The root-page number for the
2128 ** new table is in register pParse->regRoot.
2130 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2131 ** suitable state to query for the column names and types to be used
2132 ** by the new table.
2134 ** A shared-cache write-lock is not required to write to the new table,
2135 ** as a schema-lock must have already been obtained to create it. Since
2136 ** a schema-lock excludes all other database users, the write-lock would
2137 ** be redundant.
2139 if( pSelect ){
2140 SelectDest dest; /* Where the SELECT should store results */
2141 int regYield; /* Register holding co-routine entry-point */
2142 int addrTop; /* Top of the co-routine */
2143 int regRec; /* A record to be insert into the new table */
2144 int regRowid; /* Rowid of the next row to insert */
2145 int addrInsLoop; /* Top of the loop for inserting rows */
2146 Table *pSelTab; /* A table that describes the SELECT results */
2148 regYield = ++pParse->nMem;
2149 regRec = ++pParse->nMem;
2150 regRowid = ++pParse->nMem;
2151 assert(pParse->nTab==1);
2152 sqlite3MayAbort(pParse);
2153 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2154 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2155 pParse->nTab = 2;
2156 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2157 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2158 if( pParse->nErr ) return;
2159 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
2160 if( pSelTab==0 ) return;
2161 assert( p->aCol==0 );
2162 p->nCol = pSelTab->nCol;
2163 p->aCol = pSelTab->aCol;
2164 pSelTab->nCol = 0;
2165 pSelTab->aCol = 0;
2166 sqlite3DeleteTable(db, pSelTab);
2167 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2168 sqlite3Select(pParse, pSelect, &dest);
2169 if( pParse->nErr ) return;
2170 sqlite3VdbeEndCoroutine(v, regYield);
2171 sqlite3VdbeJumpHere(v, addrTop - 1);
2172 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2173 VdbeCoverage(v);
2174 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2175 sqlite3TableAffinity(v, p, 0);
2176 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2177 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2178 sqlite3VdbeGoto(v, addrInsLoop);
2179 sqlite3VdbeJumpHere(v, addrInsLoop);
2180 sqlite3VdbeAddOp1(v, OP_Close, 1);
2183 /* Compute the complete text of the CREATE statement */
2184 if( pSelect ){
2185 zStmt = createTableStmt(db, p);
2186 }else{
2187 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2188 n = (int)(pEnd2->z - pParse->sNameToken.z);
2189 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
2190 zStmt = sqlite3MPrintf(db,
2191 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2195 /* A slot for the record has already been allocated in the
2196 ** SQLITE_MASTER table. We just need to update that slot with all
2197 ** the information we've collected.
2199 sqlite3NestedParse(pParse,
2200 "UPDATE %Q.%s "
2201 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
2202 "WHERE rowid=#%d",
2203 db->aDb[iDb].zDbSName, MASTER_NAME,
2204 zType,
2205 p->zName,
2206 p->zName,
2207 pParse->regRoot,
2208 zStmt,
2209 pParse->regRowid
2211 sqlite3DbFree(db, zStmt);
2212 sqlite3ChangeCookie(pParse, iDb);
2214 #ifndef SQLITE_OMIT_AUTOINCREMENT
2215 /* Check to see if we need to create an sqlite_sequence table for
2216 ** keeping track of autoincrement keys.
2218 if( (p->tabFlags & TF_Autoincrement)!=0 ){
2219 Db *pDb = &db->aDb[iDb];
2220 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2221 if( pDb->pSchema->pSeqTab==0 ){
2222 sqlite3NestedParse(pParse,
2223 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2224 pDb->zDbSName
2228 #endif
2230 /* Reparse everything to update our internal data structures */
2231 sqlite3VdbeAddParseSchemaOp(v, iDb,
2232 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
2236 /* Add the table to the in-memory representation of the database.
2238 if( db->init.busy ){
2239 Table *pOld;
2240 Schema *pSchema = p->pSchema;
2241 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2242 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
2243 if( pOld ){
2244 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
2245 sqlite3OomFault(db);
2246 return;
2248 pParse->pNewTable = 0;
2249 db->mDbFlags |= DBFLAG_SchemaChange;
2251 #ifndef SQLITE_OMIT_ALTERTABLE
2252 if( !p->pSelect ){
2253 const char *zName = (const char *)pParse->sNameToken.z;
2254 int nName;
2255 assert( !pSelect && pCons && pEnd );
2256 if( pCons->z==0 ){
2257 pCons = pEnd;
2259 nName = (int)((const char *)pCons->z - zName);
2260 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
2262 #endif
2266 #ifndef SQLITE_OMIT_VIEW
2268 ** The parser calls this routine in order to create a new VIEW
2270 void sqlite3CreateView(
2271 Parse *pParse, /* The parsing context */
2272 Token *pBegin, /* The CREATE token that begins the statement */
2273 Token *pName1, /* The token that holds the name of the view */
2274 Token *pName2, /* The token that holds the name of the view */
2275 ExprList *pCNames, /* Optional list of view column names */
2276 Select *pSelect, /* A SELECT statement that will become the new view */
2277 int isTemp, /* TRUE for a TEMPORARY view */
2278 int noErr /* Suppress error messages if VIEW already exists */
2280 Table *p;
2281 int n;
2282 const char *z;
2283 Token sEnd;
2284 DbFixer sFix;
2285 Token *pName = 0;
2286 int iDb;
2287 sqlite3 *db = pParse->db;
2289 if( pParse->nVar>0 ){
2290 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2291 goto create_view_fail;
2293 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2294 p = pParse->pNewTable;
2295 if( p==0 || pParse->nErr ) goto create_view_fail;
2296 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2297 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2298 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2299 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
2301 /* Make a copy of the entire SELECT statement that defines the view.
2302 ** This will force all the Expr.token.z values to be dynamically
2303 ** allocated rather than point to the input string - which means that
2304 ** they will persist after the current sqlite3_exec() call returns.
2306 if( IN_RENAME_OBJECT ){
2307 p->pSelect = pSelect;
2308 pSelect = 0;
2309 }else{
2310 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
2312 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2313 if( db->mallocFailed ) goto create_view_fail;
2315 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2316 ** the end.
2318 sEnd = pParse->sLastToken;
2319 assert( sEnd.z[0]!=0 || sEnd.n==0 );
2320 if( sEnd.z[0]!=';' ){
2321 sEnd.z += sEnd.n;
2323 sEnd.n = 0;
2324 n = (int)(sEnd.z - pBegin->z);
2325 assert( n>0 );
2326 z = pBegin->z;
2327 while( sqlite3Isspace(z[n-1]) ){ n--; }
2328 sEnd.z = &z[n-1];
2329 sEnd.n = 1;
2331 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
2332 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
2334 create_view_fail:
2335 sqlite3SelectDelete(db, pSelect);
2336 if( IN_RENAME_OBJECT ){
2337 sqlite3RenameExprlistUnmap(pParse, pCNames);
2339 sqlite3ExprListDelete(db, pCNames);
2340 return;
2342 #endif /* SQLITE_OMIT_VIEW */
2344 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2346 ** The Table structure pTable is really a VIEW. Fill in the names of
2347 ** the columns of the view in the pTable structure. Return the number
2348 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
2350 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
2351 Table *pSelTab; /* A fake table from which we get the result set */
2352 Select *pSel; /* Copy of the SELECT that implements the view */
2353 int nErr = 0; /* Number of errors encountered */
2354 int n; /* Temporarily holds the number of cursors assigned */
2355 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
2356 #ifndef SQLITE_OMIT_VIRTUALTABLE
2357 int rc;
2358 #endif
2359 #ifndef SQLITE_OMIT_AUTHORIZATION
2360 sqlite3_xauth xAuth; /* Saved xAuth pointer */
2361 #endif
2363 assert( pTable );
2365 #ifndef SQLITE_OMIT_VIRTUALTABLE
2366 db->nSchemaLock++;
2367 rc = sqlite3VtabCallConnect(pParse, pTable);
2368 db->nSchemaLock--;
2369 if( rc ){
2370 return 1;
2372 if( IsVirtual(pTable) ) return 0;
2373 #endif
2375 #ifndef SQLITE_OMIT_VIEW
2376 /* A positive nCol means the columns names for this view are
2377 ** already known.
2379 if( pTable->nCol>0 ) return 0;
2381 /* A negative nCol is a special marker meaning that we are currently
2382 ** trying to compute the column names. If we enter this routine with
2383 ** a negative nCol, it means two or more views form a loop, like this:
2385 ** CREATE VIEW one AS SELECT * FROM two;
2386 ** CREATE VIEW two AS SELECT * FROM one;
2388 ** Actually, the error above is now caught prior to reaching this point.
2389 ** But the following test is still important as it does come up
2390 ** in the following:
2392 ** CREATE TABLE main.ex1(a);
2393 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2394 ** SELECT * FROM temp.ex1;
2396 if( pTable->nCol<0 ){
2397 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
2398 return 1;
2400 assert( pTable->nCol>=0 );
2402 /* If we get this far, it means we need to compute the table names.
2403 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2404 ** "*" elements in the results set of the view and will assign cursors
2405 ** to the elements of the FROM clause. But we do not want these changes
2406 ** to be permanent. So the computation is done on a copy of the SELECT
2407 ** statement that defines the view.
2409 assert( pTable->pSelect );
2410 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2411 if( pSel ){
2412 #ifndef SQLITE_OMIT_ALTERTABLE
2413 u8 eParseMode = pParse->eParseMode;
2414 pParse->eParseMode = PARSE_MODE_NORMAL;
2415 #endif
2416 n = pParse->nTab;
2417 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2418 pTable->nCol = -1;
2419 db->lookaside.bDisable++;
2420 #ifndef SQLITE_OMIT_AUTHORIZATION
2421 xAuth = db->xAuth;
2422 db->xAuth = 0;
2423 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2424 db->xAuth = xAuth;
2425 #else
2426 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2427 #endif
2428 pParse->nTab = n;
2429 if( pTable->pCheck ){
2430 /* CREATE VIEW name(arglist) AS ...
2431 ** The names of the columns in the table are taken from
2432 ** arglist which is stored in pTable->pCheck. The pCheck field
2433 ** normally holds CHECK constraints on an ordinary table, but for
2434 ** a VIEW it holds the list of column names.
2436 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2437 &pTable->nCol, &pTable->aCol);
2438 if( db->mallocFailed==0
2439 && pParse->nErr==0
2440 && pTable->nCol==pSel->pEList->nExpr
2442 sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
2444 }else if( pSelTab ){
2445 /* CREATE VIEW name AS... without an argument list. Construct
2446 ** the column names from the SELECT statement that defines the view.
2448 assert( pTable->aCol==0 );
2449 pTable->nCol = pSelTab->nCol;
2450 pTable->aCol = pSelTab->aCol;
2451 pSelTab->nCol = 0;
2452 pSelTab->aCol = 0;
2453 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2454 }else{
2455 pTable->nCol = 0;
2456 nErr++;
2458 sqlite3DeleteTable(db, pSelTab);
2459 sqlite3SelectDelete(db, pSel);
2460 db->lookaside.bDisable--;
2461 #ifndef SQLITE_OMIT_ALTERTABLE
2462 pParse->eParseMode = eParseMode;
2463 #endif
2464 } else {
2465 nErr++;
2467 pTable->pSchema->schemaFlags |= DB_UnresetViews;
2468 if( db->mallocFailed ){
2469 sqlite3DeleteColumnNames(db, pTable);
2470 pTable->aCol = 0;
2471 pTable->nCol = 0;
2473 #endif /* SQLITE_OMIT_VIEW */
2474 return nErr;
2476 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2478 #ifndef SQLITE_OMIT_VIEW
2480 ** Clear the column names from every VIEW in database idx.
2482 static void sqliteViewResetAll(sqlite3 *db, int idx){
2483 HashElem *i;
2484 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
2485 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
2486 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
2487 Table *pTab = sqliteHashData(i);
2488 if( pTab->pSelect ){
2489 sqlite3DeleteColumnNames(db, pTab);
2490 pTab->aCol = 0;
2491 pTab->nCol = 0;
2494 DbClearProperty(db, idx, DB_UnresetViews);
2496 #else
2497 # define sqliteViewResetAll(A,B)
2498 #endif /* SQLITE_OMIT_VIEW */
2501 ** This function is called by the VDBE to adjust the internal schema
2502 ** used by SQLite when the btree layer moves a table root page. The
2503 ** root-page of a table or index in database iDb has changed from iFrom
2504 ** to iTo.
2506 ** Ticket #1728: The symbol table might still contain information
2507 ** on tables and/or indices that are the process of being deleted.
2508 ** If you are unlucky, one of those deleted indices or tables might
2509 ** have the same rootpage number as the real table or index that is
2510 ** being moved. So we cannot stop searching after the first match
2511 ** because the first match might be for one of the deleted indices
2512 ** or tables and not the table/index that is actually being moved.
2513 ** We must continue looping until all tables and indices with
2514 ** rootpage==iFrom have been converted to have a rootpage of iTo
2515 ** in order to be certain that we got the right one.
2517 #ifndef SQLITE_OMIT_AUTOVACUUM
2518 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
2519 HashElem *pElem;
2520 Hash *pHash;
2521 Db *pDb;
2523 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2524 pDb = &db->aDb[iDb];
2525 pHash = &pDb->pSchema->tblHash;
2526 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2527 Table *pTab = sqliteHashData(pElem);
2528 if( pTab->tnum==iFrom ){
2529 pTab->tnum = iTo;
2532 pHash = &pDb->pSchema->idxHash;
2533 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
2534 Index *pIdx = sqliteHashData(pElem);
2535 if( pIdx->tnum==iFrom ){
2536 pIdx->tnum = iTo;
2540 #endif
2543 ** Write code to erase the table with root-page iTable from database iDb.
2544 ** Also write code to modify the sqlite_master table and internal schema
2545 ** if a root-page of another table is moved by the btree-layer whilst
2546 ** erasing iTable (this can happen with an auto-vacuum database).
2548 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2549 Vdbe *v = sqlite3GetVdbe(pParse);
2550 int r1 = sqlite3GetTempReg(pParse);
2551 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
2552 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
2553 sqlite3MayAbort(pParse);
2554 #ifndef SQLITE_OMIT_AUTOVACUUM
2555 /* OP_Destroy stores an in integer r1. If this integer
2556 ** is non-zero, then it is the root page number of a table moved to
2557 ** location iTable. The following code modifies the sqlite_master table to
2558 ** reflect this.
2560 ** The "#NNN" in the SQL is a special constant that means whatever value
2561 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2562 ** token for additional information.
2564 sqlite3NestedParse(pParse,
2565 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2566 pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
2567 #endif
2568 sqlite3ReleaseTempReg(pParse, r1);
2572 ** Write VDBE code to erase table pTab and all associated indices on disk.
2573 ** Code to update the sqlite_master tables and internal schema definitions
2574 ** in case a root-page belonging to another table is moved by the btree layer
2575 ** is also added (this can happen with an auto-vacuum database).
2577 static void destroyTable(Parse *pParse, Table *pTab){
2578 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2579 ** is not defined), then it is important to call OP_Destroy on the
2580 ** table and index root-pages in order, starting with the numerically
2581 ** largest root-page number. This guarantees that none of the root-pages
2582 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2583 ** following were coded:
2585 ** OP_Destroy 4 0
2586 ** ...
2587 ** OP_Destroy 5 0
2589 ** and root page 5 happened to be the largest root-page number in the
2590 ** database, then root page 5 would be moved to page 4 by the
2591 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2592 ** a free-list page.
2594 int iTab = pTab->tnum;
2595 int iDestroyed = 0;
2597 while( 1 ){
2598 Index *pIdx;
2599 int iLargest = 0;
2601 if( iDestroyed==0 || iTab<iDestroyed ){
2602 iLargest = iTab;
2604 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2605 int iIdx = pIdx->tnum;
2606 assert( pIdx->pSchema==pTab->pSchema );
2607 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2608 iLargest = iIdx;
2611 if( iLargest==0 ){
2612 return;
2613 }else{
2614 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2615 assert( iDb>=0 && iDb<pParse->db->nDb );
2616 destroyRootPage(pParse, iLargest, iDb);
2617 iDestroyed = iLargest;
2623 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2624 ** after a DROP INDEX or DROP TABLE command.
2626 static void sqlite3ClearStatTables(
2627 Parse *pParse, /* The parsing context */
2628 int iDb, /* The database number */
2629 const char *zType, /* "idx" or "tbl" */
2630 const char *zName /* Name of index or table */
2632 int i;
2633 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
2634 for(i=1; i<=4; i++){
2635 char zTab[24];
2636 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2637 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
2638 sqlite3NestedParse(pParse,
2639 "DELETE FROM %Q.%s WHERE %s=%Q",
2640 zDbName, zTab, zType, zName
2647 ** Generate code to drop a table.
2649 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2650 Vdbe *v;
2651 sqlite3 *db = pParse->db;
2652 Trigger *pTrigger;
2653 Db *pDb = &db->aDb[iDb];
2655 v = sqlite3GetVdbe(pParse);
2656 assert( v!=0 );
2657 sqlite3BeginWriteOperation(pParse, 1, iDb);
2659 #ifndef SQLITE_OMIT_VIRTUALTABLE
2660 if( IsVirtual(pTab) ){
2661 sqlite3VdbeAddOp0(v, OP_VBegin);
2663 #endif
2665 /* Drop all triggers associated with the table being dropped. Code
2666 ** is generated to remove entries from sqlite_master and/or
2667 ** sqlite_temp_master if required.
2669 pTrigger = sqlite3TriggerList(pParse, pTab);
2670 while( pTrigger ){
2671 assert( pTrigger->pSchema==pTab->pSchema ||
2672 pTrigger->pSchema==db->aDb[1].pSchema );
2673 sqlite3DropTriggerPtr(pParse, pTrigger);
2674 pTrigger = pTrigger->pNext;
2677 #ifndef SQLITE_OMIT_AUTOINCREMENT
2678 /* Remove any entries of the sqlite_sequence table associated with
2679 ** the table being dropped. This is done before the table is dropped
2680 ** at the btree level, in case the sqlite_sequence table needs to
2681 ** move as a result of the drop (can happen in auto-vacuum mode).
2683 if( pTab->tabFlags & TF_Autoincrement ){
2684 sqlite3NestedParse(pParse,
2685 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2686 pDb->zDbSName, pTab->zName
2689 #endif
2691 /* Drop all SQLITE_MASTER table and index entries that refer to the
2692 ** table. The program name loops through the master table and deletes
2693 ** every row that refers to a table of the same name as the one being
2694 ** dropped. Triggers are handled separately because a trigger can be
2695 ** created in the temp database that refers to a table in another
2696 ** database.
2698 sqlite3NestedParse(pParse,
2699 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2700 pDb->zDbSName, MASTER_NAME, pTab->zName);
2701 if( !isView && !IsVirtual(pTab) ){
2702 destroyTable(pParse, pTab);
2705 /* Remove the table entry from SQLite's internal schema and modify
2706 ** the schema cookie.
2708 if( IsVirtual(pTab) ){
2709 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2710 sqlite3MayAbort(pParse);
2712 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2713 sqlite3ChangeCookie(pParse, iDb);
2714 sqliteViewResetAll(db, iDb);
2718 ** This routine is called to do the work of a DROP TABLE statement.
2719 ** pName is the name of the table to be dropped.
2721 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
2722 Table *pTab;
2723 Vdbe *v;
2724 sqlite3 *db = pParse->db;
2725 int iDb;
2727 if( db->mallocFailed ){
2728 goto exit_drop_table;
2730 assert( pParse->nErr==0 );
2731 assert( pName->nSrc==1 );
2732 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
2733 if( noErr ) db->suppressErr++;
2734 assert( isView==0 || isView==LOCATE_VIEW );
2735 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
2736 if( noErr ) db->suppressErr--;
2738 if( pTab==0 ){
2739 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2740 goto exit_drop_table;
2742 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2743 assert( iDb>=0 && iDb<db->nDb );
2745 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2746 ** it is initialized.
2748 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2749 goto exit_drop_table;
2751 #ifndef SQLITE_OMIT_AUTHORIZATION
2753 int code;
2754 const char *zTab = SCHEMA_TABLE(iDb);
2755 const char *zDb = db->aDb[iDb].zDbSName;
2756 const char *zArg2 = 0;
2757 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
2758 goto exit_drop_table;
2760 if( isView ){
2761 if( !OMIT_TEMPDB && iDb==1 ){
2762 code = SQLITE_DROP_TEMP_VIEW;
2763 }else{
2764 code = SQLITE_DROP_VIEW;
2766 #ifndef SQLITE_OMIT_VIRTUALTABLE
2767 }else if( IsVirtual(pTab) ){
2768 code = SQLITE_DROP_VTABLE;
2769 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
2770 #endif
2771 }else{
2772 if( !OMIT_TEMPDB && iDb==1 ){
2773 code = SQLITE_DROP_TEMP_TABLE;
2774 }else{
2775 code = SQLITE_DROP_TABLE;
2778 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2779 goto exit_drop_table;
2781 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2782 goto exit_drop_table;
2785 #endif
2786 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2787 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
2788 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2789 goto exit_drop_table;
2792 #ifndef SQLITE_OMIT_VIEW
2793 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2794 ** on a table.
2796 if( isView && pTab->pSelect==0 ){
2797 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2798 goto exit_drop_table;
2800 if( !isView && pTab->pSelect ){
2801 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2802 goto exit_drop_table;
2804 #endif
2806 /* Generate code to remove the table from the master table
2807 ** on disk.
2809 v = sqlite3GetVdbe(pParse);
2810 if( v ){
2811 sqlite3BeginWriteOperation(pParse, 1, iDb);
2812 if( !isView ){
2813 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
2814 sqlite3FkDropTable(pParse, pName, pTab);
2816 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
2819 exit_drop_table:
2820 sqlite3SrcListDelete(db, pName);
2824 ** This routine is called to create a new foreign key on the table
2825 ** currently under construction. pFromCol determines which columns
2826 ** in the current table point to the foreign key. If pFromCol==0 then
2827 ** connect the key to the last column inserted. pTo is the name of
2828 ** the table referred to (a.k.a the "parent" table). pToCol is a list
2829 ** of tables in the parent pTo table. flags contains all
2830 ** information about the conflict resolution algorithms specified
2831 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2833 ** An FKey structure is created and added to the table currently
2834 ** under construction in the pParse->pNewTable field.
2836 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2837 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2839 void sqlite3CreateForeignKey(
2840 Parse *pParse, /* Parsing context */
2841 ExprList *pFromCol, /* Columns in this table that point to other table */
2842 Token *pTo, /* Name of the other table */
2843 ExprList *pToCol, /* Columns in the other table */
2844 int flags /* Conflict resolution algorithms. */
2846 sqlite3 *db = pParse->db;
2847 #ifndef SQLITE_OMIT_FOREIGN_KEY
2848 FKey *pFKey = 0;
2849 FKey *pNextTo;
2850 Table *p = pParse->pNewTable;
2851 int nByte;
2852 int i;
2853 int nCol;
2854 char *z;
2856 assert( pTo!=0 );
2857 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2858 if( pFromCol==0 ){
2859 int iCol = p->nCol-1;
2860 if( NEVER(iCol<0) ) goto fk_end;
2861 if( pToCol && pToCol->nExpr!=1 ){
2862 sqlite3ErrorMsg(pParse, "foreign key on %s"
2863 " should reference only one column of table %T",
2864 p->aCol[iCol].zName, pTo);
2865 goto fk_end;
2867 nCol = 1;
2868 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2869 sqlite3ErrorMsg(pParse,
2870 "number of columns in foreign key does not match the number of "
2871 "columns in the referenced table");
2872 goto fk_end;
2873 }else{
2874 nCol = pFromCol->nExpr;
2876 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2877 if( pToCol ){
2878 for(i=0; i<pToCol->nExpr; i++){
2879 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2882 pFKey = sqlite3DbMallocZero(db, nByte );
2883 if( pFKey==0 ){
2884 goto fk_end;
2886 pFKey->pFrom = p;
2887 pFKey->pNextFrom = p->pFKey;
2888 z = (char*)&pFKey->aCol[nCol];
2889 pFKey->zTo = z;
2890 if( IN_RENAME_OBJECT ){
2891 sqlite3RenameTokenMap(pParse, (void*)z, pTo);
2893 memcpy(z, pTo->z, pTo->n);
2894 z[pTo->n] = 0;
2895 sqlite3Dequote(z);
2896 z += pTo->n+1;
2897 pFKey->nCol = nCol;
2898 if( pFromCol==0 ){
2899 pFKey->aCol[0].iFrom = p->nCol-1;
2900 }else{
2901 for(i=0; i<nCol; i++){
2902 int j;
2903 for(j=0; j<p->nCol; j++){
2904 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2905 pFKey->aCol[i].iFrom = j;
2906 break;
2909 if( j>=p->nCol ){
2910 sqlite3ErrorMsg(pParse,
2911 "unknown column \"%s\" in foreign key definition",
2912 pFromCol->a[i].zName);
2913 goto fk_end;
2915 if( IN_RENAME_OBJECT ){
2916 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
2920 if( pToCol ){
2921 for(i=0; i<nCol; i++){
2922 int n = sqlite3Strlen30(pToCol->a[i].zName);
2923 pFKey->aCol[i].zCol = z;
2924 if( IN_RENAME_OBJECT ){
2925 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
2927 memcpy(z, pToCol->a[i].zName, n);
2928 z[n] = 0;
2929 z += n+1;
2932 pFKey->isDeferred = 0;
2933 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2934 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
2936 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2937 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2938 pFKey->zTo, (void *)pFKey
2940 if( pNextTo==pFKey ){
2941 sqlite3OomFault(db);
2942 goto fk_end;
2944 if( pNextTo ){
2945 assert( pNextTo->pPrevTo==0 );
2946 pFKey->pNextTo = pNextTo;
2947 pNextTo->pPrevTo = pFKey;
2950 /* Link the foreign key to the table as the last step.
2952 p->pFKey = pFKey;
2953 pFKey = 0;
2955 fk_end:
2956 sqlite3DbFree(db, pFKey);
2957 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2958 sqlite3ExprListDelete(db, pFromCol);
2959 sqlite3ExprListDelete(db, pToCol);
2963 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2964 ** clause is seen as part of a foreign key definition. The isDeferred
2965 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2966 ** The behavior of the most recently created foreign key is adjusted
2967 ** accordingly.
2969 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2970 #ifndef SQLITE_OMIT_FOREIGN_KEY
2971 Table *pTab;
2972 FKey *pFKey;
2973 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2974 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
2975 pFKey->isDeferred = (u8)isDeferred;
2976 #endif
2980 ** Generate code that will erase and refill index *pIdx. This is
2981 ** used to initialize a newly created index or to recompute the
2982 ** content of an index in response to a REINDEX command.
2984 ** if memRootPage is not negative, it means that the index is newly
2985 ** created. The register specified by memRootPage contains the
2986 ** root page number of the index. If memRootPage is negative, then
2987 ** the index already exists and must be cleared before being refilled and
2988 ** the root page number of the index is taken from pIndex->tnum.
2990 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2991 Table *pTab = pIndex->pTable; /* The table that is indexed */
2992 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2993 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
2994 int iSorter; /* Cursor opened by OpenSorter (if in use) */
2995 int addr1; /* Address of top of loop */
2996 int addr2; /* Address to jump to for next iteration */
2997 int tnum; /* Root page of index */
2998 int iPartIdxLabel; /* Jump to this label to skip a row */
2999 Vdbe *v; /* Generate code into this virtual machine */
3000 KeyInfo *pKey; /* KeyInfo for index */
3001 int regRecord; /* Register holding assembled index record */
3002 sqlite3 *db = pParse->db; /* The database connection */
3003 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3005 #ifndef SQLITE_OMIT_AUTHORIZATION
3006 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3007 db->aDb[iDb].zDbSName ) ){
3008 return;
3010 #endif
3012 /* Require a write-lock on the table to perform this operation */
3013 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3015 v = sqlite3GetVdbe(pParse);
3016 if( v==0 ) return;
3017 if( memRootPage>=0 ){
3018 tnum = memRootPage;
3019 }else{
3020 tnum = pIndex->tnum;
3022 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3023 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
3025 /* Open the sorter cursor if we are to use one. */
3026 iSorter = pParse->nTab++;
3027 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3028 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3030 /* Open the table. Loop through all rows of the table, inserting index
3031 ** records into the sorter. */
3032 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3033 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3034 regRecord = sqlite3GetTempReg(pParse);
3035 sqlite3MultiWrite(pParse);
3037 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3038 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3039 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3040 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3041 sqlite3VdbeJumpHere(v, addr1);
3042 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3043 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
3044 (char *)pKey, P4_KEYINFO);
3045 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3047 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3048 if( IsUniqueIndex(pIndex) ){
3049 int j2 = sqlite3VdbeGoto(v, 1);
3050 addr2 = sqlite3VdbeCurrentAddr(v);
3051 sqlite3VdbeVerifyAbortable(v, OE_Abort);
3052 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3053 pIndex->nKeyCol); VdbeCoverage(v);
3054 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3055 sqlite3VdbeJumpHere(v, j2);
3056 }else{
3057 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3058 ** abort. The exception is if one of the indexed expressions contains a
3059 ** user function that throws an exception when it is evaluated. But the
3060 ** overhead of adding a statement journal to a CREATE INDEX statement is
3061 ** very small (since most of the pages written do not contain content that
3062 ** needs to be restored if the statement aborts), so we call
3063 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3064 sqlite3MayAbort(pParse);
3065 addr2 = sqlite3VdbeCurrentAddr(v);
3067 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3068 if( !pIndex->bAscKeyBug ){
3069 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3070 ** faster by avoiding unnecessary seeks. But the optimization does
3071 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3072 ** with DESC primary keys, since those indexes have there keys in
3073 ** a different order from the main table.
3074 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3076 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3078 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3079 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3080 sqlite3ReleaseTempReg(pParse, regRecord);
3081 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3082 sqlite3VdbeJumpHere(v, addr1);
3084 sqlite3VdbeAddOp1(v, OP_Close, iTab);
3085 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3086 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3090 ** Allocate heap space to hold an Index object with nCol columns.
3092 ** Increase the allocation size to provide an extra nExtra bytes
3093 ** of 8-byte aligned space after the Index object and return a
3094 ** pointer to this extra space in *ppExtra.
3096 Index *sqlite3AllocateIndexObject(
3097 sqlite3 *db, /* Database connection */
3098 i16 nCol, /* Total number of columns in the index */
3099 int nExtra, /* Number of bytes of extra space to alloc */
3100 char **ppExtra /* Pointer to the "extra" space */
3102 Index *p; /* Allocated index object */
3103 int nByte; /* Bytes of space for Index object + arrays */
3105 nByte = ROUND8(sizeof(Index)) + /* Index structure */
3106 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
3107 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
3108 sizeof(i16)*nCol + /* Index.aiColumn */
3109 sizeof(u8)*nCol); /* Index.aSortOrder */
3110 p = sqlite3DbMallocZero(db, nByte + nExtra);
3111 if( p ){
3112 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3113 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3114 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3115 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
3116 p->aSortOrder = (u8*)pExtra;
3117 p->nColumn = nCol;
3118 p->nKeyCol = nCol - 1;
3119 *ppExtra = ((char*)p) + nByte;
3121 return p;
3125 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
3126 ** and pTblList is the name of the table that is to be indexed. Both will
3127 ** be NULL for a primary key or an index that is created to satisfy a
3128 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
3129 ** as the table to be indexed. pParse->pNewTable is a table that is
3130 ** currently being constructed by a CREATE TABLE statement.
3132 ** pList is a list of columns to be indexed. pList will be NULL if this
3133 ** is a primary key or unique-constraint on the most recent column added
3134 ** to the table currently under construction.
3136 void sqlite3CreateIndex(
3137 Parse *pParse, /* All information about this parse */
3138 Token *pName1, /* First part of index name. May be NULL */
3139 Token *pName2, /* Second part of index name. May be NULL */
3140 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3141 ExprList *pList, /* A list of columns to be indexed */
3142 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3143 Token *pStart, /* The CREATE token that begins this statement */
3144 Expr *pPIWhere, /* WHERE clause for partial indices */
3145 int sortOrder, /* Sort order of primary key when pList==NULL */
3146 int ifNotExist, /* Omit error if index already exists */
3147 u8 idxType /* The index type */
3149 Table *pTab = 0; /* Table to be indexed */
3150 Index *pIndex = 0; /* The index to be created */
3151 char *zName = 0; /* Name of the index */
3152 int nName; /* Number of characters in zName */
3153 int i, j;
3154 DbFixer sFix; /* For assigning database names to pTable */
3155 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
3156 sqlite3 *db = pParse->db;
3157 Db *pDb; /* The specific table containing the indexed database */
3158 int iDb; /* Index of the database that is being written */
3159 Token *pName = 0; /* Unqualified name of the index to create */
3160 struct ExprList_item *pListItem; /* For looping over pList */
3161 int nExtra = 0; /* Space allocated for zExtra[] */
3162 int nExtraCol; /* Number of extra columns needed */
3163 char *zExtra = 0; /* Extra space after the Index object */
3164 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
3166 if( db->mallocFailed || pParse->nErr>0 ){
3167 goto exit_create_index;
3169 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3170 goto exit_create_index;
3172 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3173 goto exit_create_index;
3177 ** Find the table that is to be indexed. Return early if not found.
3179 if( pTblName!=0 ){
3181 /* Use the two-part index name to determine the database
3182 ** to search for the table. 'Fix' the table name to this db
3183 ** before looking up the table.
3185 assert( pName1 && pName2 );
3186 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3187 if( iDb<0 ) goto exit_create_index;
3188 assert( pName && pName->z );
3190 #ifndef SQLITE_OMIT_TEMPDB
3191 /* If the index name was unqualified, check if the table
3192 ** is a temp table. If so, set the database to 1. Do not do this
3193 ** if initialising a database schema.
3195 if( !db->init.busy ){
3196 pTab = sqlite3SrcListLookup(pParse, pTblName);
3197 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3198 iDb = 1;
3201 #endif
3203 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3204 if( sqlite3FixSrcList(&sFix, pTblName) ){
3205 /* Because the parser constructs pTblName from a single identifier,
3206 ** sqlite3FixSrcList can never fail. */
3207 assert(0);
3209 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3210 assert( db->mallocFailed==0 || pTab==0 );
3211 if( pTab==0 ) goto exit_create_index;
3212 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3213 sqlite3ErrorMsg(pParse,
3214 "cannot create a TEMP index on non-TEMP table \"%s\"",
3215 pTab->zName);
3216 goto exit_create_index;
3218 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
3219 }else{
3220 assert( pName==0 );
3221 assert( pStart==0 );
3222 pTab = pParse->pNewTable;
3223 if( !pTab ) goto exit_create_index;
3224 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3226 pDb = &db->aDb[iDb];
3228 assert( pTab!=0 );
3229 assert( pParse->nErr==0 );
3230 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
3231 && db->init.busy==0
3232 && pTblName!=0
3233 #if SQLITE_USER_AUTHENTICATION
3234 && sqlite3UserAuthTable(pTab->zName)==0
3235 #endif
3236 #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
3237 && sqlite3StrICmp(&pTab->zName[7],"master")!=0
3238 #endif
3240 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
3241 goto exit_create_index;
3243 #ifndef SQLITE_OMIT_VIEW
3244 if( pTab->pSelect ){
3245 sqlite3ErrorMsg(pParse, "views may not be indexed");
3246 goto exit_create_index;
3248 #endif
3249 #ifndef SQLITE_OMIT_VIRTUALTABLE
3250 if( IsVirtual(pTab) ){
3251 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
3252 goto exit_create_index;
3254 #endif
3257 ** Find the name of the index. Make sure there is not already another
3258 ** index or table with the same name.
3260 ** Exception: If we are reading the names of permanent indices from the
3261 ** sqlite_master table (because some other process changed the schema) and
3262 ** one of the index names collides with the name of a temporary table or
3263 ** index, then we will continue to process this index.
3265 ** If pName==0 it means that we are
3266 ** dealing with a primary key or UNIQUE constraint. We have to invent our
3267 ** own name.
3269 if( pName ){
3270 zName = sqlite3NameFromToken(db, pName);
3271 if( zName==0 ) goto exit_create_index;
3272 assert( pName->z!=0 );
3273 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
3274 goto exit_create_index;
3276 if( !IN_RENAME_OBJECT ){
3277 if( !db->init.busy ){
3278 if( sqlite3FindTable(db, zName, 0)!=0 ){
3279 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3280 goto exit_create_index;
3283 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
3284 if( !ifNotExist ){
3285 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
3286 }else{
3287 assert( !db->init.busy );
3288 sqlite3CodeVerifySchema(pParse, iDb);
3290 goto exit_create_index;
3293 }else{
3294 int n;
3295 Index *pLoop;
3296 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
3297 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
3298 if( zName==0 ){
3299 goto exit_create_index;
3302 /* Automatic index names generated from within sqlite3_declare_vtab()
3303 ** must have names that are distinct from normal automatic index names.
3304 ** The following statement converts "sqlite3_autoindex..." into
3305 ** "sqlite3_butoindex..." in order to make the names distinct.
3306 ** The "vtab_err.test" test demonstrates the need of this statement. */
3307 if( IN_SPECIAL_PARSE ) zName[7]++;
3310 /* Check for authorization to create an index.
3312 #ifndef SQLITE_OMIT_AUTHORIZATION
3313 if( !IN_RENAME_OBJECT ){
3314 const char *zDb = pDb->zDbSName;
3315 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
3316 goto exit_create_index;
3318 i = SQLITE_CREATE_INDEX;
3319 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
3320 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
3321 goto exit_create_index;
3324 #endif
3326 /* If pList==0, it means this routine was called to make a primary
3327 ** key out of the last column added to the table under construction.
3328 ** So create a fake list to simulate this.
3330 if( pList==0 ){
3331 Token prevCol;
3332 Column *pCol = &pTab->aCol[pTab->nCol-1];
3333 pCol->colFlags |= COLFLAG_UNIQUE;
3334 sqlite3TokenInit(&prevCol, pCol->zName);
3335 pList = sqlite3ExprListAppend(pParse, 0,
3336 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
3337 if( pList==0 ) goto exit_create_index;
3338 assert( pList->nExpr==1 );
3339 sqlite3ExprListSetSortOrder(pList, sortOrder);
3340 }else{
3341 sqlite3ExprListCheckLength(pParse, pList, "index");
3342 if( pParse->nErr ) goto exit_create_index;
3345 /* Figure out how many bytes of space are required to store explicitly
3346 ** specified collation sequence names.
3348 for(i=0; i<pList->nExpr; i++){
3349 Expr *pExpr = pList->a[i].pExpr;
3350 assert( pExpr!=0 );
3351 if( pExpr->op==TK_COLLATE ){
3352 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
3357 ** Allocate the index structure.
3359 nName = sqlite3Strlen30(zName);
3360 nExtraCol = pPk ? pPk->nKeyCol : 1;
3361 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
3362 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
3363 nName + nExtra + 1, &zExtra);
3364 if( db->mallocFailed ){
3365 goto exit_create_index;
3367 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
3368 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
3369 pIndex->zName = zExtra;
3370 zExtra += nName + 1;
3371 memcpy(pIndex->zName, zName, nName+1);
3372 pIndex->pTable = pTab;
3373 pIndex->onError = (u8)onError;
3374 pIndex->uniqNotNull = onError!=OE_None;
3375 pIndex->idxType = idxType;
3376 pIndex->pSchema = db->aDb[iDb].pSchema;
3377 pIndex->nKeyCol = pList->nExpr;
3378 if( pPIWhere ){
3379 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3380 pIndex->pPartIdxWhere = pPIWhere;
3381 pPIWhere = 0;
3383 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3385 /* Check to see if we should honor DESC requests on index columns
3387 if( pDb->pSchema->file_format>=4 ){
3388 sortOrderMask = -1; /* Honor DESC */
3389 }else{
3390 sortOrderMask = 0; /* Ignore DESC */
3393 /* Analyze the list of expressions that form the terms of the index and
3394 ** report any errors. In the common case where the expression is exactly
3395 ** a table column, store that column in aiColumn[]. For general expressions,
3396 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
3398 ** TODO: Issue a warning if two or more columns of the index are identical.
3399 ** TODO: Issue a warning if the table primary key is used as part of the
3400 ** index key.
3402 pListItem = pList->a;
3403 if( IN_RENAME_OBJECT ){
3404 pIndex->aColExpr = pList;
3405 pList = 0;
3407 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
3408 Expr *pCExpr; /* The i-th index expression */
3409 int requestedSortOrder; /* ASC or DESC on the i-th expression */
3410 const char *zColl; /* Collation sequence name */
3412 sqlite3StringToId(pListItem->pExpr);
3413 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3414 if( pParse->nErr ) goto exit_create_index;
3415 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
3416 if( pCExpr->op!=TK_COLUMN ){
3417 if( pTab==pParse->pNewTable ){
3418 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3419 "UNIQUE constraints");
3420 goto exit_create_index;
3422 if( pIndex->aColExpr==0 ){
3423 pIndex->aColExpr = pList;
3424 pList = 0;
3426 j = XN_EXPR;
3427 pIndex->aiColumn[i] = XN_EXPR;
3428 pIndex->uniqNotNull = 0;
3429 }else{
3430 j = pCExpr->iColumn;
3431 assert( j<=0x7fff );
3432 if( j<0 ){
3433 j = pTab->iPKey;
3434 }else if( pTab->aCol[j].notNull==0 ){
3435 pIndex->uniqNotNull = 0;
3437 pIndex->aiColumn[i] = (i16)j;
3439 zColl = 0;
3440 if( pListItem->pExpr->op==TK_COLLATE ){
3441 int nColl;
3442 zColl = pListItem->pExpr->u.zToken;
3443 nColl = sqlite3Strlen30(zColl) + 1;
3444 assert( nExtra>=nColl );
3445 memcpy(zExtra, zColl, nColl);
3446 zColl = zExtra;
3447 zExtra += nColl;
3448 nExtra -= nColl;
3449 }else if( j>=0 ){
3450 zColl = pTab->aCol[j].zColl;
3452 if( !zColl ) zColl = sqlite3StrBINARY;
3453 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
3454 goto exit_create_index;
3456 pIndex->azColl[i] = zColl;
3457 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
3458 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3461 /* Append the table key to the end of the index. For WITHOUT ROWID
3462 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
3463 ** normal tables (when pPk==0) this will be the rowid.
3465 if( pPk ){
3466 for(j=0; j<pPk->nKeyCol; j++){
3467 int x = pPk->aiColumn[j];
3468 assert( x>=0 );
3469 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
3470 pIndex->nColumn--;
3471 }else{
3472 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
3473 pIndex->aiColumn[i] = x;
3474 pIndex->azColl[i] = pPk->azColl[j];
3475 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3476 i++;
3479 assert( i==pIndex->nColumn );
3480 }else{
3481 pIndex->aiColumn[i] = XN_ROWID;
3482 pIndex->azColl[i] = sqlite3StrBINARY;
3484 sqlite3DefaultRowEst(pIndex);
3485 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
3487 /* If this index contains every column of its table, then mark
3488 ** it as a covering index */
3489 assert( HasRowid(pTab)
3490 || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
3491 recomputeColumnsNotIndexed(pIndex);
3492 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
3493 pIndex->isCovering = 1;
3494 for(j=0; j<pTab->nCol; j++){
3495 if( j==pTab->iPKey ) continue;
3496 if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
3497 pIndex->isCovering = 0;
3498 break;
3502 if( pTab==pParse->pNewTable ){
3503 /* This routine has been called to create an automatic index as a
3504 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3505 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3506 ** i.e. one of:
3508 ** CREATE TABLE t(x PRIMARY KEY, y);
3509 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3511 ** Either way, check to see if the table already has such an index. If
3512 ** so, don't bother creating this one. This only applies to
3513 ** automatically created indices. Users can do as they wish with
3514 ** explicit indices.
3516 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3517 ** (and thus suppressing the second one) even if they have different
3518 ** sort orders.
3520 ** If there are different collating sequences or if the columns of
3521 ** the constraint occur in different orders, then the constraints are
3522 ** considered distinct and both result in separate indices.
3524 Index *pIdx;
3525 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3526 int k;
3527 assert( IsUniqueIndex(pIdx) );
3528 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
3529 assert( IsUniqueIndex(pIndex) );
3531 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3532 for(k=0; k<pIdx->nKeyCol; k++){
3533 const char *z1;
3534 const char *z2;
3535 assert( pIdx->aiColumn[k]>=0 );
3536 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
3537 z1 = pIdx->azColl[k];
3538 z2 = pIndex->azColl[k];
3539 if( sqlite3StrICmp(z1, z2) ) break;
3541 if( k==pIdx->nKeyCol ){
3542 if( pIdx->onError!=pIndex->onError ){
3543 /* This constraint creates the same index as a previous
3544 ** constraint specified somewhere in the CREATE TABLE statement.
3545 ** However the ON CONFLICT clauses are different. If both this
3546 ** constraint and the previous equivalent constraint have explicit
3547 ** ON CONFLICT clauses this is an error. Otherwise, use the
3548 ** explicitly specified behavior for the index.
3550 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3551 sqlite3ErrorMsg(pParse,
3552 "conflicting ON CONFLICT clauses specified", 0);
3554 if( pIdx->onError==OE_Default ){
3555 pIdx->onError = pIndex->onError;
3558 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
3559 if( IN_RENAME_OBJECT ){
3560 pIndex->pNext = pParse->pNewIndex;
3561 pParse->pNewIndex = pIndex;
3562 pIndex = 0;
3564 goto exit_create_index;
3569 if( !IN_RENAME_OBJECT ){
3571 /* Link the new Index structure to its table and to the other
3572 ** in-memory database structures.
3574 assert( pParse->nErr==0 );
3575 if( db->init.busy ){
3576 Index *p;
3577 assert( !IN_SPECIAL_PARSE );
3578 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
3579 if( pTblName!=0 ){
3580 pIndex->tnum = db->init.newTnum;
3581 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
3582 sqlite3ErrorMsg(pParse, "invalid rootpage");
3583 pParse->rc = SQLITE_CORRUPT_BKPT;
3584 goto exit_create_index;
3587 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
3588 pIndex->zName, pIndex);
3589 if( p ){
3590 assert( p==pIndex ); /* Malloc must have failed */
3591 sqlite3OomFault(db);
3592 goto exit_create_index;
3594 db->mDbFlags |= DBFLAG_SchemaChange;
3597 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3598 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3599 ** emit code to allocate the index rootpage on disk and make an entry for
3600 ** the index in the sqlite_master table and populate the index with
3601 ** content. But, do not do this if we are simply reading the sqlite_master
3602 ** table to parse the schema, or if this index is the PRIMARY KEY index
3603 ** of a WITHOUT ROWID table.
3605 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3606 ** or UNIQUE index in a CREATE TABLE statement. Since the table
3607 ** has just been created, it contains no data and the index initialization
3608 ** step can be skipped.
3610 else if( HasRowid(pTab) || pTblName!=0 ){
3611 Vdbe *v;
3612 char *zStmt;
3613 int iMem = ++pParse->nMem;
3615 v = sqlite3GetVdbe(pParse);
3616 if( v==0 ) goto exit_create_index;
3618 sqlite3BeginWriteOperation(pParse, 1, iDb);
3620 /* Create the rootpage for the index using CreateIndex. But before
3621 ** doing so, code a Noop instruction and store its address in
3622 ** Index.tnum. This is required in case this index is actually a
3623 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3624 ** that case the convertToWithoutRowidTable() routine will replace
3625 ** the Noop with a Goto to jump over the VDBE code generated below. */
3626 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
3627 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
3629 /* Gather the complete text of the CREATE INDEX statement into
3630 ** the zStmt variable
3632 if( pStart ){
3633 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
3634 if( pName->z[n-1]==';' ) n--;
3635 /* A named index with an explicit CREATE INDEX statement */
3636 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
3637 onError==OE_None ? "" : " UNIQUE", n, pName->z);
3638 }else{
3639 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3640 /* zStmt = sqlite3MPrintf(""); */
3641 zStmt = 0;
3644 /* Add an entry in sqlite_master for this index
3646 sqlite3NestedParse(pParse,
3647 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3648 db->aDb[iDb].zDbSName, MASTER_NAME,
3649 pIndex->zName,
3650 pTab->zName,
3651 iMem,
3652 zStmt
3654 sqlite3DbFree(db, zStmt);
3656 /* Fill the index with data and reparse the schema. Code an OP_Expire
3657 ** to invalidate all pre-compiled statements.
3659 if( pTblName ){
3660 sqlite3RefillIndex(pParse, pIndex, iMem);
3661 sqlite3ChangeCookie(pParse, iDb);
3662 sqlite3VdbeAddParseSchemaOp(v, iDb,
3663 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
3664 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
3667 sqlite3VdbeJumpHere(v, pIndex->tnum);
3671 /* When adding an index to the list of indices for a table, make
3672 ** sure all indices labeled OE_Replace come after all those labeled
3673 ** OE_Ignore. This is necessary for the correct constraint check
3674 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3675 ** UPDATE and INSERT statements.
3677 if( db->init.busy || pTblName==0 ){
3678 if( onError!=OE_Replace || pTab->pIndex==0
3679 || pTab->pIndex->onError==OE_Replace){
3680 pIndex->pNext = pTab->pIndex;
3681 pTab->pIndex = pIndex;
3682 }else{
3683 Index *pOther = pTab->pIndex;
3684 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3685 pOther = pOther->pNext;
3687 pIndex->pNext = pOther->pNext;
3688 pOther->pNext = pIndex;
3690 pIndex = 0;
3692 else if( IN_RENAME_OBJECT ){
3693 assert( pParse->pNewIndex==0 );
3694 pParse->pNewIndex = pIndex;
3695 pIndex = 0;
3698 /* Clean up before exiting */
3699 exit_create_index:
3700 if( pIndex ) sqlite3FreeIndex(db, pIndex);
3701 sqlite3ExprDelete(db, pPIWhere);
3702 sqlite3ExprListDelete(db, pList);
3703 sqlite3SrcListDelete(db, pTblName);
3704 sqlite3DbFree(db, zName);
3708 ** Fill the Index.aiRowEst[] array with default information - information
3709 ** to be used when we have not run the ANALYZE command.
3711 ** aiRowEst[0] is supposed to contain the number of elements in the index.
3712 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3713 ** number of rows in the table that match any particular value of the
3714 ** first column of the index. aiRowEst[2] is an estimate of the number
3715 ** of rows that match any particular combination of the first 2 columns
3716 ** of the index. And so forth. It must always be the case that
3718 ** aiRowEst[N]<=aiRowEst[N-1]
3719 ** aiRowEst[N]>=1
3721 ** Apart from that, we have little to go on besides intuition as to
3722 ** how aiRowEst[] should be initialized. The numbers generated here
3723 ** are based on typical values found in actual indices.
3725 void sqlite3DefaultRowEst(Index *pIdx){
3726 /* 10, 9, 8, 7, 6 */
3727 LogEst aVal[] = { 33, 32, 30, 28, 26 };
3728 LogEst *a = pIdx->aiRowLogEst;
3729 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
3730 int i;
3732 /* Indexes with default row estimates should not have stat1 data */
3733 assert( !pIdx->hasStat1 );
3735 /* Set the first entry (number of rows in the index) to the estimated
3736 ** number of rows in the table, or half the number of rows in the table
3737 ** for a partial index. But do not let the estimate drop below 10. */
3738 a[0] = pIdx->pTable->nRowLogEst;
3739 if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
3740 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3742 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3743 ** 6 and each subsequent value (if any) is 5. */
3744 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
3745 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3746 a[i] = 23; assert( 23==sqlite3LogEst(5) );
3749 assert( 0==sqlite3LogEst(1) );
3750 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
3754 ** This routine will drop an existing named index. This routine
3755 ** implements the DROP INDEX statement.
3757 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
3758 Index *pIndex;
3759 Vdbe *v;
3760 sqlite3 *db = pParse->db;
3761 int iDb;
3763 assert( pParse->nErr==0 ); /* Never called with prior errors */
3764 if( db->mallocFailed ){
3765 goto exit_drop_index;
3767 assert( pName->nSrc==1 );
3768 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3769 goto exit_drop_index;
3771 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
3772 if( pIndex==0 ){
3773 if( !ifExists ){
3774 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
3775 }else{
3776 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3778 pParse->checkSchema = 1;
3779 goto exit_drop_index;
3781 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
3782 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
3783 "or PRIMARY KEY constraint cannot be dropped", 0);
3784 goto exit_drop_index;
3786 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3787 #ifndef SQLITE_OMIT_AUTHORIZATION
3789 int code = SQLITE_DROP_INDEX;
3790 Table *pTab = pIndex->pTable;
3791 const char *zDb = db->aDb[iDb].zDbSName;
3792 const char *zTab = SCHEMA_TABLE(iDb);
3793 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
3794 goto exit_drop_index;
3796 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
3797 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
3798 goto exit_drop_index;
3801 #endif
3803 /* Generate code to remove the index and from the master table */
3804 v = sqlite3GetVdbe(pParse);
3805 if( v ){
3806 sqlite3BeginWriteOperation(pParse, 1, iDb);
3807 sqlite3NestedParse(pParse,
3808 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3809 db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
3811 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
3812 sqlite3ChangeCookie(pParse, iDb);
3813 destroyRootPage(pParse, pIndex->tnum, iDb);
3814 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
3817 exit_drop_index:
3818 sqlite3SrcListDelete(db, pName);
3822 ** pArray is a pointer to an array of objects. Each object in the
3823 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3824 ** to extend the array so that there is space for a new object at the end.
3826 ** When this function is called, *pnEntry contains the current size of
3827 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3828 ** in total).
3830 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3831 ** space allocated for the new object is zeroed, *pnEntry updated to
3832 ** reflect the new size of the array and a pointer to the new allocation
3833 ** returned. *pIdx is set to the index of the new array entry in this case.
3835 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3836 ** unchanged and a copy of pArray returned.
3838 void *sqlite3ArrayAllocate(
3839 sqlite3 *db, /* Connection to notify of malloc failures */
3840 void *pArray, /* Array of objects. Might be reallocated */
3841 int szEntry, /* Size of each object in the array */
3842 int *pnEntry, /* Number of objects currently in use */
3843 int *pIdx /* Write the index of a new slot here */
3845 char *z;
3846 sqlite3_int64 n = *pIdx = *pnEntry;
3847 if( (n & (n-1))==0 ){
3848 sqlite3_int64 sz = (n==0) ? 1 : 2*n;
3849 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
3850 if( pNew==0 ){
3851 *pIdx = -1;
3852 return pArray;
3854 pArray = pNew;
3856 z = (char*)pArray;
3857 memset(&z[n * szEntry], 0, szEntry);
3858 ++*pnEntry;
3859 return pArray;
3863 ** Append a new element to the given IdList. Create a new IdList if
3864 ** need be.
3866 ** A new IdList is returned, or NULL if malloc() fails.
3868 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
3869 sqlite3 *db = pParse->db;
3870 int i;
3871 if( pList==0 ){
3872 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3873 if( pList==0 ) return 0;
3875 pList->a = sqlite3ArrayAllocate(
3877 pList->a,
3878 sizeof(pList->a[0]),
3879 &pList->nId,
3882 if( i<0 ){
3883 sqlite3IdListDelete(db, pList);
3884 return 0;
3886 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3887 if( IN_RENAME_OBJECT && pList->a[i].zName ){
3888 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
3890 return pList;
3894 ** Delete an IdList.
3896 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
3897 int i;
3898 if( pList==0 ) return;
3899 for(i=0; i<pList->nId; i++){
3900 sqlite3DbFree(db, pList->a[i].zName);
3902 sqlite3DbFree(db, pList->a);
3903 sqlite3DbFreeNN(db, pList);
3907 ** Return the index in pList of the identifier named zId. Return -1
3908 ** if not found.
3910 int sqlite3IdListIndex(IdList *pList, const char *zName){
3911 int i;
3912 if( pList==0 ) return -1;
3913 for(i=0; i<pList->nId; i++){
3914 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3916 return -1;
3920 ** Maximum size of a SrcList object.
3921 ** The SrcList object is used to represent the FROM clause of a
3922 ** SELECT statement, and the query planner cannot deal with more
3923 ** than 64 tables in a join. So any value larger than 64 here
3924 ** is sufficient for most uses. Smaller values, like say 10, are
3925 ** appropriate for small and memory-limited applications.
3927 #ifndef SQLITE_MAX_SRCLIST
3928 # define SQLITE_MAX_SRCLIST 200
3929 #endif
3932 ** Expand the space allocated for the given SrcList object by
3933 ** creating nExtra new slots beginning at iStart. iStart is zero based.
3934 ** New slots are zeroed.
3936 ** For example, suppose a SrcList initially contains two entries: A,B.
3937 ** To append 3 new entries onto the end, do this:
3939 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3941 ** After the call above it would contain: A, B, nil, nil, nil.
3942 ** If the iStart argument had been 1 instead of 2, then the result
3943 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
3944 ** the iStart value would be 0. The result then would
3945 ** be: nil, nil, nil, A, B.
3947 ** If a memory allocation fails or the SrcList becomes too large, leave
3948 ** the original SrcList unchanged, return NULL, and leave an error message
3949 ** in pParse.
3951 SrcList *sqlite3SrcListEnlarge(
3952 Parse *pParse, /* Parsing context into which errors are reported */
3953 SrcList *pSrc, /* The SrcList to be enlarged */
3954 int nExtra, /* Number of new slots to add to pSrc->a[] */
3955 int iStart /* Index in pSrc->a[] of first new slot */
3957 int i;
3959 /* Sanity checking on calling parameters */
3960 assert( iStart>=0 );
3961 assert( nExtra>=1 );
3962 assert( pSrc!=0 );
3963 assert( iStart<=pSrc->nSrc );
3965 /* Allocate additional space if needed */
3966 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
3967 SrcList *pNew;
3968 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
3969 sqlite3 *db = pParse->db;
3971 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
3972 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
3973 SQLITE_MAX_SRCLIST);
3974 return 0;
3976 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
3977 pNew = sqlite3DbRealloc(db, pSrc,
3978 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3979 if( pNew==0 ){
3980 assert( db->mallocFailed );
3981 return 0;
3983 pSrc = pNew;
3984 pSrc->nAlloc = nAlloc;
3987 /* Move existing slots that come after the newly inserted slots
3988 ** out of the way */
3989 for(i=pSrc->nSrc-1; i>=iStart; i--){
3990 pSrc->a[i+nExtra] = pSrc->a[i];
3992 pSrc->nSrc += nExtra;
3994 /* Zero the newly allocated slots */
3995 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3996 for(i=iStart; i<iStart+nExtra; i++){
3997 pSrc->a[i].iCursor = -1;
4000 /* Return a pointer to the enlarged SrcList */
4001 return pSrc;
4006 ** Append a new table name to the given SrcList. Create a new SrcList if
4007 ** need be. A new entry is created in the SrcList even if pTable is NULL.
4009 ** A SrcList is returned, or NULL if there is an OOM error or if the
4010 ** SrcList grows to large. The returned
4011 ** SrcList might be the same as the SrcList that was input or it might be
4012 ** a new one. If an OOM error does occurs, then the prior value of pList
4013 ** that is input to this routine is automatically freed.
4015 ** If pDatabase is not null, it means that the table has an optional
4016 ** database name prefix. Like this: "database.table". The pDatabase
4017 ** points to the table name and the pTable points to the database name.
4018 ** The SrcList.a[].zName field is filled with the table name which might
4019 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4020 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4021 ** or with NULL if no database is specified.
4023 ** In other words, if call like this:
4025 ** sqlite3SrcListAppend(D,A,B,0);
4027 ** Then B is a table name and the database name is unspecified. If called
4028 ** like this:
4030 ** sqlite3SrcListAppend(D,A,B,C);
4032 ** Then C is the table name and B is the database name. If C is defined
4033 ** then so is B. In other words, we never have a case where:
4035 ** sqlite3SrcListAppend(D,A,0,C);
4037 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
4038 ** before being added to the SrcList.
4040 SrcList *sqlite3SrcListAppend(
4041 Parse *pParse, /* Parsing context, in which errors are reported */
4042 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
4043 Token *pTable, /* Table to append */
4044 Token *pDatabase /* Database of the table */
4046 struct SrcList_item *pItem;
4047 sqlite3 *db;
4048 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
4049 assert( pParse!=0 );
4050 assert( pParse->db!=0 );
4051 db = pParse->db;
4052 if( pList==0 ){
4053 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4054 if( pList==0 ) return 0;
4055 pList->nAlloc = 1;
4056 pList->nSrc = 1;
4057 memset(&pList->a[0], 0, sizeof(pList->a[0]));
4058 pList->a[0].iCursor = -1;
4059 }else{
4060 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4061 if( pNew==0 ){
4062 sqlite3SrcListDelete(db, pList);
4063 return 0;
4064 }else{
4065 pList = pNew;
4068 pItem = &pList->a[pList->nSrc-1];
4069 if( pDatabase && pDatabase->z==0 ){
4070 pDatabase = 0;
4072 if( pDatabase ){
4073 pItem->zName = sqlite3NameFromToken(db, pDatabase);
4074 pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4075 }else{
4076 pItem->zName = sqlite3NameFromToken(db, pTable);
4077 pItem->zDatabase = 0;
4079 return pList;
4083 ** Assign VdbeCursor index numbers to all tables in a SrcList
4085 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4086 int i;
4087 struct SrcList_item *pItem;
4088 assert(pList || pParse->db->mallocFailed );
4089 if( pList ){
4090 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4091 if( pItem->iCursor>=0 ) break;
4092 pItem->iCursor = pParse->nTab++;
4093 if( pItem->pSelect ){
4094 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4101 ** Delete an entire SrcList including all its substructure.
4103 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4104 int i;
4105 struct SrcList_item *pItem;
4106 if( pList==0 ) return;
4107 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4108 sqlite3DbFree(db, pItem->zDatabase);
4109 sqlite3DbFree(db, pItem->zName);
4110 sqlite3DbFree(db, pItem->zAlias);
4111 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4112 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4113 sqlite3DeleteTable(db, pItem->pTab);
4114 sqlite3SelectDelete(db, pItem->pSelect);
4115 sqlite3ExprDelete(db, pItem->pOn);
4116 sqlite3IdListDelete(db, pItem->pUsing);
4118 sqlite3DbFreeNN(db, pList);
4122 ** This routine is called by the parser to add a new term to the
4123 ** end of a growing FROM clause. The "p" parameter is the part of
4124 ** the FROM clause that has already been constructed. "p" is NULL
4125 ** if this is the first term of the FROM clause. pTable and pDatabase
4126 ** are the name of the table and database named in the FROM clause term.
4127 ** pDatabase is NULL if the database name qualifier is missing - the
4128 ** usual case. If the term has an alias, then pAlias points to the
4129 ** alias token. If the term is a subquery, then pSubquery is the
4130 ** SELECT statement that the subquery encodes. The pTable and
4131 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
4132 ** parameters are the content of the ON and USING clauses.
4134 ** Return a new SrcList which encodes is the FROM with the new
4135 ** term added.
4137 SrcList *sqlite3SrcListAppendFromTerm(
4138 Parse *pParse, /* Parsing context */
4139 SrcList *p, /* The left part of the FROM clause already seen */
4140 Token *pTable, /* Name of the table to add to the FROM clause */
4141 Token *pDatabase, /* Name of the database containing pTable */
4142 Token *pAlias, /* The right-hand side of the AS subexpression */
4143 Select *pSubquery, /* A subquery used in place of a table name */
4144 Expr *pOn, /* The ON clause of a join */
4145 IdList *pUsing /* The USING clause of a join */
4147 struct SrcList_item *pItem;
4148 sqlite3 *db = pParse->db;
4149 if( !p && (pOn || pUsing) ){
4150 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4151 (pOn ? "ON" : "USING")
4153 goto append_from_error;
4155 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4156 if( p==0 ){
4157 goto append_from_error;
4159 assert( p->nSrc>0 );
4160 pItem = &p->a[p->nSrc-1];
4161 assert( (pTable==0)==(pDatabase==0) );
4162 assert( pItem->zName==0 || pDatabase!=0 );
4163 if( IN_RENAME_OBJECT && pItem->zName ){
4164 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4165 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4167 assert( pAlias!=0 );
4168 if( pAlias->n ){
4169 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4171 pItem->pSelect = pSubquery;
4172 pItem->pOn = pOn;
4173 pItem->pUsing = pUsing;
4174 return p;
4176 append_from_error:
4177 assert( p==0 );
4178 sqlite3ExprDelete(db, pOn);
4179 sqlite3IdListDelete(db, pUsing);
4180 sqlite3SelectDelete(db, pSubquery);
4181 return 0;
4185 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
4186 ** element of the source-list passed as the second argument.
4188 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
4189 assert( pIndexedBy!=0 );
4190 if( p && pIndexedBy->n>0 ){
4191 struct SrcList_item *pItem;
4192 assert( p->nSrc>0 );
4193 pItem = &p->a[p->nSrc-1];
4194 assert( pItem->fg.notIndexed==0 );
4195 assert( pItem->fg.isIndexedBy==0 );
4196 assert( pItem->fg.isTabFunc==0 );
4197 if( pIndexedBy->n==1 && !pIndexedBy->z ){
4198 /* A "NOT INDEXED" clause was supplied. See parse.y
4199 ** construct "indexed_opt" for details. */
4200 pItem->fg.notIndexed = 1;
4201 }else{
4202 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
4203 pItem->fg.isIndexedBy = 1;
4209 ** Add the list of function arguments to the SrcList entry for a
4210 ** table-valued-function.
4212 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
4213 if( p ){
4214 struct SrcList_item *pItem = &p->a[p->nSrc-1];
4215 assert( pItem->fg.notIndexed==0 );
4216 assert( pItem->fg.isIndexedBy==0 );
4217 assert( pItem->fg.isTabFunc==0 );
4218 pItem->u1.pFuncArg = pList;
4219 pItem->fg.isTabFunc = 1;
4220 }else{
4221 sqlite3ExprListDelete(pParse->db, pList);
4226 ** When building up a FROM clause in the parser, the join operator
4227 ** is initially attached to the left operand. But the code generator
4228 ** expects the join operator to be on the right operand. This routine
4229 ** Shifts all join operators from left to right for an entire FROM
4230 ** clause.
4232 ** Example: Suppose the join is like this:
4234 ** A natural cross join B
4236 ** The operator is "natural cross join". The A and B operands are stored
4237 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
4238 ** operator with A. This routine shifts that operator over to B.
4240 void sqlite3SrcListShiftJoinType(SrcList *p){
4241 if( p ){
4242 int i;
4243 for(i=p->nSrc-1; i>0; i--){
4244 p->a[i].fg.jointype = p->a[i-1].fg.jointype;
4246 p->a[0].fg.jointype = 0;
4251 ** Generate VDBE code for a BEGIN statement.
4253 void sqlite3BeginTransaction(Parse *pParse, int type){
4254 sqlite3 *db;
4255 Vdbe *v;
4256 int i;
4258 assert( pParse!=0 );
4259 db = pParse->db;
4260 assert( db!=0 );
4261 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
4262 return;
4264 v = sqlite3GetVdbe(pParse);
4265 if( !v ) return;
4266 if( type!=TK_DEFERRED ){
4267 for(i=0; i<db->nDb; i++){
4268 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
4269 sqlite3VdbeUsesBtree(v, i);
4272 sqlite3VdbeAddOp0(v, OP_AutoCommit);
4276 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
4277 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
4278 ** code is generated for a COMMIT.
4280 void sqlite3EndTransaction(Parse *pParse, int eType){
4281 Vdbe *v;
4282 int isRollback;
4284 assert( pParse!=0 );
4285 assert( pParse->db!=0 );
4286 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
4287 isRollback = eType==TK_ROLLBACK;
4288 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
4289 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
4290 return;
4292 v = sqlite3GetVdbe(pParse);
4293 if( v ){
4294 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
4299 ** This function is called by the parser when it parses a command to create,
4300 ** release or rollback an SQL savepoint.
4302 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
4303 char *zName = sqlite3NameFromToken(pParse->db, pName);
4304 if( zName ){
4305 Vdbe *v = sqlite3GetVdbe(pParse);
4306 #ifndef SQLITE_OMIT_AUTHORIZATION
4307 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
4308 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
4309 #endif
4310 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
4311 sqlite3DbFree(pParse->db, zName);
4312 return;
4314 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
4319 ** Make sure the TEMP database is open and available for use. Return
4320 ** the number of errors. Leave any error messages in the pParse structure.
4322 int sqlite3OpenTempDatabase(Parse *pParse){
4323 sqlite3 *db = pParse->db;
4324 if( db->aDb[1].pBt==0 && !pParse->explain ){
4325 int rc;
4326 Btree *pBt;
4327 static const int flags =
4328 SQLITE_OPEN_READWRITE |
4329 SQLITE_OPEN_CREATE |
4330 SQLITE_OPEN_EXCLUSIVE |
4331 SQLITE_OPEN_DELETEONCLOSE |
4332 SQLITE_OPEN_TEMP_DB;
4334 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
4335 if( rc!=SQLITE_OK ){
4336 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4337 "file for storing temporary tables");
4338 pParse->rc = rc;
4339 return 1;
4341 db->aDb[1].pBt = pBt;
4342 assert( db->aDb[1].pSchema );
4343 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
4344 sqlite3OomFault(db);
4345 return 1;
4348 return 0;
4352 ** Record the fact that the schema cookie will need to be verified
4353 ** for database iDb. The code to actually verify the schema cookie
4354 ** will occur at the end of the top-level VDBE and will be generated
4355 ** later, by sqlite3FinishCoding().
4357 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
4358 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4360 assert( iDb>=0 && iDb<pParse->db->nDb );
4361 assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
4362 assert( iDb<SQLITE_MAX_ATTACHED+2 );
4363 assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
4364 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4365 DbMaskSet(pToplevel->cookieMask, iDb);
4366 if( !OMIT_TEMPDB && iDb==1 ){
4367 sqlite3OpenTempDatabase(pToplevel);
4373 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4374 ** attached database. Otherwise, invoke it for the database named zDb only.
4376 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4377 sqlite3 *db = pParse->db;
4378 int i;
4379 for(i=0; i<db->nDb; i++){
4380 Db *pDb = &db->aDb[i];
4381 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
4382 sqlite3CodeVerifySchema(pParse, i);
4388 ** Generate VDBE code that prepares for doing an operation that
4389 ** might change the database.
4391 ** This routine starts a new transaction if we are not already within
4392 ** a transaction. If we are already within a transaction, then a checkpoint
4393 ** is set if the setStatement parameter is true. A checkpoint should
4394 ** be set for operations that might fail (due to a constraint) part of
4395 ** the way through and which will need to undo some writes without having to
4396 ** rollback the whole transaction. For operations where all constraints
4397 ** can be checked before any changes are made to the database, it is never
4398 ** necessary to undo a write and the checkpoint should not be set.
4400 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
4401 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4402 sqlite3CodeVerifySchema(pParse, iDb);
4403 DbMaskSet(pToplevel->writeMask, iDb);
4404 pToplevel->isMultiWrite |= setStatement;
4408 ** Indicate that the statement currently under construction might write
4409 ** more than one entry (example: deleting one row then inserting another,
4410 ** inserting multiple rows in a table, or inserting a row and index entries.)
4411 ** If an abort occurs after some of these writes have completed, then it will
4412 ** be necessary to undo the completed writes.
4414 void sqlite3MultiWrite(Parse *pParse){
4415 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4416 pToplevel->isMultiWrite = 1;
4420 ** The code generator calls this routine if is discovers that it is
4421 ** possible to abort a statement prior to completion. In order to
4422 ** perform this abort without corrupting the database, we need to make
4423 ** sure that the statement is protected by a statement transaction.
4425 ** Technically, we only need to set the mayAbort flag if the
4426 ** isMultiWrite flag was previously set. There is a time dependency
4427 ** such that the abort must occur after the multiwrite. This makes
4428 ** some statements involving the REPLACE conflict resolution algorithm
4429 ** go a little faster. But taking advantage of this time dependency
4430 ** makes it more difficult to prove that the code is correct (in
4431 ** particular, it prevents us from writing an effective
4432 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
4433 ** to take the safe route and skip the optimization.
4435 void sqlite3MayAbort(Parse *pParse){
4436 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4437 pToplevel->mayAbort = 1;
4441 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4442 ** error. The onError parameter determines which (if any) of the statement
4443 ** and/or current transaction is rolled back.
4445 void sqlite3HaltConstraint(
4446 Parse *pParse, /* Parsing context */
4447 int errCode, /* extended error code */
4448 int onError, /* Constraint type */
4449 char *p4, /* Error message */
4450 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4451 u8 p5Errmsg /* P5_ErrMsg type */
4453 Vdbe *v = sqlite3GetVdbe(pParse);
4454 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
4455 if( onError==OE_Abort ){
4456 sqlite3MayAbort(pParse);
4458 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
4459 sqlite3VdbeChangeP5(v, p5Errmsg);
4463 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4465 void sqlite3UniqueConstraint(
4466 Parse *pParse, /* Parsing context */
4467 int onError, /* Constraint type */
4468 Index *pIdx /* The index that triggers the constraint */
4470 char *zErr;
4471 int j;
4472 StrAccum errMsg;
4473 Table *pTab = pIdx->pTable;
4475 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
4476 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
4477 if( pIdx->aColExpr ){
4478 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
4479 }else{
4480 for(j=0; j<pIdx->nKeyCol; j++){
4481 char *zCol;
4482 assert( pIdx->aiColumn[j]>=0 );
4483 zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4484 if( j ) sqlite3_str_append(&errMsg, ", ", 2);
4485 sqlite3_str_appendall(&errMsg, pTab->zName);
4486 sqlite3_str_append(&errMsg, ".", 1);
4487 sqlite3_str_appendall(&errMsg, zCol);
4490 zErr = sqlite3StrAccumFinish(&errMsg);
4491 sqlite3HaltConstraint(pParse,
4492 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4493 : SQLITE_CONSTRAINT_UNIQUE,
4494 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
4499 ** Code an OP_Halt due to non-unique rowid.
4501 void sqlite3RowidConstraint(
4502 Parse *pParse, /* Parsing context */
4503 int onError, /* Conflict resolution algorithm */
4504 Table *pTab /* The table with the non-unique rowid */
4506 char *zMsg;
4507 int rc;
4508 if( pTab->iPKey>=0 ){
4509 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4510 pTab->aCol[pTab->iPKey].zName);
4511 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4512 }else{
4513 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4514 rc = SQLITE_CONSTRAINT_ROWID;
4516 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4517 P5_ConstraintUnique);
4521 ** Check to see if pIndex uses the collating sequence pColl. Return
4522 ** true if it does and false if it does not.
4524 #ifndef SQLITE_OMIT_REINDEX
4525 static int collationMatch(const char *zColl, Index *pIndex){
4526 int i;
4527 assert( zColl!=0 );
4528 for(i=0; i<pIndex->nColumn; i++){
4529 const char *z = pIndex->azColl[i];
4530 assert( z!=0 || pIndex->aiColumn[i]<0 );
4531 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
4532 return 1;
4535 return 0;
4537 #endif
4540 ** Recompute all indices of pTab that use the collating sequence pColl.
4541 ** If pColl==0 then recompute all indices of pTab.
4543 #ifndef SQLITE_OMIT_REINDEX
4544 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
4545 if( !IsVirtual(pTab) ){
4546 Index *pIndex; /* An index associated with pTab */
4548 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
4549 if( zColl==0 || collationMatch(zColl, pIndex) ){
4550 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4551 sqlite3BeginWriteOperation(pParse, 0, iDb);
4552 sqlite3RefillIndex(pParse, pIndex, -1);
4557 #endif
4560 ** Recompute all indices of all tables in all databases where the
4561 ** indices use the collating sequence pColl. If pColl==0 then recompute
4562 ** all indices everywhere.
4564 #ifndef SQLITE_OMIT_REINDEX
4565 static void reindexDatabases(Parse *pParse, char const *zColl){
4566 Db *pDb; /* A single database */
4567 int iDb; /* The database index number */
4568 sqlite3 *db = pParse->db; /* The database connection */
4569 HashElem *k; /* For looping over tables in pDb */
4570 Table *pTab; /* A table in the database */
4572 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
4573 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
4574 assert( pDb!=0 );
4575 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
4576 pTab = (Table*)sqliteHashData(k);
4577 reindexTable(pParse, pTab, zColl);
4581 #endif
4584 ** Generate code for the REINDEX command.
4586 ** REINDEX -- 1
4587 ** REINDEX <collation> -- 2
4588 ** REINDEX ?<database>.?<tablename> -- 3
4589 ** REINDEX ?<database>.?<indexname> -- 4
4591 ** Form 1 causes all indices in all attached databases to be rebuilt.
4592 ** Form 2 rebuilds all indices in all databases that use the named
4593 ** collating function. Forms 3 and 4 rebuild the named index or all
4594 ** indices associated with the named table.
4596 #ifndef SQLITE_OMIT_REINDEX
4597 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4598 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4599 char *z; /* Name of a table or index */
4600 const char *zDb; /* Name of the database */
4601 Table *pTab; /* A table in the database */
4602 Index *pIndex; /* An index associated with pTab */
4603 int iDb; /* The database index number */
4604 sqlite3 *db = pParse->db; /* The database connection */
4605 Token *pObjName; /* Name of the table or index to be reindexed */
4607 /* Read the database schema. If an error occurs, leave an error message
4608 ** and code in pParse and return NULL. */
4609 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4610 return;
4613 if( pName1==0 ){
4614 reindexDatabases(pParse, 0);
4615 return;
4616 }else if( NEVER(pName2==0) || pName2->z==0 ){
4617 char *zColl;
4618 assert( pName1->z );
4619 zColl = sqlite3NameFromToken(pParse->db, pName1);
4620 if( !zColl ) return;
4621 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
4622 if( pColl ){
4623 reindexDatabases(pParse, zColl);
4624 sqlite3DbFree(db, zColl);
4625 return;
4627 sqlite3DbFree(db, zColl);
4629 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4630 if( iDb<0 ) return;
4631 z = sqlite3NameFromToken(db, pObjName);
4632 if( z==0 ) return;
4633 zDb = db->aDb[iDb].zDbSName;
4634 pTab = sqlite3FindTable(db, z, zDb);
4635 if( pTab ){
4636 reindexTable(pParse, pTab, 0);
4637 sqlite3DbFree(db, z);
4638 return;
4640 pIndex = sqlite3FindIndex(db, z, zDb);
4641 sqlite3DbFree(db, z);
4642 if( pIndex ){
4643 sqlite3BeginWriteOperation(pParse, 0, iDb);
4644 sqlite3RefillIndex(pParse, pIndex, -1);
4645 return;
4647 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4649 #endif
4652 ** Return a KeyInfo structure that is appropriate for the given Index.
4654 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4655 ** when it has finished using it.
4657 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
4658 int i;
4659 int nCol = pIdx->nColumn;
4660 int nKey = pIdx->nKeyCol;
4661 KeyInfo *pKey;
4662 if( pParse->nErr ) return 0;
4663 if( pIdx->uniqNotNull ){
4664 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4665 }else{
4666 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4668 if( pKey ){
4669 assert( sqlite3KeyInfoIsWriteable(pKey) );
4670 for(i=0; i<nCol; i++){
4671 const char *zColl = pIdx->azColl[i];
4672 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
4673 sqlite3LocateCollSeq(pParse, zColl);
4674 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4676 if( pParse->nErr ){
4677 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
4678 if( pIdx->bNoQuery==0 ){
4679 /* Deactivate the index because it contains an unknown collating
4680 ** sequence. The only way to reactive the index is to reload the
4681 ** schema. Adding the missing collating sequence later does not
4682 ** reactive the index. The application had the chance to register
4683 ** the missing index using the collation-needed callback. For
4684 ** simplicity, SQLite will not give the application a second chance.
4686 pIdx->bNoQuery = 1;
4687 pParse->rc = SQLITE_ERROR_RETRY;
4689 sqlite3KeyInfoUnref(pKey);
4690 pKey = 0;
4693 return pKey;
4696 #ifndef SQLITE_OMIT_CTE
4698 ** This routine is invoked once per CTE by the parser while parsing a
4699 ** WITH clause.
4701 With *sqlite3WithAdd(
4702 Parse *pParse, /* Parsing context */
4703 With *pWith, /* Existing WITH clause, or NULL */
4704 Token *pName, /* Name of the common-table */
4705 ExprList *pArglist, /* Optional column name list for the table */
4706 Select *pQuery /* Query used to initialize the table */
4708 sqlite3 *db = pParse->db;
4709 With *pNew;
4710 char *zName;
4712 /* Check that the CTE name is unique within this WITH clause. If
4713 ** not, store an error in the Parse structure. */
4714 zName = sqlite3NameFromToken(pParse->db, pName);
4715 if( zName && pWith ){
4716 int i;
4717 for(i=0; i<pWith->nCte; i++){
4718 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
4719 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
4724 if( pWith ){
4725 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4726 pNew = sqlite3DbRealloc(db, pWith, nByte);
4727 }else{
4728 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4730 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
4732 if( db->mallocFailed ){
4733 sqlite3ExprListDelete(db, pArglist);
4734 sqlite3SelectDelete(db, pQuery);
4735 sqlite3DbFree(db, zName);
4736 pNew = pWith;
4737 }else{
4738 pNew->a[pNew->nCte].pSelect = pQuery;
4739 pNew->a[pNew->nCte].pCols = pArglist;
4740 pNew->a[pNew->nCte].zName = zName;
4741 pNew->a[pNew->nCte].zCteErr = 0;
4742 pNew->nCte++;
4745 return pNew;
4749 ** Free the contents of the With object passed as the second argument.
4751 void sqlite3WithDelete(sqlite3 *db, With *pWith){
4752 if( pWith ){
4753 int i;
4754 for(i=0; i<pWith->nCte; i++){
4755 struct Cte *pCte = &pWith->a[i];
4756 sqlite3ExprListDelete(db, pCte->pCols);
4757 sqlite3SelectDelete(db, pCte->pSelect);
4758 sqlite3DbFree(db, pCte->zName);
4760 sqlite3DbFree(db, pWith);
4763 #endif /* !defined(SQLITE_OMIT_CTE) */