Merge sqlite-release(3.44.2) into prerelease-integration
[sqlcipher.git] / src / build.c
blob3d0679235866f421222f500efd28a5375136a3b9
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 Pgno 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 static SQLITE_NOINLINE void lockTable(
50 Parse *pParse, /* Parsing context */
51 int iDb, /* Index of the database containing the table to lock */
52 Pgno 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;
57 int i;
58 int nBytes;
59 TableLock *p;
60 assert( iDb>=0 );
62 pToplevel = sqlite3ParseToplevel(pParse);
63 for(i=0; i<pToplevel->nTableLock; i++){
64 p = &pToplevel->aTableLock[i];
65 if( p->iDb==iDb && p->iTab==iTab ){
66 p->isWriteLock = (p->isWriteLock || isWriteLock);
67 return;
71 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
72 pToplevel->aTableLock =
73 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
74 if( pToplevel->aTableLock ){
75 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
76 p->iDb = iDb;
77 p->iTab = iTab;
78 p->isWriteLock = isWriteLock;
79 p->zLockName = zName;
80 }else{
81 pToplevel->nTableLock = 0;
82 sqlite3OomFault(pToplevel->db);
85 void sqlite3TableLock(
86 Parse *pParse, /* Parsing context */
87 int iDb, /* Index of the database containing the table to lock */
88 Pgno iTab, /* Root page number of the table to be locked */
89 u8 isWriteLock, /* True for a write lock */
90 const char *zName /* Name of the table to be locked */
92 if( iDb==1 ) return;
93 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
94 lockTable(pParse, iDb, iTab, isWriteLock, zName);
98 ** Code an OP_TableLock instruction for each table locked by the
99 ** statement (configured by calls to sqlite3TableLock()).
101 static void codeTableLocks(Parse *pParse){
102 int i;
103 Vdbe *pVdbe = pParse->pVdbe;
104 assert( pVdbe!=0 );
106 for(i=0; i<pParse->nTableLock; i++){
107 TableLock *p = &pParse->aTableLock[i];
108 int p1 = p->iDb;
109 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
110 p->zLockName, P4_STATIC);
113 #else
114 #define codeTableLocks(x)
115 #endif
118 ** Return TRUE if the given yDbMask object is empty - if it contains no
119 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
120 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
122 #if SQLITE_MAX_ATTACHED>30
123 int sqlite3DbMaskAllZero(yDbMask m){
124 int i;
125 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
126 return 1;
128 #endif
131 ** This routine is called after a single SQL statement has been
132 ** parsed and a VDBE program to execute that statement has been
133 ** prepared. This routine puts the finishing touches on the
134 ** VDBE program and resets the pParse structure for the next
135 ** parse.
137 ** Note that if an error occurred, it might be the case that
138 ** no VDBE code was generated.
140 void sqlite3FinishCoding(Parse *pParse){
141 sqlite3 *db;
142 Vdbe *v;
143 int iDb, i;
145 assert( pParse->pToplevel==0 );
146 db = pParse->db;
147 assert( db->pParse==pParse );
148 if( pParse->nested ) return;
149 if( pParse->nErr ){
150 if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
151 return;
153 assert( db->mallocFailed==0 );
155 /* Begin by generating some termination code at the end of the
156 ** vdbe program
158 v = pParse->pVdbe;
159 if( v==0 ){
160 if( db->init.busy ){
161 pParse->rc = SQLITE_DONE;
162 return;
164 v = sqlite3GetVdbe(pParse);
165 if( v==0 ) pParse->rc = SQLITE_ERROR;
167 assert( !pParse->isMultiWrite
168 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
169 if( v ){
170 if( pParse->bReturning ){
171 Returning *pReturning = pParse->u1.pReturning;
172 int addrRewind;
173 int reg;
175 if( pReturning->nRetCol ){
176 sqlite3VdbeAddOp0(v, OP_FkCheck);
177 addrRewind =
178 sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
179 VdbeCoverage(v);
180 reg = pReturning->iRetReg;
181 for(i=0; i<pReturning->nRetCol; i++){
182 sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
184 sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
185 sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
186 VdbeCoverage(v);
187 sqlite3VdbeJumpHere(v, addrRewind);
190 sqlite3VdbeAddOp0(v, OP_Halt);
192 #if SQLITE_USER_AUTHENTICATION
193 if( pParse->nTableLock>0 && db->init.busy==0 ){
194 sqlite3UserAuthInit(db);
195 if( db->auth.authLevel<UAUTH_User ){
196 sqlite3ErrorMsg(pParse, "user not authenticated");
197 pParse->rc = SQLITE_AUTH_USER;
198 return;
201 #endif
203 /* The cookie mask contains one bit for each database file open.
204 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
205 ** set for each database that is used. Generate code to start a
206 ** transaction on each used database and to verify the schema cookie
207 ** on each used database.
209 assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
210 sqlite3VdbeJumpHere(v, 0);
211 assert( db->nDb>0 );
212 iDb = 0;
214 Schema *pSchema;
215 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
216 sqlite3VdbeUsesBtree(v, iDb);
217 pSchema = db->aDb[iDb].pSchema;
218 sqlite3VdbeAddOp4Int(v,
219 OP_Transaction, /* Opcode */
220 iDb, /* P1 */
221 DbMaskTest(pParse->writeMask,iDb), /* P2 */
222 pSchema->schema_cookie, /* P3 */
223 pSchema->iGeneration /* P4 */
225 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
226 VdbeComment((v,
227 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
228 }while( ++iDb<db->nDb );
229 #ifndef SQLITE_OMIT_VIRTUALTABLE
230 for(i=0; i<pParse->nVtabLock; i++){
231 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
232 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
234 pParse->nVtabLock = 0;
235 #endif
237 #ifndef SQLITE_OMIT_SHARED_CACHE
238 /* Once all the cookies have been verified and transactions opened,
239 ** obtain the required table-locks. This is a no-op unless the
240 ** shared-cache feature is enabled.
242 if( pParse->nTableLock ) codeTableLocks(pParse);
243 #endif
245 /* Initialize any AUTOINCREMENT data structures required.
247 if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
249 /* Code constant expressions that were factored out of inner loops.
251 if( pParse->pConstExpr ){
252 ExprList *pEL = pParse->pConstExpr;
253 pParse->okConstFactor = 0;
254 for(i=0; i<pEL->nExpr; i++){
255 assert( pEL->a[i].u.iConstExprReg>0 );
256 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
260 if( pParse->bReturning ){
261 Returning *pRet = pParse->u1.pReturning;
262 if( pRet->nRetCol ){
263 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
267 /* Finally, jump back to the beginning of the executable code. */
268 sqlite3VdbeGoto(v, 1);
271 /* Get the VDBE program ready for execution
273 assert( v!=0 || pParse->nErr );
274 assert( db->mallocFailed==0 || pParse->nErr );
275 if( pParse->nErr==0 ){
276 /* A minimum of one cursor is required if autoincrement is used
277 * See ticket [a696379c1f08866] */
278 assert( pParse->pAinc==0 || pParse->nTab>0 );
279 sqlite3VdbeMakeReady(v, pParse);
280 pParse->rc = SQLITE_DONE;
281 }else{
282 pParse->rc = SQLITE_ERROR;
287 ** Run the parser and code generator recursively in order to generate
288 ** code for the SQL statement given onto the end of the pParse context
289 ** currently under construction. Notes:
291 ** * The final OP_Halt is not appended and other initialization
292 ** and finalization steps are omitted because those are handling by the
293 ** outermost parser.
295 ** * Built-in SQL functions always take precedence over application-defined
296 ** SQL functions. In other words, it is not possible to override a
297 ** built-in function.
299 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
300 va_list ap;
301 char *zSql;
302 sqlite3 *db = pParse->db;
303 u32 savedDbFlags = db->mDbFlags;
304 char saveBuf[PARSE_TAIL_SZ];
306 if( pParse->nErr ) return;
307 if( pParse->eParseMode ) return;
308 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
309 va_start(ap, zFormat);
310 zSql = sqlite3VMPrintf(db, zFormat, ap);
311 va_end(ap);
312 if( zSql==0 ){
313 /* This can result either from an OOM or because the formatted string
314 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
315 ** an error */
316 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
317 pParse->nErr++;
318 return;
320 pParse->nested++;
321 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
322 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
323 db->mDbFlags |= DBFLAG_PreferBuiltin;
324 sqlite3RunParser(pParse, zSql);
325 db->mDbFlags = savedDbFlags;
326 sqlite3DbFree(db, zSql);
327 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
328 pParse->nested--;
331 #if SQLITE_USER_AUTHENTICATION
333 ** Return TRUE if zTable is the name of the system table that stores the
334 ** list of users and their access credentials.
336 int sqlite3UserAuthTable(const char *zTable){
337 return sqlite3_stricmp(zTable, "sqlite_user")==0;
339 #endif
342 ** Locate the in-memory structure that describes a particular database
343 ** table given the name of that table and (optionally) the name of the
344 ** database containing the table. Return NULL if not found.
346 ** If zDatabase is 0, all databases are searched for the table and the
347 ** first matching table is returned. (No checking for duplicate table
348 ** names is done.) The search order is TEMP first, then MAIN, then any
349 ** auxiliary databases added using the ATTACH command.
351 ** See also sqlite3LocateTable().
353 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
354 Table *p = 0;
355 int i;
357 /* All mutexes are required for schema access. Make sure we hold them. */
358 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
359 #if SQLITE_USER_AUTHENTICATION
360 /* Only the admin user is allowed to know that the sqlite_user table
361 ** exists */
362 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
363 return 0;
365 #endif
366 if( zDatabase ){
367 for(i=0; i<db->nDb; i++){
368 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
370 if( i>=db->nDb ){
371 /* No match against the official names. But always match "main"
372 ** to schema 0 as a legacy fallback. */
373 if( sqlite3StrICmp(zDatabase,"main")==0 ){
374 i = 0;
375 }else{
376 return 0;
379 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
380 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
381 if( i==1 ){
382 if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
383 || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
384 || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
386 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
387 LEGACY_TEMP_SCHEMA_TABLE);
389 }else{
390 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
391 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
392 LEGACY_SCHEMA_TABLE);
396 }else{
397 /* Match against TEMP first */
398 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
399 if( p ) return p;
400 /* The main database is second */
401 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
402 if( p ) return p;
403 /* Attached databases are in order of attachment */
404 for(i=2; i<db->nDb; i++){
405 assert( sqlite3SchemaMutexHeld(db, i, 0) );
406 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
407 if( p ) break;
409 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
410 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
411 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
412 }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
413 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
414 LEGACY_TEMP_SCHEMA_TABLE);
418 return p;
422 ** Locate the in-memory structure that describes a particular database
423 ** table given the name of that table and (optionally) the name of the
424 ** database containing the table. Return NULL if not found. Also leave an
425 ** error message in pParse->zErrMsg.
427 ** The difference between this routine and sqlite3FindTable() is that this
428 ** routine leaves an error message in pParse->zErrMsg where
429 ** sqlite3FindTable() does not.
431 Table *sqlite3LocateTable(
432 Parse *pParse, /* context in which to report errors */
433 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
434 const char *zName, /* Name of the table we are looking for */
435 const char *zDbase /* Name of the database. Might be NULL */
437 Table *p;
438 sqlite3 *db = pParse->db;
440 /* Read the database schema. If an error occurs, leave an error message
441 ** and code in pParse and return NULL. */
442 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
443 && SQLITE_OK!=sqlite3ReadSchema(pParse)
445 return 0;
448 p = sqlite3FindTable(db, zName, zDbase);
449 if( p==0 ){
450 #ifndef SQLITE_OMIT_VIRTUALTABLE
451 /* If zName is the not the name of a table in the schema created using
452 ** CREATE, then check to see if it is the name of an virtual table that
453 ** can be an eponymous virtual table. */
454 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
455 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
456 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
457 pMod = sqlite3PragmaVtabRegister(db, zName);
459 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
460 testcase( pMod->pEpoTab==0 );
461 return pMod->pEpoTab;
464 #endif
465 if( flags & LOCATE_NOERR ) return 0;
466 pParse->checkSchema = 1;
467 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
468 p = 0;
471 if( p==0 ){
472 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
473 if( zDbase ){
474 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
475 }else{
476 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
478 }else{
479 assert( HasRowid(p) || p->iPKey<0 );
482 return p;
486 ** Locate the table identified by *p.
488 ** This is a wrapper around sqlite3LocateTable(). The difference between
489 ** sqlite3LocateTable() and this function is that this function restricts
490 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
491 ** non-NULL if it is part of a view or trigger program definition. See
492 ** sqlite3FixSrcList() for details.
494 Table *sqlite3LocateTableItem(
495 Parse *pParse,
496 u32 flags,
497 SrcItem *p
499 const char *zDb;
500 assert( p->pSchema==0 || p->zDatabase==0 );
501 if( p->pSchema ){
502 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
503 zDb = pParse->db->aDb[iDb].zDbSName;
504 }else{
505 zDb = p->zDatabase;
507 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
511 ** Return the preferred table name for system tables. Translate legacy
512 ** names into the new preferred names, as appropriate.
514 const char *sqlite3PreferredTableName(const char *zName){
515 if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
516 if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
517 return PREFERRED_SCHEMA_TABLE;
519 if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
520 return PREFERRED_TEMP_SCHEMA_TABLE;
523 return zName;
527 ** Locate the in-memory structure that describes
528 ** a particular index given the name of that index
529 ** and the name of the database that contains the index.
530 ** Return NULL if not found.
532 ** If zDatabase is 0, all databases are searched for the
533 ** table and the first matching index is returned. (No checking
534 ** for duplicate index names is done.) The search order is
535 ** TEMP first, then MAIN, then any auxiliary databases added
536 ** using the ATTACH command.
538 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
539 Index *p = 0;
540 int i;
541 /* All mutexes are required for schema access. Make sure we hold them. */
542 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
543 for(i=OMIT_TEMPDB; i<db->nDb; i++){
544 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
545 Schema *pSchema = db->aDb[j].pSchema;
546 assert( pSchema );
547 if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
548 assert( sqlite3SchemaMutexHeld(db, j, 0) );
549 p = sqlite3HashFind(&pSchema->idxHash, zName);
550 if( p ) break;
552 return p;
556 ** Reclaim the memory used by an index
558 void sqlite3FreeIndex(sqlite3 *db, Index *p){
559 #ifndef SQLITE_OMIT_ANALYZE
560 sqlite3DeleteIndexSamples(db, p);
561 #endif
562 sqlite3ExprDelete(db, p->pPartIdxWhere);
563 sqlite3ExprListDelete(db, p->aColExpr);
564 sqlite3DbFree(db, p->zColAff);
565 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
566 #ifdef SQLITE_ENABLE_STAT4
567 sqlite3_free(p->aiRowEst);
568 #endif
569 sqlite3DbFree(db, p);
573 ** For the index called zIdxName which is found in the database iDb,
574 ** unlike that index from its Table then remove the index from
575 ** the index hash table and free all memory structures associated
576 ** with the index.
578 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
579 Index *pIndex;
580 Hash *pHash;
582 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
583 pHash = &db->aDb[iDb].pSchema->idxHash;
584 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
585 if( ALWAYS(pIndex) ){
586 if( pIndex->pTable->pIndex==pIndex ){
587 pIndex->pTable->pIndex = pIndex->pNext;
588 }else{
589 Index *p;
590 /* Justification of ALWAYS(); The index must be on the list of
591 ** indices. */
592 p = pIndex->pTable->pIndex;
593 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
594 if( ALWAYS(p && p->pNext==pIndex) ){
595 p->pNext = pIndex->pNext;
598 sqlite3FreeIndex(db, pIndex);
600 db->mDbFlags |= DBFLAG_SchemaChange;
604 ** Look through the list of open database files in db->aDb[] and if
605 ** any have been closed, remove them from the list. Reallocate the
606 ** db->aDb[] structure to a smaller size, if possible.
608 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
609 ** are never candidates for being collapsed.
611 void sqlite3CollapseDatabaseArray(sqlite3 *db){
612 int i, j;
613 for(i=j=2; i<db->nDb; i++){
614 struct Db *pDb = &db->aDb[i];
615 if( pDb->pBt==0 ){
616 sqlite3DbFree(db, pDb->zDbSName);
617 pDb->zDbSName = 0;
618 continue;
620 if( j<i ){
621 db->aDb[j] = db->aDb[i];
623 j++;
625 db->nDb = j;
626 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
627 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
628 sqlite3DbFree(db, db->aDb);
629 db->aDb = db->aDbStatic;
634 ** Reset the schema for the database at index iDb. Also reset the
635 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
636 ** Deferred resets may be run by calling with iDb<0.
638 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
639 int i;
640 assert( iDb<db->nDb );
642 if( iDb>=0 ){
643 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
644 DbSetProperty(db, iDb, DB_ResetWanted);
645 DbSetProperty(db, 1, DB_ResetWanted);
646 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
649 if( db->nSchemaLock==0 ){
650 for(i=0; i<db->nDb; i++){
651 if( DbHasProperty(db, i, DB_ResetWanted) ){
652 sqlite3SchemaClear(db->aDb[i].pSchema);
659 ** Erase all schema information from all attached databases (including
660 ** "main" and "temp") for a single database connection.
662 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
663 int i;
664 sqlite3BtreeEnterAll(db);
665 for(i=0; i<db->nDb; i++){
666 Db *pDb = &db->aDb[i];
667 if( pDb->pSchema ){
668 if( db->nSchemaLock==0 ){
669 sqlite3SchemaClear(pDb->pSchema);
670 }else{
671 DbSetProperty(db, i, DB_ResetWanted);
675 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
676 sqlite3VtabUnlockList(db);
677 sqlite3BtreeLeaveAll(db);
678 if( db->nSchemaLock==0 ){
679 sqlite3CollapseDatabaseArray(db);
684 ** This routine is called when a commit occurs.
686 void sqlite3CommitInternalChanges(sqlite3 *db){
687 db->mDbFlags &= ~DBFLAG_SchemaChange;
691 ** Set the expression associated with a column. This is usually
692 ** the DEFAULT value, but might also be the expression that computes
693 ** the value for a generated column.
695 void sqlite3ColumnSetExpr(
696 Parse *pParse, /* Parsing context */
697 Table *pTab, /* The table containing the column */
698 Column *pCol, /* The column to receive the new DEFAULT expression */
699 Expr *pExpr /* The new default expression */
701 ExprList *pList;
702 assert( IsOrdinaryTable(pTab) );
703 pList = pTab->u.tab.pDfltList;
704 if( pCol->iDflt==0
705 || NEVER(pList==0)
706 || NEVER(pList->nExpr<pCol->iDflt)
708 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
709 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
710 }else{
711 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
712 pList->a[pCol->iDflt-1].pExpr = pExpr;
717 ** Return the expression associated with a column. The expression might be
718 ** the DEFAULT clause or the AS clause of a generated column.
719 ** Return NULL if the column has no associated expression.
721 Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
722 if( pCol->iDflt==0 ) return 0;
723 if( NEVER(!IsOrdinaryTable(pTab)) ) return 0;
724 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
725 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
726 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
730 ** Set the collating sequence name for a column.
732 void sqlite3ColumnSetColl(
733 sqlite3 *db,
734 Column *pCol,
735 const char *zColl
737 i64 nColl;
738 i64 n;
739 char *zNew;
740 assert( zColl!=0 );
741 n = sqlite3Strlen30(pCol->zCnName) + 1;
742 if( pCol->colFlags & COLFLAG_HASTYPE ){
743 n += sqlite3Strlen30(pCol->zCnName+n) + 1;
745 nColl = sqlite3Strlen30(zColl) + 1;
746 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
747 if( zNew ){
748 pCol->zCnName = zNew;
749 memcpy(pCol->zCnName + n, zColl, nColl);
750 pCol->colFlags |= COLFLAG_HASCOLL;
755 ** Return the collating sequence name for a column
757 const char *sqlite3ColumnColl(Column *pCol){
758 const char *z;
759 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
760 z = pCol->zCnName;
761 while( *z ){ z++; }
762 if( pCol->colFlags & COLFLAG_HASTYPE ){
763 do{ z++; }while( *z );
765 return z+1;
769 ** Delete memory allocated for the column names of a table or view (the
770 ** Table.aCol[] array).
772 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
773 int i;
774 Column *pCol;
775 assert( pTable!=0 );
776 assert( db!=0 );
777 if( (pCol = pTable->aCol)!=0 ){
778 for(i=0; i<pTable->nCol; i++, pCol++){
779 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
780 sqlite3DbFree(db, pCol->zCnName);
782 sqlite3DbNNFreeNN(db, pTable->aCol);
783 if( IsOrdinaryTable(pTable) ){
784 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
786 if( db->pnBytesFreed==0 ){
787 pTable->aCol = 0;
788 pTable->nCol = 0;
789 if( IsOrdinaryTable(pTable) ){
790 pTable->u.tab.pDfltList = 0;
797 ** Remove the memory data structures associated with the given
798 ** Table. No changes are made to disk by this routine.
800 ** This routine just deletes the data structure. It does not unlink
801 ** the table data structure from the hash table. But it does destroy
802 ** memory structures of the indices and foreign keys associated with
803 ** the table.
805 ** The db parameter is optional. It is needed if the Table object
806 ** contains lookaside memory. (Table objects in the schema do not use
807 ** lookaside memory, but some ephemeral Table objects do.) Or the
808 ** db parameter can be used with db->pnBytesFreed to measure the memory
809 ** used by the Table object.
811 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
812 Index *pIndex, *pNext;
814 #ifdef SQLITE_DEBUG
815 /* Record the number of outstanding lookaside allocations in schema Tables
816 ** prior to doing any free() operations. Since schema Tables do not use
817 ** lookaside, this number should not change.
819 ** If malloc has already failed, it may be that it failed while allocating
820 ** a Table object that was going to be marked ephemeral. So do not check
821 ** that no lookaside memory is used in this case either. */
822 int nLookaside = 0;
823 assert( db!=0 );
824 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
825 nLookaside = sqlite3LookasideUsed(db, 0);
827 #endif
829 /* Delete all indices associated with this table. */
830 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
831 pNext = pIndex->pNext;
832 assert( pIndex->pSchema==pTable->pSchema
833 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
834 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
835 char *zName = pIndex->zName;
836 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
837 &pIndex->pSchema->idxHash, zName, 0
839 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
840 assert( pOld==pIndex || pOld==0 );
842 sqlite3FreeIndex(db, pIndex);
845 if( IsOrdinaryTable(pTable) ){
846 sqlite3FkDelete(db, pTable);
848 #ifndef SQLITE_OMIT_VIRTUALTABLE
849 else if( IsVirtual(pTable) ){
850 sqlite3VtabClear(db, pTable);
852 #endif
853 else{
854 assert( IsView(pTable) );
855 sqlite3SelectDelete(db, pTable->u.view.pSelect);
858 /* Delete the Table structure itself.
860 sqlite3DeleteColumnNames(db, pTable);
861 sqlite3DbFree(db, pTable->zName);
862 sqlite3DbFree(db, pTable->zColAff);
863 sqlite3ExprListDelete(db, pTable->pCheck);
864 sqlite3DbFree(db, pTable);
866 /* Verify that no lookaside memory was used by schema tables */
867 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
869 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
870 /* Do not delete the table until the reference count reaches zero. */
871 assert( db!=0 );
872 if( !pTable ) return;
873 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
874 deleteTable(db, pTable);
879 ** Unlink the given table from the hash tables and the delete the
880 ** table structure with all its indices and foreign keys.
882 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
883 Table *p;
884 Db *pDb;
886 assert( db!=0 );
887 assert( iDb>=0 && iDb<db->nDb );
888 assert( zTabName );
889 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
890 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
891 pDb = &db->aDb[iDb];
892 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
893 sqlite3DeleteTable(db, p);
894 db->mDbFlags |= DBFLAG_SchemaChange;
898 ** Given a token, return a string that consists of the text of that
899 ** token. Space to hold the returned string
900 ** is obtained from sqliteMalloc() and must be freed by the calling
901 ** function.
903 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
904 ** surround the body of the token are removed.
906 ** Tokens are often just pointers into the original SQL text and so
907 ** are not \000 terminated and are not persistent. The returned string
908 ** is \000 terminated and is persistent.
910 char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
911 char *zName;
912 if( pName ){
913 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
914 sqlite3Dequote(zName);
915 }else{
916 zName = 0;
918 return zName;
922 ** Open the sqlite_schema table stored in database number iDb for
923 ** writing. The table is opened using cursor 0.
925 void sqlite3OpenSchemaTable(Parse *p, int iDb){
926 Vdbe *v = sqlite3GetVdbe(p);
927 sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
928 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
929 if( p->nTab==0 ){
930 p->nTab = 1;
935 ** Parameter zName points to a nul-terminated buffer containing the name
936 ** of a database ("main", "temp" or the name of an attached db). This
937 ** function returns the index of the named database in db->aDb[], or
938 ** -1 if the named db cannot be found.
940 int sqlite3FindDbName(sqlite3 *db, const char *zName){
941 int i = -1; /* Database number */
942 if( zName ){
943 Db *pDb;
944 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
945 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
946 /* "main" is always an acceptable alias for the primary database
947 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
948 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
951 return i;
955 ** The token *pName contains the name of a database (either "main" or
956 ** "temp" or the name of an attached db). This routine returns the
957 ** index of the named database in db->aDb[], or -1 if the named db
958 ** does not exist.
960 int sqlite3FindDb(sqlite3 *db, Token *pName){
961 int i; /* Database number */
962 char *zName; /* Name we are searching for */
963 zName = sqlite3NameFromToken(db, pName);
964 i = sqlite3FindDbName(db, zName);
965 sqlite3DbFree(db, zName);
966 return i;
969 /* The table or view or trigger name is passed to this routine via tokens
970 ** pName1 and pName2. If the table name was fully qualified, for example:
972 ** CREATE TABLE xxx.yyy (...);
974 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
975 ** the table name is not fully qualified, i.e.:
977 ** CREATE TABLE yyy(...);
979 ** Then pName1 is set to "yyy" and pName2 is "".
981 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
982 ** pName2) that stores the unqualified table name. The index of the
983 ** database "xxx" is returned.
985 int sqlite3TwoPartName(
986 Parse *pParse, /* Parsing and code generating context */
987 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
988 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
989 Token **pUnqual /* Write the unqualified object name here */
991 int iDb; /* Database holding the object */
992 sqlite3 *db = pParse->db;
994 assert( pName2!=0 );
995 if( pName2->n>0 ){
996 if( db->init.busy ) {
997 sqlite3ErrorMsg(pParse, "corrupt database");
998 return -1;
1000 *pUnqual = pName2;
1001 iDb = sqlite3FindDb(db, pName1);
1002 if( iDb<0 ){
1003 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
1004 return -1;
1006 }else{
1007 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
1008 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
1009 iDb = db->init.iDb;
1010 *pUnqual = pName1;
1012 return iDb;
1016 ** True if PRAGMA writable_schema is ON
1018 int sqlite3WritableSchema(sqlite3 *db){
1019 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
1020 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1021 SQLITE_WriteSchema );
1022 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1023 SQLITE_Defensive );
1024 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1025 (SQLITE_WriteSchema|SQLITE_Defensive) );
1026 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
1030 ** This routine is used to check if the UTF-8 string zName is a legal
1031 ** unqualified name for a new schema object (table, index, view or
1032 ** trigger). All names are legal except those that begin with the string
1033 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
1034 ** is reserved for internal use.
1036 ** When parsing the sqlite_schema table, this routine also checks to
1037 ** make sure the "type", "name", and "tbl_name" columns are consistent
1038 ** with the SQL.
1040 int sqlite3CheckObjectName(
1041 Parse *pParse, /* Parsing context */
1042 const char *zName, /* Name of the object to check */
1043 const char *zType, /* Type of this object */
1044 const char *zTblName /* Parent table name for triggers and indexes */
1046 sqlite3 *db = pParse->db;
1047 if( sqlite3WritableSchema(db)
1048 || db->init.imposterTable
1049 || !sqlite3Config.bExtraSchemaChecks
1051 /* Skip these error checks for writable_schema=ON */
1052 return SQLITE_OK;
1054 if( db->init.busy ){
1055 if( sqlite3_stricmp(zType, db->init.azInit[0])
1056 || sqlite3_stricmp(zName, db->init.azInit[1])
1057 || sqlite3_stricmp(zTblName, db->init.azInit[2])
1059 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
1060 return SQLITE_ERROR;
1062 }else{
1063 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
1064 || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
1066 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
1067 zName);
1068 return SQLITE_ERROR;
1072 return SQLITE_OK;
1076 ** Return the PRIMARY KEY index of a table
1078 Index *sqlite3PrimaryKeyIndex(Table *pTab){
1079 Index *p;
1080 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
1081 return p;
1085 ** Convert an table column number into a index column number. That is,
1086 ** for the column iCol in the table (as defined by the CREATE TABLE statement)
1087 ** find the (first) offset of that column in index pIdx. Or return -1
1088 ** if column iCol is not used in index pIdx.
1090 i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
1091 int i;
1092 for(i=0; i<pIdx->nColumn; i++){
1093 if( iCol==pIdx->aiColumn[i] ) return i;
1095 return -1;
1098 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1099 /* Convert a storage column number into a table column number.
1101 ** The storage column number (0,1,2,....) is the index of the value
1102 ** as it appears in the record on disk. The true column number
1103 ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
1105 ** The storage column number is less than the table column number if
1106 ** and only there are VIRTUAL columns to the left.
1108 ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
1110 i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
1111 if( pTab->tabFlags & TF_HasVirtual ){
1112 int i;
1113 for(i=0; i<=iCol; i++){
1114 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
1117 return iCol;
1119 #endif
1121 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1122 /* Convert a table column number into a storage column number.
1124 ** The storage column number (0,1,2,....) is the index of the value
1125 ** as it appears in the record on disk. Or, if the input column is
1126 ** the N-th virtual column (zero-based) then the storage number is
1127 ** the number of non-virtual columns in the table plus N.
1129 ** The true column number is the index (0,1,2,...) of the column in
1130 ** the CREATE TABLE statement.
1132 ** If the input column is a VIRTUAL column, then it should not appear
1133 ** in storage. But the value sometimes is cached in registers that
1134 ** follow the range of registers used to construct storage. This
1135 ** avoids computing the same VIRTUAL column multiple times, and provides
1136 ** values for use by OP_Param opcodes in triggers. Hence, if the
1137 ** input column is a VIRTUAL table, put it after all the other columns.
1139 ** In the following, N means "normal column", S means STORED, and
1140 ** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
1142 ** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
1143 ** -- 0 1 2 3 4 5 6 7 8
1145 ** Then the mapping from this function is as follows:
1147 ** INPUTS: 0 1 2 3 4 5 6 7 8
1148 ** OUTPUTS: 0 1 6 2 3 7 4 5 8
1150 ** So, in other words, this routine shifts all the virtual columns to
1151 ** the end.
1153 ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
1154 ** this routine is a no-op macro. If the pTab does not have any virtual
1155 ** columns, then this routine is no-op that always return iCol. If iCol
1156 ** is negative (indicating the ROWID column) then this routine return iCol.
1158 i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
1159 int i;
1160 i16 n;
1161 assert( iCol<pTab->nCol );
1162 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
1163 for(i=0, n=0; i<iCol; i++){
1164 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
1166 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
1167 /* iCol is a virtual column itself */
1168 return pTab->nNVCol + i - n;
1169 }else{
1170 /* iCol is a normal or stored column */
1171 return n;
1174 #endif
1177 ** Insert a single OP_JournalMode query opcode in order to force the
1178 ** prepared statement to return false for sqlite3_stmt_readonly(). This
1179 ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
1180 ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
1181 ** will return false for sqlite3_stmt_readonly() even if that statement
1182 ** is a read-only no-op.
1184 static void sqlite3ForceNotReadOnly(Parse *pParse){
1185 int iReg = ++pParse->nMem;
1186 Vdbe *v = sqlite3GetVdbe(pParse);
1187 if( v ){
1188 sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
1189 sqlite3VdbeUsesBtree(v, 0);
1194 ** Begin constructing a new table representation in memory. This is
1195 ** the first of several action routines that get called in response
1196 ** to a CREATE TABLE statement. In particular, this routine is called
1197 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
1198 ** flag is true if the table should be stored in the auxiliary database
1199 ** file instead of in the main database file. This is normally the case
1200 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
1201 ** CREATE and TABLE.
1203 ** The new table record is initialized and put in pParse->pNewTable.
1204 ** As more of the CREATE TABLE statement is parsed, additional action
1205 ** routines will be called to add more information to this record.
1206 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
1207 ** is called to complete the construction of the new table record.
1209 void sqlite3StartTable(
1210 Parse *pParse, /* Parser context */
1211 Token *pName1, /* First part of the name of the table or view */
1212 Token *pName2, /* Second part of the name of the table or view */
1213 int isTemp, /* True if this is a TEMP table */
1214 int isView, /* True if this is a VIEW */
1215 int isVirtual, /* True if this is a VIRTUAL table */
1216 int noErr /* Do nothing if table already exists */
1218 Table *pTable;
1219 char *zName = 0; /* The name of the new table */
1220 sqlite3 *db = pParse->db;
1221 Vdbe *v;
1222 int iDb; /* Database number to create the table in */
1223 Token *pName; /* Unqualified name of the table to create */
1225 if( db->init.busy && db->init.newTnum==1 ){
1226 /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */
1227 iDb = db->init.iDb;
1228 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
1229 pName = pName1;
1230 }else{
1231 /* The common case */
1232 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1233 if( iDb<0 ) return;
1234 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
1235 /* If creating a temp table, the name may not be qualified. Unless
1236 ** the database name is "temp" anyway. */
1237 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
1238 return;
1240 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
1241 zName = sqlite3NameFromToken(db, pName);
1242 if( IN_RENAME_OBJECT ){
1243 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
1246 pParse->sNameToken = *pName;
1247 if( zName==0 ) return;
1248 if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
1249 goto begin_table_error;
1251 if( db->init.iDb==1 ) isTemp = 1;
1252 #ifndef SQLITE_OMIT_AUTHORIZATION
1253 assert( isTemp==0 || isTemp==1 );
1254 assert( isView==0 || isView==1 );
1256 static const u8 aCode[] = {
1257 SQLITE_CREATE_TABLE,
1258 SQLITE_CREATE_TEMP_TABLE,
1259 SQLITE_CREATE_VIEW,
1260 SQLITE_CREATE_TEMP_VIEW
1262 char *zDb = db->aDb[iDb].zDbSName;
1263 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1264 goto begin_table_error;
1266 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
1267 zName, 0, zDb) ){
1268 goto begin_table_error;
1271 #endif
1273 /* Make sure the new table name does not collide with an existing
1274 ** index or table name in the same database. Issue an error message if
1275 ** it does. The exception is if the statement being parsed was passed
1276 ** to an sqlite3_declare_vtab() call. In that case only the column names
1277 ** and types will be used, so there is no need to test for namespace
1278 ** collisions.
1280 if( !IN_SPECIAL_PARSE ){
1281 char *zDb = db->aDb[iDb].zDbSName;
1282 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1283 goto begin_table_error;
1285 pTable = sqlite3FindTable(db, zName, zDb);
1286 if( pTable ){
1287 if( !noErr ){
1288 sqlite3ErrorMsg(pParse, "%s %T already exists",
1289 (IsView(pTable)? "view" : "table"), pName);
1290 }else{
1291 assert( !db->init.busy || CORRUPT_DB );
1292 sqlite3CodeVerifySchema(pParse, iDb);
1293 sqlite3ForceNotReadOnly(pParse);
1295 goto begin_table_error;
1297 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
1298 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
1299 goto begin_table_error;
1303 pTable = sqlite3DbMallocZero(db, sizeof(Table));
1304 if( pTable==0 ){
1305 assert( db->mallocFailed );
1306 pParse->rc = SQLITE_NOMEM_BKPT;
1307 pParse->nErr++;
1308 goto begin_table_error;
1310 pTable->zName = zName;
1311 pTable->iPKey = -1;
1312 pTable->pSchema = db->aDb[iDb].pSchema;
1313 pTable->nTabRef = 1;
1314 #ifdef SQLITE_DEFAULT_ROWEST
1315 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
1316 #else
1317 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
1318 #endif
1319 assert( pParse->pNewTable==0 );
1320 pParse->pNewTable = pTable;
1322 /* Begin generating the code that will insert the table record into
1323 ** the schema table. Note in particular that we must go ahead
1324 ** and allocate the record number for the table entry now. Before any
1325 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
1326 ** indices to be created and the table record must come before the
1327 ** indices. Hence, the record number for the table must be allocated
1328 ** now.
1330 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1331 int addr1;
1332 int fileFormat;
1333 int reg1, reg2, reg3;
1334 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
1335 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
1336 sqlite3BeginWriteOperation(pParse, 1, iDb);
1338 #ifndef SQLITE_OMIT_VIRTUALTABLE
1339 if( isVirtual ){
1340 sqlite3VdbeAddOp0(v, OP_VBegin);
1342 #endif
1344 /* If the file format and encoding in the database have not been set,
1345 ** set them now.
1347 reg1 = pParse->regRowid = ++pParse->nMem;
1348 reg2 = pParse->regRoot = ++pParse->nMem;
1349 reg3 = ++pParse->nMem;
1350 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
1351 sqlite3VdbeUsesBtree(v, iDb);
1352 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
1353 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1354 1 : SQLITE_MAX_FILE_FORMAT;
1355 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
1356 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
1357 sqlite3VdbeJumpHere(v, addr1);
1359 /* This just creates a place-holder record in the sqlite_schema table.
1360 ** The record created does not contain anything yet. It will be replaced
1361 ** by the real entry in code generated at sqlite3EndTable().
1363 ** The rowid for the new entry is left in register pParse->regRowid.
1364 ** The root page number of the new table is left in reg pParse->regRoot.
1365 ** The rowid and root page number values are needed by the code that
1366 ** sqlite3EndTable will generate.
1368 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1369 if( isView || isVirtual ){
1370 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1371 }else
1372 #endif
1374 assert( !pParse->bReturning );
1375 pParse->u1.addrCrTab =
1376 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
1378 sqlite3OpenSchemaTable(pParse, iDb);
1379 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1380 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
1381 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1382 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1383 sqlite3VdbeAddOp0(v, OP_Close);
1386 /* Normal (non-error) return. */
1387 return;
1389 /* If an error occurs, we jump here */
1390 begin_table_error:
1391 pParse->checkSchema = 1;
1392 sqlite3DbFree(db, zName);
1393 return;
1396 /* Set properties of a table column based on the (magical)
1397 ** name of the column.
1399 #if SQLITE_ENABLE_HIDDEN_COLUMNS
1400 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
1401 if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
1402 pCol->colFlags |= COLFLAG_HIDDEN;
1403 if( pTab ) pTab->tabFlags |= TF_HasHidden;
1404 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
1405 pTab->tabFlags |= TF_OOOHidden;
1408 #endif
1411 ** Clean up the data structures associated with the RETURNING clause.
1413 static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){
1414 Hash *pHash;
1415 pHash = &(db->aDb[1].pSchema->trigHash);
1416 sqlite3HashInsert(pHash, pRet->zName, 0);
1417 sqlite3ExprListDelete(db, pRet->pReturnEL);
1418 sqlite3DbFree(db, pRet);
1422 ** Add the RETURNING clause to the parse currently underway.
1424 ** This routine creates a special TEMP trigger that will fire for each row
1425 ** of the DML statement. That TEMP trigger contains a single SELECT
1426 ** statement with a result set that is the argument of the RETURNING clause.
1427 ** The trigger has the Trigger.bReturning flag and an opcode of
1428 ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
1429 ** knows to handle it specially. The TEMP trigger is automatically
1430 ** removed at the end of the parse.
1432 ** When this routine is called, we do not yet know if the RETURNING clause
1433 ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
1434 ** RETURNING trigger instead. It will then be converted into the appropriate
1435 ** type on the first call to sqlite3TriggersExist().
1437 void sqlite3AddReturning(Parse *pParse, ExprList *pList){
1438 Returning *pRet;
1439 Hash *pHash;
1440 sqlite3 *db = pParse->db;
1441 if( pParse->pNewTrigger ){
1442 sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
1443 }else{
1444 assert( pParse->bReturning==0 || pParse->ifNotExists );
1446 pParse->bReturning = 1;
1447 pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
1448 if( pRet==0 ){
1449 sqlite3ExprListDelete(db, pList);
1450 return;
1452 pParse->u1.pReturning = pRet;
1453 pRet->pParse = pParse;
1454 pRet->pReturnEL = pList;
1455 sqlite3ParserAddCleanup(pParse,
1456 (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet);
1457 testcase( pParse->earlyCleanup );
1458 if( db->mallocFailed ) return;
1459 sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
1460 "sqlite_returning_%p", pParse);
1461 pRet->retTrig.zName = pRet->zName;
1462 pRet->retTrig.op = TK_RETURNING;
1463 pRet->retTrig.tr_tm = TRIGGER_AFTER;
1464 pRet->retTrig.bReturning = 1;
1465 pRet->retTrig.pSchema = db->aDb[1].pSchema;
1466 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
1467 pRet->retTrig.step_list = &pRet->retTStep;
1468 pRet->retTStep.op = TK_RETURNING;
1469 pRet->retTStep.pTrig = &pRet->retTrig;
1470 pRet->retTStep.pExprList = pList;
1471 pHash = &(db->aDb[1].pSchema->trigHash);
1472 assert( sqlite3HashFind(pHash, pRet->zName)==0
1473 || pParse->nErr || pParse->ifNotExists );
1474 if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
1475 ==&pRet->retTrig ){
1476 sqlite3OomFault(db);
1481 ** Add a new column to the table currently being constructed.
1483 ** The parser calls this routine once for each column declaration
1484 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1485 ** first to get things going. Then this routine is called for each
1486 ** column.
1488 void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
1489 Table *p;
1490 int i;
1491 char *z;
1492 char *zType;
1493 Column *pCol;
1494 sqlite3 *db = pParse->db;
1495 u8 hName;
1496 Column *aNew;
1497 u8 eType = COLTYPE_CUSTOM;
1498 u8 szEst = 1;
1499 char affinity = SQLITE_AFF_BLOB;
1501 if( (p = pParse->pNewTable)==0 ) return;
1502 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1503 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1504 return;
1506 if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
1508 /* Because keywords GENERATE ALWAYS can be converted into identifiers
1509 ** by the parser, we can sometimes end up with a typename that ends
1510 ** with "generated always". Check for this case and omit the surplus
1511 ** text. */
1512 if( sType.n>=16
1513 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
1515 sType.n -= 6;
1516 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1517 if( sType.n>=9
1518 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
1520 sType.n -= 9;
1521 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1525 /* Check for standard typenames. For standard typenames we will
1526 ** set the Column.eType field rather than storing the typename after
1527 ** the column name, in order to save space. */
1528 if( sType.n>=3 ){
1529 sqlite3DequoteToken(&sType);
1530 for(i=0; i<SQLITE_N_STDTYPE; i++){
1531 if( sType.n==sqlite3StdTypeLen[i]
1532 && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
1534 sType.n = 0;
1535 eType = i+1;
1536 affinity = sqlite3StdTypeAffinity[i];
1537 if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
1538 break;
1543 z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
1544 if( z==0 ) return;
1545 if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
1546 memcpy(z, sName.z, sName.n);
1547 z[sName.n] = 0;
1548 sqlite3Dequote(z);
1549 hName = sqlite3StrIHash(z);
1550 for(i=0; i<p->nCol; i++){
1551 if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
1552 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1553 sqlite3DbFree(db, z);
1554 return;
1557 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
1558 if( aNew==0 ){
1559 sqlite3DbFree(db, z);
1560 return;
1562 p->aCol = aNew;
1563 pCol = &p->aCol[p->nCol];
1564 memset(pCol, 0, sizeof(p->aCol[0]));
1565 pCol->zCnName = z;
1566 pCol->hName = hName;
1567 sqlite3ColumnPropertiesFromName(p, pCol);
1569 if( sType.n==0 ){
1570 /* If there is no type specified, columns have the default affinity
1571 ** 'BLOB' with a default size of 4 bytes. */
1572 pCol->affinity = affinity;
1573 pCol->eCType = eType;
1574 pCol->szEst = szEst;
1575 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1576 if( affinity==SQLITE_AFF_BLOB ){
1577 if( 4>=sqlite3GlobalConfig.szSorterRef ){
1578 pCol->colFlags |= COLFLAG_SORTERREF;
1581 #endif
1582 }else{
1583 zType = z + sqlite3Strlen30(z) + 1;
1584 memcpy(zType, sType.z, sType.n);
1585 zType[sType.n] = 0;
1586 sqlite3Dequote(zType);
1587 pCol->affinity = sqlite3AffinityType(zType, pCol);
1588 pCol->colFlags |= COLFLAG_HASTYPE;
1590 p->nCol++;
1591 p->nNVCol++;
1592 pParse->constraintName.n = 0;
1596 ** This routine is called by the parser while in the middle of
1597 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1598 ** been seen on a column. This routine sets the notNull flag on
1599 ** the column currently under construction.
1601 void sqlite3AddNotNull(Parse *pParse, int onError){
1602 Table *p;
1603 Column *pCol;
1604 p = pParse->pNewTable;
1605 if( p==0 || NEVER(p->nCol<1) ) return;
1606 pCol = &p->aCol[p->nCol-1];
1607 pCol->notNull = (u8)onError;
1608 p->tabFlags |= TF_HasNotNull;
1610 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1611 ** on this column. */
1612 if( pCol->colFlags & COLFLAG_UNIQUE ){
1613 Index *pIdx;
1614 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1615 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1616 if( pIdx->aiColumn[0]==p->nCol-1 ){
1617 pIdx->uniqNotNull = 1;
1624 ** Scan the column type name zType (length nType) and return the
1625 ** associated affinity type.
1627 ** This routine does a case-independent search of zType for the
1628 ** substrings in the following table. If one of the substrings is
1629 ** found, the corresponding affinity is returned. If zType contains
1630 ** more than one of the substrings, entries toward the top of
1631 ** the table take priority. For example, if zType is 'BLOBINT',
1632 ** SQLITE_AFF_INTEGER is returned.
1634 ** Substring | Affinity
1635 ** --------------------------------
1636 ** 'INT' | SQLITE_AFF_INTEGER
1637 ** 'CHAR' | SQLITE_AFF_TEXT
1638 ** 'CLOB' | SQLITE_AFF_TEXT
1639 ** 'TEXT' | SQLITE_AFF_TEXT
1640 ** 'BLOB' | SQLITE_AFF_BLOB
1641 ** 'REAL' | SQLITE_AFF_REAL
1642 ** 'FLOA' | SQLITE_AFF_REAL
1643 ** 'DOUB' | SQLITE_AFF_REAL
1645 ** If none of the substrings in the above table are found,
1646 ** SQLITE_AFF_NUMERIC is returned.
1648 char sqlite3AffinityType(const char *zIn, Column *pCol){
1649 u32 h = 0;
1650 char aff = SQLITE_AFF_NUMERIC;
1651 const char *zChar = 0;
1653 assert( zIn!=0 );
1654 while( zIn[0] ){
1655 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1656 zIn++;
1657 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1658 aff = SQLITE_AFF_TEXT;
1659 zChar = zIn;
1660 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1661 aff = SQLITE_AFF_TEXT;
1662 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1663 aff = SQLITE_AFF_TEXT;
1664 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1665 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1666 aff = SQLITE_AFF_BLOB;
1667 if( zIn[0]=='(' ) zChar = zIn;
1668 #ifndef SQLITE_OMIT_FLOATING_POINT
1669 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1670 && aff==SQLITE_AFF_NUMERIC ){
1671 aff = SQLITE_AFF_REAL;
1672 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1673 && aff==SQLITE_AFF_NUMERIC ){
1674 aff = SQLITE_AFF_REAL;
1675 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1676 && aff==SQLITE_AFF_NUMERIC ){
1677 aff = SQLITE_AFF_REAL;
1678 #endif
1679 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1680 aff = SQLITE_AFF_INTEGER;
1681 break;
1685 /* If pCol is not NULL, store an estimate of the field size. The
1686 ** estimate is scaled so that the size of an integer is 1. */
1687 if( pCol ){
1688 int v = 0; /* default size is approx 4 bytes */
1689 if( aff<SQLITE_AFF_NUMERIC ){
1690 if( zChar ){
1691 while( zChar[0] ){
1692 if( sqlite3Isdigit(zChar[0]) ){
1693 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1694 sqlite3GetInt32(zChar, &v);
1695 break;
1697 zChar++;
1699 }else{
1700 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1703 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1704 if( v>=sqlite3GlobalConfig.szSorterRef ){
1705 pCol->colFlags |= COLFLAG_SORTERREF;
1707 #endif
1708 v = v/4 + 1;
1709 if( v>255 ) v = 255;
1710 pCol->szEst = v;
1712 return aff;
1716 ** The expression is the default value for the most recently added column
1717 ** of the table currently under construction.
1719 ** Default value expressions must be constant. Raise an exception if this
1720 ** is not the case.
1722 ** This routine is called by the parser while in the middle of
1723 ** parsing a CREATE TABLE statement.
1725 void sqlite3AddDefaultValue(
1726 Parse *pParse, /* Parsing context */
1727 Expr *pExpr, /* The parsed expression of the default value */
1728 const char *zStart, /* Start of the default value text */
1729 const char *zEnd /* First character past end of default value text */
1731 Table *p;
1732 Column *pCol;
1733 sqlite3 *db = pParse->db;
1734 p = pParse->pNewTable;
1735 if( p!=0 ){
1736 int isInit = db->init.busy && db->init.iDb!=1;
1737 pCol = &(p->aCol[p->nCol-1]);
1738 if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
1739 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1740 pCol->zCnName);
1741 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1742 }else if( pCol->colFlags & COLFLAG_GENERATED ){
1743 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1744 testcase( pCol->colFlags & COLFLAG_STORED );
1745 sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
1746 #endif
1747 }else{
1748 /* A copy of pExpr is used instead of the original, as pExpr contains
1749 ** tokens that point to volatile memory.
1751 Expr x, *pDfltExpr;
1752 memset(&x, 0, sizeof(x));
1753 x.op = TK_SPAN;
1754 x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1755 x.pLeft = pExpr;
1756 x.flags = EP_Skip;
1757 pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1758 sqlite3DbFree(db, x.u.zToken);
1759 sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
1762 if( IN_RENAME_OBJECT ){
1763 sqlite3RenameExprUnmap(pParse, pExpr);
1765 sqlite3ExprDelete(db, pExpr);
1769 ** Backwards Compatibility Hack:
1771 ** Historical versions of SQLite accepted strings as column names in
1772 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1774 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1775 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1777 ** This is goofy. But to preserve backwards compatibility we continue to
1778 ** accept it. This routine does the necessary conversion. It converts
1779 ** the expression given in its argument from a TK_STRING into a TK_ID
1780 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1781 ** If the expression is anything other than TK_STRING, the expression is
1782 ** unchanged.
1784 static void sqlite3StringToId(Expr *p){
1785 if( p->op==TK_STRING ){
1786 p->op = TK_ID;
1787 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1788 p->pLeft->op = TK_ID;
1793 ** Tag the given column as being part of the PRIMARY KEY
1795 static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1796 pCol->colFlags |= COLFLAG_PRIMKEY;
1797 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1798 if( pCol->colFlags & COLFLAG_GENERATED ){
1799 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1800 testcase( pCol->colFlags & COLFLAG_STORED );
1801 sqlite3ErrorMsg(pParse,
1802 "generated columns cannot be part of the PRIMARY KEY");
1804 #endif
1808 ** Designate the PRIMARY KEY for the table. pList is a list of names
1809 ** of columns that form the primary key. If pList is NULL, then the
1810 ** most recently added column of the table is the primary key.
1812 ** A table can have at most one primary key. If the table already has
1813 ** a primary key (and this is the second primary key) then create an
1814 ** error.
1816 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1817 ** then we will try to use that column as the rowid. Set the Table.iPKey
1818 ** field of the table under construction to be the index of the
1819 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1820 ** no INTEGER PRIMARY KEY.
1822 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1823 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1825 void sqlite3AddPrimaryKey(
1826 Parse *pParse, /* Parsing context */
1827 ExprList *pList, /* List of field names to be indexed */
1828 int onError, /* What to do with a uniqueness conflict */
1829 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1830 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1832 Table *pTab = pParse->pNewTable;
1833 Column *pCol = 0;
1834 int iCol = -1, i;
1835 int nTerm;
1836 if( pTab==0 ) goto primary_key_exit;
1837 if( pTab->tabFlags & TF_HasPrimaryKey ){
1838 sqlite3ErrorMsg(pParse,
1839 "table \"%s\" has more than one primary key", pTab->zName);
1840 goto primary_key_exit;
1842 pTab->tabFlags |= TF_HasPrimaryKey;
1843 if( pList==0 ){
1844 iCol = pTab->nCol - 1;
1845 pCol = &pTab->aCol[iCol];
1846 makeColumnPartOfPrimaryKey(pParse, pCol);
1847 nTerm = 1;
1848 }else{
1849 nTerm = pList->nExpr;
1850 for(i=0; i<nTerm; i++){
1851 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1852 assert( pCExpr!=0 );
1853 sqlite3StringToId(pCExpr);
1854 if( pCExpr->op==TK_ID ){
1855 const char *zCName;
1856 assert( !ExprHasProperty(pCExpr, EP_IntValue) );
1857 zCName = pCExpr->u.zToken;
1858 for(iCol=0; iCol<pTab->nCol; iCol++){
1859 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
1860 pCol = &pTab->aCol[iCol];
1861 makeColumnPartOfPrimaryKey(pParse, pCol);
1862 break;
1868 if( nTerm==1
1869 && pCol
1870 && pCol->eCType==COLTYPE_INTEGER
1871 && sortOrder!=SQLITE_SO_DESC
1873 if( IN_RENAME_OBJECT && pList ){
1874 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1875 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1877 pTab->iPKey = iCol;
1878 pTab->keyConf = (u8)onError;
1879 assert( autoInc==0 || autoInc==1 );
1880 pTab->tabFlags |= autoInc*TF_Autoincrement;
1881 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
1882 (void)sqlite3HasExplicitNulls(pParse, pList);
1883 }else if( autoInc ){
1884 #ifndef SQLITE_OMIT_AUTOINCREMENT
1885 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1886 "INTEGER PRIMARY KEY");
1887 #endif
1888 }else{
1889 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1890 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1891 pList = 0;
1894 primary_key_exit:
1895 sqlite3ExprListDelete(pParse->db, pList);
1896 return;
1900 ** Add a new CHECK constraint to the table currently under construction.
1902 void sqlite3AddCheckConstraint(
1903 Parse *pParse, /* Parsing context */
1904 Expr *pCheckExpr, /* The check expression */
1905 const char *zStart, /* Opening "(" */
1906 const char *zEnd /* Closing ")" */
1908 #ifndef SQLITE_OMIT_CHECK
1909 Table *pTab = pParse->pNewTable;
1910 sqlite3 *db = pParse->db;
1911 if( pTab && !IN_DECLARE_VTAB
1912 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1914 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1915 if( pParse->constraintName.n ){
1916 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1917 }else{
1918 Token t;
1919 for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
1920 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
1921 t.z = zStart;
1922 t.n = (int)(zEnd - t.z);
1923 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
1925 }else
1926 #endif
1928 sqlite3ExprDelete(pParse->db, pCheckExpr);
1933 ** Set the collation function of the most recently parsed table column
1934 ** to the CollSeq given.
1936 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1937 Table *p;
1938 int i;
1939 char *zColl; /* Dequoted name of collation sequence */
1940 sqlite3 *db;
1942 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
1943 i = p->nCol-1;
1944 db = pParse->db;
1945 zColl = sqlite3NameFromToken(db, pToken);
1946 if( !zColl ) return;
1948 if( sqlite3LocateCollSeq(pParse, zColl) ){
1949 Index *pIdx;
1950 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
1952 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1953 ** then an index may have been created on this column before the
1954 ** collation type was added. Correct this if it is the case.
1956 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1957 assert( pIdx->nKeyCol==1 );
1958 if( pIdx->aiColumn[0]==i ){
1959 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
1963 sqlite3DbFree(db, zColl);
1966 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1967 ** column.
1969 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
1970 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1971 u8 eType = COLFLAG_VIRTUAL;
1972 Table *pTab = pParse->pNewTable;
1973 Column *pCol;
1974 if( pTab==0 ){
1975 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1976 goto generated_done;
1978 pCol = &(pTab->aCol[pTab->nCol-1]);
1979 if( IN_DECLARE_VTAB ){
1980 sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
1981 goto generated_done;
1983 if( pCol->iDflt>0 ) goto generated_error;
1984 if( pType ){
1985 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
1986 /* no-op */
1987 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
1988 eType = COLFLAG_STORED;
1989 }else{
1990 goto generated_error;
1993 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
1994 pCol->colFlags |= eType;
1995 assert( TF_HasVirtual==COLFLAG_VIRTUAL );
1996 assert( TF_HasStored==COLFLAG_STORED );
1997 pTab->tabFlags |= eType;
1998 if( pCol->colFlags & COLFLAG_PRIMKEY ){
1999 makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
2001 if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
2002 /* The value of a generated column needs to be a real expression, not
2003 ** just a reference to another column, in order for covering index
2004 ** optimizations to work correctly. So if the value is not an expression,
2005 ** turn it into one by adding a unary "+" operator. */
2006 pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
2008 if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
2009 sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
2010 pExpr = 0;
2011 goto generated_done;
2013 generated_error:
2014 sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
2015 pCol->zCnName);
2016 generated_done:
2017 sqlite3ExprDelete(pParse->db, pExpr);
2018 #else
2019 /* Throw and error for the GENERATED ALWAYS AS clause if the
2020 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
2021 sqlite3ErrorMsg(pParse, "generated columns not supported");
2022 sqlite3ExprDelete(pParse->db, pExpr);
2023 #endif
2027 ** Generate code that will increment the schema cookie.
2029 ** The schema cookie is used to determine when the schema for the
2030 ** database changes. After each schema change, the cookie value
2031 ** changes. When a process first reads the schema it records the
2032 ** cookie. Thereafter, whenever it goes to access the database,
2033 ** it checks the cookie to make sure the schema has not changed
2034 ** since it was last read.
2036 ** This plan is not completely bullet-proof. It is possible for
2037 ** the schema to change multiple times and for the cookie to be
2038 ** set back to prior value. But schema changes are infrequent
2039 ** and the probability of hitting the same cookie value is only
2040 ** 1 chance in 2^32. So we're safe enough.
2042 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
2043 ** the schema-version whenever the schema changes.
2045 void sqlite3ChangeCookie(Parse *pParse, int iDb){
2046 sqlite3 *db = pParse->db;
2047 Vdbe *v = pParse->pVdbe;
2048 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2049 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
2050 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
2054 ** Measure the number of characters needed to output the given
2055 ** identifier. The number returned includes any quotes used
2056 ** but does not include the null terminator.
2058 ** The estimate is conservative. It might be larger that what is
2059 ** really needed.
2061 static int identLength(const char *z){
2062 int n;
2063 for(n=0; *z; n++, z++){
2064 if( *z=='"' ){ n++; }
2066 return n + 2;
2070 ** The first parameter is a pointer to an output buffer. The second
2071 ** parameter is a pointer to an integer that contains the offset at
2072 ** which to write into the output buffer. This function copies the
2073 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
2074 ** to the specified offset in the buffer and updates *pIdx to refer
2075 ** to the first byte after the last byte written before returning.
2077 ** If the string zSignedIdent consists entirely of alphanumeric
2078 ** characters, does not begin with a digit and is not an SQL keyword,
2079 ** then it is copied to the output buffer exactly as it is. Otherwise,
2080 ** it is quoted using double-quotes.
2082 static void identPut(char *z, int *pIdx, char *zSignedIdent){
2083 unsigned char *zIdent = (unsigned char*)zSignedIdent;
2084 int i, j, needQuote;
2085 i = *pIdx;
2087 for(j=0; zIdent[j]; j++){
2088 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
2090 needQuote = sqlite3Isdigit(zIdent[0])
2091 || sqlite3KeywordCode(zIdent, j)!=TK_ID
2092 || zIdent[j]!=0
2093 || j==0;
2095 if( needQuote ) z[i++] = '"';
2096 for(j=0; zIdent[j]; j++){
2097 z[i++] = zIdent[j];
2098 if( zIdent[j]=='"' ) z[i++] = '"';
2100 if( needQuote ) z[i++] = '"';
2101 z[i] = 0;
2102 *pIdx = i;
2106 ** Generate a CREATE TABLE statement appropriate for the given
2107 ** table. Memory to hold the text of the statement is obtained
2108 ** from sqliteMalloc() and must be freed by the calling function.
2110 static char *createTableStmt(sqlite3 *db, Table *p){
2111 int i, k, n;
2112 char *zStmt;
2113 char *zSep, *zSep2, *zEnd;
2114 Column *pCol;
2115 n = 0;
2116 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
2117 n += identLength(pCol->zCnName) + 5;
2119 n += identLength(p->zName);
2120 if( n<50 ){
2121 zSep = "";
2122 zSep2 = ",";
2123 zEnd = ")";
2124 }else{
2125 zSep = "\n ";
2126 zSep2 = ",\n ";
2127 zEnd = "\n)";
2129 n += 35 + 6*p->nCol;
2130 zStmt = sqlite3DbMallocRaw(0, n);
2131 if( zStmt==0 ){
2132 sqlite3OomFault(db);
2133 return 0;
2135 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
2136 k = sqlite3Strlen30(zStmt);
2137 identPut(zStmt, &k, p->zName);
2138 zStmt[k++] = '(';
2139 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
2140 static const char * const azType[] = {
2141 /* SQLITE_AFF_BLOB */ "",
2142 /* SQLITE_AFF_TEXT */ " TEXT",
2143 /* SQLITE_AFF_NUMERIC */ " NUM",
2144 /* SQLITE_AFF_INTEGER */ " INT",
2145 /* SQLITE_AFF_REAL */ " REAL",
2146 /* SQLITE_AFF_FLEXNUM */ " NUM",
2148 int len;
2149 const char *zType;
2151 sqlite3_snprintf(n-k, &zStmt[k], zSep);
2152 k += sqlite3Strlen30(&zStmt[k]);
2153 zSep = zSep2;
2154 identPut(zStmt, &k, pCol->zCnName);
2155 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
2156 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
2157 testcase( pCol->affinity==SQLITE_AFF_BLOB );
2158 testcase( pCol->affinity==SQLITE_AFF_TEXT );
2159 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
2160 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
2161 testcase( pCol->affinity==SQLITE_AFF_REAL );
2162 testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
2164 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
2165 len = sqlite3Strlen30(zType);
2166 assert( pCol->affinity==SQLITE_AFF_BLOB
2167 || pCol->affinity==SQLITE_AFF_FLEXNUM
2168 || pCol->affinity==sqlite3AffinityType(zType, 0) );
2169 memcpy(&zStmt[k], zType, len);
2170 k += len;
2171 assert( k<=n );
2173 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
2174 return zStmt;
2178 ** Resize an Index object to hold N columns total. Return SQLITE_OK
2179 ** on success and SQLITE_NOMEM on an OOM error.
2181 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
2182 char *zExtra;
2183 int nByte;
2184 if( pIdx->nColumn>=N ) return SQLITE_OK;
2185 assert( pIdx->isResized==0 );
2186 nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
2187 zExtra = sqlite3DbMallocZero(db, nByte);
2188 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
2189 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
2190 pIdx->azColl = (const char**)zExtra;
2191 zExtra += sizeof(char*)*N;
2192 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
2193 pIdx->aiRowLogEst = (LogEst*)zExtra;
2194 zExtra += sizeof(LogEst)*N;
2195 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
2196 pIdx->aiColumn = (i16*)zExtra;
2197 zExtra += sizeof(i16)*N;
2198 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
2199 pIdx->aSortOrder = (u8*)zExtra;
2200 pIdx->nColumn = N;
2201 pIdx->isResized = 1;
2202 return SQLITE_OK;
2206 ** Estimate the total row width for a table.
2208 static void estimateTableWidth(Table *pTab){
2209 unsigned wTable = 0;
2210 const Column *pTabCol;
2211 int i;
2212 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
2213 wTable += pTabCol->szEst;
2215 if( pTab->iPKey<0 ) wTable++;
2216 pTab->szTabRow = sqlite3LogEst(wTable*4);
2220 ** Estimate the average size of a row for an index.
2222 static void estimateIndexWidth(Index *pIdx){
2223 unsigned wIndex = 0;
2224 int i;
2225 const Column *aCol = pIdx->pTable->aCol;
2226 for(i=0; i<pIdx->nColumn; i++){
2227 i16 x = pIdx->aiColumn[i];
2228 assert( x<pIdx->pTable->nCol );
2229 wIndex += x<0 ? 1 : aCol[x].szEst;
2231 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
2234 /* Return true if column number x is any of the first nCol entries of aiCol[].
2235 ** This is used to determine if the column number x appears in any of the
2236 ** first nCol entries of an index.
2238 static int hasColumn(const i16 *aiCol, int nCol, int x){
2239 while( nCol-- > 0 ){
2240 if( x==*(aiCol++) ){
2241 return 1;
2244 return 0;
2248 ** Return true if any of the first nKey entries of index pIdx exactly
2249 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
2250 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
2251 ** or may not be the same index as pPk.
2253 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2254 ** not a rowid or expression.
2256 ** This routine differs from hasColumn() in that both the column and the
2257 ** collating sequence must match for this routine, but for hasColumn() only
2258 ** the column name must match.
2260 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
2261 int i, j;
2262 assert( nKey<=pIdx->nColumn );
2263 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
2264 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
2265 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
2266 assert( pPk->pTable==pIdx->pTable );
2267 testcase( pPk==pIdx );
2268 j = pPk->aiColumn[iCol];
2269 assert( j!=XN_ROWID && j!=XN_EXPR );
2270 for(i=0; i<nKey; i++){
2271 assert( pIdx->aiColumn[i]>=0 || j>=0 );
2272 if( pIdx->aiColumn[i]==j
2273 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
2275 return 1;
2278 return 0;
2281 /* Recompute the colNotIdxed field of the Index.
2283 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2284 ** columns that are within the first 63 columns of the table and a 1 for
2285 ** all other bits (all columns that are not in the index). The
2286 ** high-order bit of colNotIdxed is always 1. All unindexed columns
2287 ** of the table have a 1.
2289 ** 2019-10-24: For the purpose of this computation, virtual columns are
2290 ** not considered to be covered by the index, even if they are in the
2291 ** index, because we do not trust the logic in whereIndexExprTrans() to be
2292 ** able to find all instances of a reference to the indexed table column
2293 ** and convert them into references to the index. Hence we always want
2294 ** the actual table at hand in order to recompute the virtual column, if
2295 ** necessary.
2297 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2298 ** to determine if the index is covering index.
2300 static void recomputeColumnsNotIndexed(Index *pIdx){
2301 Bitmask m = 0;
2302 int j;
2303 Table *pTab = pIdx->pTable;
2304 for(j=pIdx->nColumn-1; j>=0; j--){
2305 int x = pIdx->aiColumn[j];
2306 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
2307 testcase( x==BMS-1 );
2308 testcase( x==BMS-2 );
2309 if( x<BMS-1 ) m |= MASKBIT(x);
2312 pIdx->colNotIdxed = ~m;
2313 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
2317 ** This routine runs at the end of parsing a CREATE TABLE statement that
2318 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
2319 ** internal schema data structures and the generated VDBE code so that they
2320 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2321 ** Changes include:
2323 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2324 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2325 ** into BTREE_BLOBKEY.
2326 ** (3) Bypass the creation of the sqlite_schema table entry
2327 ** for the PRIMARY KEY as the primary key index is now
2328 ** identified by the sqlite_schema table entry of the table itself.
2329 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
2330 ** schema to the rootpage from the main table.
2331 ** (5) Add all table columns to the PRIMARY KEY Index object
2332 ** so that the PRIMARY KEY is a covering index. The surplus
2333 ** columns are part of KeyInfo.nAllField and are not used for
2334 ** sorting or lookup or uniqueness checks.
2335 ** (6) Replace the rowid tail on all automatically generated UNIQUE
2336 ** indices with the PRIMARY KEY columns.
2338 ** For virtual tables, only (1) is performed.
2340 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
2341 Index *pIdx;
2342 Index *pPk;
2343 int nPk;
2344 int nExtra;
2345 int i, j;
2346 sqlite3 *db = pParse->db;
2347 Vdbe *v = pParse->pVdbe;
2349 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2351 if( !db->init.imposterTable ){
2352 for(i=0; i<pTab->nCol; i++){
2353 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
2354 && (pTab->aCol[i].notNull==OE_None)
2356 pTab->aCol[i].notNull = OE_Abort;
2359 pTab->tabFlags |= TF_HasNotNull;
2362 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2363 ** into BTREE_BLOBKEY.
2365 assert( !pParse->bReturning );
2366 if( pParse->u1.addrCrTab ){
2367 assert( v );
2368 sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
2371 /* Locate the PRIMARY KEY index. Or, if this table was originally
2372 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2374 if( pTab->iPKey>=0 ){
2375 ExprList *pList;
2376 Token ipkToken;
2377 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
2378 pList = sqlite3ExprListAppend(pParse, 0,
2379 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
2380 if( pList==0 ){
2381 pTab->tabFlags &= ~TF_WithoutRowid;
2382 return;
2384 if( IN_RENAME_OBJECT ){
2385 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2387 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
2388 assert( pParse->pNewTable==pTab );
2389 pTab->iPKey = -1;
2390 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
2391 SQLITE_IDXTYPE_PRIMARYKEY);
2392 if( pParse->nErr ){
2393 pTab->tabFlags &= ~TF_WithoutRowid;
2394 return;
2396 assert( db->mallocFailed==0 );
2397 pPk = sqlite3PrimaryKeyIndex(pTab);
2398 assert( pPk->nKeyCol==1 );
2399 }else{
2400 pPk = sqlite3PrimaryKeyIndex(pTab);
2401 assert( pPk!=0 );
2404 ** Remove all redundant columns from the PRIMARY KEY. For example, change
2405 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
2406 ** code assumes the PRIMARY KEY contains no repeated columns.
2408 for(i=j=1; i<pPk->nKeyCol; i++){
2409 if( isDupColumn(pPk, j, pPk, i) ){
2410 pPk->nColumn--;
2411 }else{
2412 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
2413 pPk->azColl[j] = pPk->azColl[i];
2414 pPk->aSortOrder[j] = pPk->aSortOrder[i];
2415 pPk->aiColumn[j++] = pPk->aiColumn[i];
2418 pPk->nKeyCol = j;
2420 assert( pPk!=0 );
2421 pPk->isCovering = 1;
2422 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
2423 nPk = pPk->nColumn = pPk->nKeyCol;
2425 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2426 ** table entry. This is only required if currently generating VDBE
2427 ** code for a CREATE TABLE (not when parsing one as part of reading
2428 ** a database schema). */
2429 if( v && pPk->tnum>0 ){
2430 assert( db->init.busy==0 );
2431 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
2434 /* The root page of the PRIMARY KEY is the table root page */
2435 pPk->tnum = pTab->tnum;
2437 /* Update the in-memory representation of all UNIQUE indices by converting
2438 ** the final rowid column into one or more columns of the PRIMARY KEY.
2440 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2441 int n;
2442 if( IsPrimaryKeyIndex(pIdx) ) continue;
2443 for(i=n=0; i<nPk; i++){
2444 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2445 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2446 n++;
2449 if( n==0 ){
2450 /* This index is a superset of the primary key */
2451 pIdx->nColumn = pIdx->nKeyCol;
2452 continue;
2454 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
2455 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2456 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2457 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2458 pIdx->aiColumn[j] = pPk->aiColumn[i];
2459 pIdx->azColl[j] = pPk->azColl[i];
2460 if( pPk->aSortOrder[i] ){
2461 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2462 pIdx->bAscKeyBug = 1;
2464 j++;
2467 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
2468 assert( pIdx->nColumn>=j );
2471 /* Add all table columns to the PRIMARY KEY index
2473 nExtra = 0;
2474 for(i=0; i<pTab->nCol; i++){
2475 if( !hasColumn(pPk->aiColumn, nPk, i)
2476 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
2478 if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
2479 for(i=0, j=nPk; i<pTab->nCol; i++){
2480 if( !hasColumn(pPk->aiColumn, j, i)
2481 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
2483 assert( j<pPk->nColumn );
2484 pPk->aiColumn[j] = i;
2485 pPk->azColl[j] = sqlite3StrBINARY;
2486 j++;
2489 assert( pPk->nColumn==j );
2490 assert( pTab->nNVCol<=j );
2491 recomputeColumnsNotIndexed(pPk);
2495 #ifndef SQLITE_OMIT_VIRTUALTABLE
2497 ** Return true if pTab is a virtual table and zName is a shadow table name
2498 ** for that virtual table.
2500 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
2501 int nName; /* Length of zName */
2502 Module *pMod; /* Module for the virtual table */
2504 if( !IsVirtual(pTab) ) return 0;
2505 nName = sqlite3Strlen30(pTab->zName);
2506 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
2507 if( zName[nName]!='_' ) return 0;
2508 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2509 if( pMod==0 ) return 0;
2510 if( pMod->pModule->iVersion<3 ) return 0;
2511 if( pMod->pModule->xShadowName==0 ) return 0;
2512 return pMod->pModule->xShadowName(zName+nName+1);
2514 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2516 #ifndef SQLITE_OMIT_VIRTUALTABLE
2518 ** Table pTab is a virtual table. If it the virtual table implementation
2519 ** exists and has an xShadowName method, then loop over all other ordinary
2520 ** tables within the same schema looking for shadow tables of pTab, and mark
2521 ** any shadow tables seen using the TF_Shadow flag.
2523 void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
2524 int nName; /* Length of pTab->zName */
2525 Module *pMod; /* Module for the virtual table */
2526 HashElem *k; /* For looping through the symbol table */
2528 assert( IsVirtual(pTab) );
2529 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2530 if( pMod==0 ) return;
2531 if( NEVER(pMod->pModule==0) ) return;
2532 if( pMod->pModule->iVersion<3 ) return;
2533 if( pMod->pModule->xShadowName==0 ) return;
2534 assert( pTab->zName!=0 );
2535 nName = sqlite3Strlen30(pTab->zName);
2536 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
2537 Table *pOther = sqliteHashData(k);
2538 assert( pOther->zName!=0 );
2539 if( !IsOrdinaryTable(pOther) ) continue;
2540 if( pOther->tabFlags & TF_Shadow ) continue;
2541 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
2542 && pOther->zName[nName]=='_'
2543 && pMod->pModule->xShadowName(pOther->zName+nName+1)
2545 pOther->tabFlags |= TF_Shadow;
2549 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2551 #ifndef SQLITE_OMIT_VIRTUALTABLE
2553 ** Return true if zName is a shadow table name in the current database
2554 ** connection.
2556 ** zName is temporarily modified while this routine is running, but is
2557 ** restored to its original value prior to this routine returning.
2559 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
2560 char *zTail; /* Pointer to the last "_" in zName */
2561 Table *pTab; /* Table that zName is a shadow of */
2562 zTail = strrchr(zName, '_');
2563 if( zTail==0 ) return 0;
2564 *zTail = 0;
2565 pTab = sqlite3FindTable(db, zName, 0);
2566 *zTail = '_';
2567 if( pTab==0 ) return 0;
2568 if( !IsVirtual(pTab) ) return 0;
2569 return sqlite3IsShadowTableOf(db, pTab, zName);
2571 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2574 #ifdef SQLITE_DEBUG
2576 ** Mark all nodes of an expression as EP_Immutable, indicating that
2577 ** they should not be changed. Expressions attached to a table or
2578 ** index definition are tagged this way to help ensure that we do
2579 ** not pass them into code generator routines by mistake.
2581 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2582 (void)pWalker;
2583 ExprSetVVAProperty(pExpr, EP_Immutable);
2584 return WRC_Continue;
2586 static void markExprListImmutable(ExprList *pList){
2587 if( pList ){
2588 Walker w;
2589 memset(&w, 0, sizeof(w));
2590 w.xExprCallback = markImmutableExprStep;
2591 w.xSelectCallback = sqlite3SelectWalkNoop;
2592 w.xSelectCallback2 = 0;
2593 sqlite3WalkExprList(&w, pList);
2596 #else
2597 #define markExprListImmutable(X) /* no-op */
2598 #endif /* SQLITE_DEBUG */
2602 ** This routine is called to report the final ")" that terminates
2603 ** a CREATE TABLE statement.
2605 ** The table structure that other action routines have been building
2606 ** is added to the internal hash tables, assuming no errors have
2607 ** occurred.
2609 ** An entry for the table is made in the schema table on disk, unless
2610 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
2611 ** it means we are reading the sqlite_schema table because we just
2612 ** connected to the database or because the sqlite_schema table has
2613 ** recently changed, so the entry for this table already exists in
2614 ** the sqlite_schema table. We do not want to create it again.
2616 ** If the pSelect argument is not NULL, it means that this routine
2617 ** was called to create a table generated from a
2618 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2619 ** the new table will match the result set of the SELECT.
2621 void sqlite3EndTable(
2622 Parse *pParse, /* Parse context */
2623 Token *pCons, /* The ',' token after the last column defn. */
2624 Token *pEnd, /* The ')' before options in the CREATE TABLE */
2625 u32 tabOpts, /* Extra table options. Usually 0. */
2626 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
2628 Table *p; /* The new table */
2629 sqlite3 *db = pParse->db; /* The database connection */
2630 int iDb; /* Database in which the table lives */
2631 Index *pIdx; /* An implied index of the table */
2633 if( pEnd==0 && pSelect==0 ){
2634 return;
2636 p = pParse->pNewTable;
2637 if( p==0 ) return;
2639 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
2640 p->tabFlags |= TF_Shadow;
2643 /* If the db->init.busy is 1 it means we are reading the SQL off the
2644 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2645 ** So do not write to the disk again. Extract the root page number
2646 ** for the table from the db->init.newTnum field. (The page number
2647 ** should have been put there by the sqliteOpenCb routine.)
2649 ** If the root page number is 1, that means this is the sqlite_schema
2650 ** table itself. So mark it read-only.
2652 if( db->init.busy ){
2653 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
2654 sqlite3ErrorMsg(pParse, "");
2655 return;
2657 p->tnum = db->init.newTnum;
2658 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2661 /* Special processing for tables that include the STRICT keyword:
2663 ** * Do not allow custom column datatypes. Every column must have
2664 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
2666 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
2667 ** then all columns of the PRIMARY KEY must have a NOT NULL
2668 ** constraint.
2670 if( tabOpts & TF_Strict ){
2671 int ii;
2672 p->tabFlags |= TF_Strict;
2673 for(ii=0; ii<p->nCol; ii++){
2674 Column *pCol = &p->aCol[ii];
2675 if( pCol->eCType==COLTYPE_CUSTOM ){
2676 if( pCol->colFlags & COLFLAG_HASTYPE ){
2677 sqlite3ErrorMsg(pParse,
2678 "unknown datatype for %s.%s: \"%s\"",
2679 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
2681 }else{
2682 sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
2683 p->zName, pCol->zCnName);
2685 return;
2686 }else if( pCol->eCType==COLTYPE_ANY ){
2687 pCol->affinity = SQLITE_AFF_BLOB;
2689 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
2690 && p->iPKey!=ii
2691 && pCol->notNull == OE_None
2693 pCol->notNull = OE_Abort;
2694 p->tabFlags |= TF_HasNotNull;
2699 assert( (p->tabFlags & TF_HasPrimaryKey)==0
2700 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2701 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2702 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2704 /* Special processing for WITHOUT ROWID Tables */
2705 if( tabOpts & TF_WithoutRowid ){
2706 if( (p->tabFlags & TF_Autoincrement) ){
2707 sqlite3ErrorMsg(pParse,
2708 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2709 return;
2711 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2712 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2713 return;
2715 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2716 convertToWithoutRowidTable(pParse, p);
2718 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2720 #ifndef SQLITE_OMIT_CHECK
2721 /* Resolve names in all CHECK constraint expressions.
2723 if( p->pCheck ){
2724 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2725 if( pParse->nErr ){
2726 /* If errors are seen, delete the CHECK constraints now, else they might
2727 ** actually be used if PRAGMA writable_schema=ON is set. */
2728 sqlite3ExprListDelete(db, p->pCheck);
2729 p->pCheck = 0;
2730 }else{
2731 markExprListImmutable(p->pCheck);
2734 #endif /* !defined(SQLITE_OMIT_CHECK) */
2735 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2736 if( p->tabFlags & TF_HasGenerated ){
2737 int ii, nNG = 0;
2738 testcase( p->tabFlags & TF_HasVirtual );
2739 testcase( p->tabFlags & TF_HasStored );
2740 for(ii=0; ii<p->nCol; ii++){
2741 u32 colFlags = p->aCol[ii].colFlags;
2742 if( (colFlags & COLFLAG_GENERATED)!=0 ){
2743 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
2744 testcase( colFlags & COLFLAG_VIRTUAL );
2745 testcase( colFlags & COLFLAG_STORED );
2746 if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
2747 /* If there are errors in resolving the expression, change the
2748 ** expression to a NULL. This prevents code generators that operate
2749 ** on the expression from inserting extra parts into the expression
2750 ** tree that have been allocated from lookaside memory, which is
2751 ** illegal in a schema and will lead to errors or heap corruption
2752 ** when the database connection closes. */
2753 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
2754 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
2756 }else{
2757 nNG++;
2760 if( nNG==0 ){
2761 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
2762 return;
2765 #endif
2767 /* Estimate the average row size for the table and for all implied indices */
2768 estimateTableWidth(p);
2769 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2770 estimateIndexWidth(pIdx);
2773 /* If not initializing, then create a record for the new table
2774 ** in the schema table of the database.
2776 ** If this is a TEMPORARY table, write the entry into the auxiliary
2777 ** file instead of into the main database file.
2779 if( !db->init.busy ){
2780 int n;
2781 Vdbe *v;
2782 char *zType; /* "view" or "table" */
2783 char *zType2; /* "VIEW" or "TABLE" */
2784 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
2786 v = sqlite3GetVdbe(pParse);
2787 if( NEVER(v==0) ) return;
2789 sqlite3VdbeAddOp1(v, OP_Close, 0);
2792 ** Initialize zType for the new view or table.
2794 if( IsOrdinaryTable(p) ){
2795 /* A regular table */
2796 zType = "table";
2797 zType2 = "TABLE";
2798 #ifndef SQLITE_OMIT_VIEW
2799 }else{
2800 /* A view */
2801 zType = "view";
2802 zType2 = "VIEW";
2803 #endif
2806 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2807 ** statement to populate the new table. The root-page number for the
2808 ** new table is in register pParse->regRoot.
2810 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2811 ** suitable state to query for the column names and types to be used
2812 ** by the new table.
2814 ** A shared-cache write-lock is not required to write to the new table,
2815 ** as a schema-lock must have already been obtained to create it. Since
2816 ** a schema-lock excludes all other database users, the write-lock would
2817 ** be redundant.
2819 if( pSelect ){
2820 SelectDest dest; /* Where the SELECT should store results */
2821 int regYield; /* Register holding co-routine entry-point */
2822 int addrTop; /* Top of the co-routine */
2823 int regRec; /* A record to be insert into the new table */
2824 int regRowid; /* Rowid of the next row to insert */
2825 int addrInsLoop; /* Top of the loop for inserting rows */
2826 Table *pSelTab; /* A table that describes the SELECT results */
2828 if( IN_SPECIAL_PARSE ){
2829 pParse->rc = SQLITE_ERROR;
2830 pParse->nErr++;
2831 return;
2833 regYield = ++pParse->nMem;
2834 regRec = ++pParse->nMem;
2835 regRowid = ++pParse->nMem;
2836 assert(pParse->nTab==1);
2837 sqlite3MayAbort(pParse);
2838 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2839 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2840 pParse->nTab = 2;
2841 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2842 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2843 if( pParse->nErr ) return;
2844 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
2845 if( pSelTab==0 ) return;
2846 assert( p->aCol==0 );
2847 p->nCol = p->nNVCol = pSelTab->nCol;
2848 p->aCol = pSelTab->aCol;
2849 pSelTab->nCol = 0;
2850 pSelTab->aCol = 0;
2851 sqlite3DeleteTable(db, pSelTab);
2852 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2853 sqlite3Select(pParse, pSelect, &dest);
2854 if( pParse->nErr ) return;
2855 sqlite3VdbeEndCoroutine(v, regYield);
2856 sqlite3VdbeJumpHere(v, addrTop - 1);
2857 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2858 VdbeCoverage(v);
2859 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2860 sqlite3TableAffinity(v, p, 0);
2861 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2862 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2863 sqlite3VdbeGoto(v, addrInsLoop);
2864 sqlite3VdbeJumpHere(v, addrInsLoop);
2865 sqlite3VdbeAddOp1(v, OP_Close, 1);
2868 /* Compute the complete text of the CREATE statement */
2869 if( pSelect ){
2870 zStmt = createTableStmt(db, p);
2871 }else{
2872 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2873 n = (int)(pEnd2->z - pParse->sNameToken.z);
2874 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
2875 zStmt = sqlite3MPrintf(db,
2876 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2880 /* A slot for the record has already been allocated in the
2881 ** schema table. We just need to update that slot with all
2882 ** the information we've collected.
2884 sqlite3NestedParse(pParse,
2885 "UPDATE %Q." LEGACY_SCHEMA_TABLE
2886 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2887 " WHERE rowid=#%d",
2888 db->aDb[iDb].zDbSName,
2889 zType,
2890 p->zName,
2891 p->zName,
2892 pParse->regRoot,
2893 zStmt,
2894 pParse->regRowid
2896 sqlite3DbFree(db, zStmt);
2897 sqlite3ChangeCookie(pParse, iDb);
2899 #ifndef SQLITE_OMIT_AUTOINCREMENT
2900 /* Check to see if we need to create an sqlite_sequence table for
2901 ** keeping track of autoincrement keys.
2903 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
2904 Db *pDb = &db->aDb[iDb];
2905 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2906 if( pDb->pSchema->pSeqTab==0 ){
2907 sqlite3NestedParse(pParse,
2908 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2909 pDb->zDbSName
2913 #endif
2915 /* Reparse everything to update our internal data structures */
2916 sqlite3VdbeAddParseSchemaOp(v, iDb,
2917 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
2919 /* Test for cycles in generated columns and illegal expressions
2920 ** in CHECK constraints and in DEFAULT clauses. */
2921 if( p->tabFlags & TF_HasGenerated ){
2922 sqlite3VdbeAddOp4(v, OP_SqlExec, 1, 0, 0,
2923 sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
2924 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
2926 sqlite3VdbeAddOp4(v, OP_SqlExec, 1, 0, 0,
2927 sqlite3MPrintf(db, "PRAGMA \"%w\".integrity_check(%Q)",
2928 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
2931 /* Add the table to the in-memory representation of the database.
2933 if( db->init.busy ){
2934 Table *pOld;
2935 Schema *pSchema = p->pSchema;
2936 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2937 assert( HasRowid(p) || p->iPKey<0 );
2938 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
2939 if( pOld ){
2940 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
2941 sqlite3OomFault(db);
2942 return;
2944 pParse->pNewTable = 0;
2945 db->mDbFlags |= DBFLAG_SchemaChange;
2947 /* If this is the magic sqlite_sequence table used by autoincrement,
2948 ** then record a pointer to this table in the main database structure
2949 ** so that INSERT can find the table easily. */
2950 assert( !pParse->nested );
2951 #ifndef SQLITE_OMIT_AUTOINCREMENT
2952 if( strcmp(p->zName, "sqlite_sequence")==0 ){
2953 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2954 p->pSchema->pSeqTab = p;
2956 #endif
2959 #ifndef SQLITE_OMIT_ALTERTABLE
2960 if( !pSelect && IsOrdinaryTable(p) ){
2961 assert( pCons && pEnd );
2962 if( pCons->z==0 ){
2963 pCons = pEnd;
2965 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
2967 #endif
2970 #ifndef SQLITE_OMIT_VIEW
2972 ** The parser calls this routine in order to create a new VIEW
2974 void sqlite3CreateView(
2975 Parse *pParse, /* The parsing context */
2976 Token *pBegin, /* The CREATE token that begins the statement */
2977 Token *pName1, /* The token that holds the name of the view */
2978 Token *pName2, /* The token that holds the name of the view */
2979 ExprList *pCNames, /* Optional list of view column names */
2980 Select *pSelect, /* A SELECT statement that will become the new view */
2981 int isTemp, /* TRUE for a TEMPORARY view */
2982 int noErr /* Suppress error messages if VIEW already exists */
2984 Table *p;
2985 int n;
2986 const char *z;
2987 Token sEnd;
2988 DbFixer sFix;
2989 Token *pName = 0;
2990 int iDb;
2991 sqlite3 *db = pParse->db;
2993 if( pParse->nVar>0 ){
2994 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2995 goto create_view_fail;
2997 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2998 p = pParse->pNewTable;
2999 if( p==0 || pParse->nErr ) goto create_view_fail;
3001 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
3002 ** on a view, even though views do not have rowids. The following flag
3003 ** setting fixes this problem. But the fix can be disabled by compiling
3004 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
3005 ** depend upon the old buggy behavior. */
3006 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
3007 p->tabFlags |= TF_NoVisibleRowid;
3008 #endif
3010 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3011 iDb = sqlite3SchemaToIndex(db, p->pSchema);
3012 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
3013 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
3015 /* Make a copy of the entire SELECT statement that defines the view.
3016 ** This will force all the Expr.token.z values to be dynamically
3017 ** allocated rather than point to the input string - which means that
3018 ** they will persist after the current sqlite3_exec() call returns.
3020 pSelect->selFlags |= SF_View;
3021 if( IN_RENAME_OBJECT ){
3022 p->u.view.pSelect = pSelect;
3023 pSelect = 0;
3024 }else{
3025 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
3027 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
3028 p->eTabType = TABTYP_VIEW;
3029 if( db->mallocFailed ) goto create_view_fail;
3031 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
3032 ** the end.
3034 sEnd = pParse->sLastToken;
3035 assert( sEnd.z[0]!=0 || sEnd.n==0 );
3036 if( sEnd.z[0]!=';' ){
3037 sEnd.z += sEnd.n;
3039 sEnd.n = 0;
3040 n = (int)(sEnd.z - pBegin->z);
3041 assert( n>0 );
3042 z = pBegin->z;
3043 while( sqlite3Isspace(z[n-1]) ){ n--; }
3044 sEnd.z = &z[n-1];
3045 sEnd.n = 1;
3047 /* Use sqlite3EndTable() to add the view to the schema table */
3048 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
3050 create_view_fail:
3051 sqlite3SelectDelete(db, pSelect);
3052 if( IN_RENAME_OBJECT ){
3053 sqlite3RenameExprlistUnmap(pParse, pCNames);
3055 sqlite3ExprListDelete(db, pCNames);
3056 return;
3058 #endif /* SQLITE_OMIT_VIEW */
3060 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3062 ** The Table structure pTable is really a VIEW. Fill in the names of
3063 ** the columns of the view in the pTable structure. Return the number
3064 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
3066 static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
3067 Table *pSelTab; /* A fake table from which we get the result set */
3068 Select *pSel; /* Copy of the SELECT that implements the view */
3069 int nErr = 0; /* Number of errors encountered */
3070 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
3071 #ifndef SQLITE_OMIT_VIRTUALTABLE
3072 int rc;
3073 #endif
3074 #ifndef SQLITE_OMIT_AUTHORIZATION
3075 sqlite3_xauth xAuth; /* Saved xAuth pointer */
3076 #endif
3078 assert( pTable );
3080 #ifndef SQLITE_OMIT_VIRTUALTABLE
3081 if( IsVirtual(pTable) ){
3082 db->nSchemaLock++;
3083 rc = sqlite3VtabCallConnect(pParse, pTable);
3084 db->nSchemaLock--;
3085 return rc;
3087 #endif
3089 #ifndef SQLITE_OMIT_VIEW
3090 /* A positive nCol means the columns names for this view are
3091 ** already known. This routine is not called unless either the
3092 ** table is virtual or nCol is zero.
3094 assert( pTable->nCol<=0 );
3096 /* A negative nCol is a special marker meaning that we are currently
3097 ** trying to compute the column names. If we enter this routine with
3098 ** a negative nCol, it means two or more views form a loop, like this:
3100 ** CREATE VIEW one AS SELECT * FROM two;
3101 ** CREATE VIEW two AS SELECT * FROM one;
3103 ** Actually, the error above is now caught prior to reaching this point.
3104 ** But the following test is still important as it does come up
3105 ** in the following:
3107 ** CREATE TABLE main.ex1(a);
3108 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3109 ** SELECT * FROM temp.ex1;
3111 if( pTable->nCol<0 ){
3112 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
3113 return 1;
3115 assert( pTable->nCol>=0 );
3117 /* If we get this far, it means we need to compute the table names.
3118 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
3119 ** "*" elements in the results set of the view and will assign cursors
3120 ** to the elements of the FROM clause. But we do not want these changes
3121 ** to be permanent. So the computation is done on a copy of the SELECT
3122 ** statement that defines the view.
3124 assert( IsView(pTable) );
3125 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
3126 if( pSel ){
3127 u8 eParseMode = pParse->eParseMode;
3128 int nTab = pParse->nTab;
3129 int nSelect = pParse->nSelect;
3130 pParse->eParseMode = PARSE_MODE_NORMAL;
3131 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
3132 pTable->nCol = -1;
3133 DisableLookaside;
3134 #ifndef SQLITE_OMIT_AUTHORIZATION
3135 xAuth = db->xAuth;
3136 db->xAuth = 0;
3137 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3138 db->xAuth = xAuth;
3139 #else
3140 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3141 #endif
3142 pParse->nTab = nTab;
3143 pParse->nSelect = nSelect;
3144 if( pSelTab==0 ){
3145 pTable->nCol = 0;
3146 nErr++;
3147 }else if( pTable->pCheck ){
3148 /* CREATE VIEW name(arglist) AS ...
3149 ** The names of the columns in the table are taken from
3150 ** arglist which is stored in pTable->pCheck. The pCheck field
3151 ** normally holds CHECK constraints on an ordinary table, but for
3152 ** a VIEW it holds the list of column names.
3154 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
3155 &pTable->nCol, &pTable->aCol);
3156 if( pParse->nErr==0
3157 && pTable->nCol==pSel->pEList->nExpr
3159 assert( db->mallocFailed==0 );
3160 sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
3162 }else{
3163 /* CREATE VIEW name AS... without an argument list. Construct
3164 ** the column names from the SELECT statement that defines the view.
3166 assert( pTable->aCol==0 );
3167 pTable->nCol = pSelTab->nCol;
3168 pTable->aCol = pSelTab->aCol;
3169 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
3170 pSelTab->nCol = 0;
3171 pSelTab->aCol = 0;
3172 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
3174 pTable->nNVCol = pTable->nCol;
3175 sqlite3DeleteTable(db, pSelTab);
3176 sqlite3SelectDelete(db, pSel);
3177 EnableLookaside;
3178 pParse->eParseMode = eParseMode;
3179 } else {
3180 nErr++;
3182 pTable->pSchema->schemaFlags |= DB_UnresetViews;
3183 if( db->mallocFailed ){
3184 sqlite3DeleteColumnNames(db, pTable);
3186 #endif /* SQLITE_OMIT_VIEW */
3187 return nErr;
3189 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
3190 assert( pTable!=0 );
3191 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
3192 return viewGetColumnNames(pParse, pTable);
3194 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3196 #ifndef SQLITE_OMIT_VIEW
3198 ** Clear the column names from every VIEW in database idx.
3200 static void sqliteViewResetAll(sqlite3 *db, int idx){
3201 HashElem *i;
3202 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
3203 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
3204 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
3205 Table *pTab = sqliteHashData(i);
3206 if( IsView(pTab) ){
3207 sqlite3DeleteColumnNames(db, pTab);
3210 DbClearProperty(db, idx, DB_UnresetViews);
3212 #else
3213 # define sqliteViewResetAll(A,B)
3214 #endif /* SQLITE_OMIT_VIEW */
3217 ** This function is called by the VDBE to adjust the internal schema
3218 ** used by SQLite when the btree layer moves a table root page. The
3219 ** root-page of a table or index in database iDb has changed from iFrom
3220 ** to iTo.
3222 ** Ticket #1728: The symbol table might still contain information
3223 ** on tables and/or indices that are the process of being deleted.
3224 ** If you are unlucky, one of those deleted indices or tables might
3225 ** have the same rootpage number as the real table or index that is
3226 ** being moved. So we cannot stop searching after the first match
3227 ** because the first match might be for one of the deleted indices
3228 ** or tables and not the table/index that is actually being moved.
3229 ** We must continue looping until all tables and indices with
3230 ** rootpage==iFrom have been converted to have a rootpage of iTo
3231 ** in order to be certain that we got the right one.
3233 #ifndef SQLITE_OMIT_AUTOVACUUM
3234 void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
3235 HashElem *pElem;
3236 Hash *pHash;
3237 Db *pDb;
3239 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3240 pDb = &db->aDb[iDb];
3241 pHash = &pDb->pSchema->tblHash;
3242 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3243 Table *pTab = sqliteHashData(pElem);
3244 if( pTab->tnum==iFrom ){
3245 pTab->tnum = iTo;
3248 pHash = &pDb->pSchema->idxHash;
3249 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3250 Index *pIdx = sqliteHashData(pElem);
3251 if( pIdx->tnum==iFrom ){
3252 pIdx->tnum = iTo;
3256 #endif
3259 ** Write code to erase the table with root-page iTable from database iDb.
3260 ** Also write code to modify the sqlite_schema table and internal schema
3261 ** if a root-page of another table is moved by the btree-layer whilst
3262 ** erasing iTable (this can happen with an auto-vacuum database).
3264 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
3265 Vdbe *v = sqlite3GetVdbe(pParse);
3266 int r1 = sqlite3GetTempReg(pParse);
3267 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
3268 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
3269 sqlite3MayAbort(pParse);
3270 #ifndef SQLITE_OMIT_AUTOVACUUM
3271 /* OP_Destroy stores an in integer r1. If this integer
3272 ** is non-zero, then it is the root page number of a table moved to
3273 ** location iTable. The following code modifies the sqlite_schema table to
3274 ** reflect this.
3276 ** The "#NNN" in the SQL is a special constant that means whatever value
3277 ** is in register NNN. See grammar rules associated with the TK_REGISTER
3278 ** token for additional information.
3280 sqlite3NestedParse(pParse,
3281 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3282 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3283 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
3284 #endif
3285 sqlite3ReleaseTempReg(pParse, r1);
3289 ** Write VDBE code to erase table pTab and all associated indices on disk.
3290 ** Code to update the sqlite_schema tables and internal schema definitions
3291 ** in case a root-page belonging to another table is moved by the btree layer
3292 ** is also added (this can happen with an auto-vacuum database).
3294 static void destroyTable(Parse *pParse, Table *pTab){
3295 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3296 ** is not defined), then it is important to call OP_Destroy on the
3297 ** table and index root-pages in order, starting with the numerically
3298 ** largest root-page number. This guarantees that none of the root-pages
3299 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3300 ** following were coded:
3302 ** OP_Destroy 4 0
3303 ** ...
3304 ** OP_Destroy 5 0
3306 ** and root page 5 happened to be the largest root-page number in the
3307 ** database, then root page 5 would be moved to page 4 by the
3308 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3309 ** a free-list page.
3311 Pgno iTab = pTab->tnum;
3312 Pgno iDestroyed = 0;
3314 while( 1 ){
3315 Index *pIdx;
3316 Pgno iLargest = 0;
3318 if( iDestroyed==0 || iTab<iDestroyed ){
3319 iLargest = iTab;
3321 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3322 Pgno iIdx = pIdx->tnum;
3323 assert( pIdx->pSchema==pTab->pSchema );
3324 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
3325 iLargest = iIdx;
3328 if( iLargest==0 ){
3329 return;
3330 }else{
3331 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3332 assert( iDb>=0 && iDb<pParse->db->nDb );
3333 destroyRootPage(pParse, iLargest, iDb);
3334 iDestroyed = iLargest;
3340 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3341 ** after a DROP INDEX or DROP TABLE command.
3343 static void sqlite3ClearStatTables(
3344 Parse *pParse, /* The parsing context */
3345 int iDb, /* The database number */
3346 const char *zType, /* "idx" or "tbl" */
3347 const char *zName /* Name of index or table */
3349 int i;
3350 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
3351 for(i=1; i<=4; i++){
3352 char zTab[24];
3353 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
3354 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
3355 sqlite3NestedParse(pParse,
3356 "DELETE FROM %Q.%s WHERE %s=%Q",
3357 zDbName, zTab, zType, zName
3364 ** Generate code to drop a table.
3366 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
3367 Vdbe *v;
3368 sqlite3 *db = pParse->db;
3369 Trigger *pTrigger;
3370 Db *pDb = &db->aDb[iDb];
3372 v = sqlite3GetVdbe(pParse);
3373 assert( v!=0 );
3374 sqlite3BeginWriteOperation(pParse, 1, iDb);
3376 #ifndef SQLITE_OMIT_VIRTUALTABLE
3377 if( IsVirtual(pTab) ){
3378 sqlite3VdbeAddOp0(v, OP_VBegin);
3380 #endif
3382 /* Drop all triggers associated with the table being dropped. Code
3383 ** is generated to remove entries from sqlite_schema and/or
3384 ** sqlite_temp_schema if required.
3386 pTrigger = sqlite3TriggerList(pParse, pTab);
3387 while( pTrigger ){
3388 assert( pTrigger->pSchema==pTab->pSchema ||
3389 pTrigger->pSchema==db->aDb[1].pSchema );
3390 sqlite3DropTriggerPtr(pParse, pTrigger);
3391 pTrigger = pTrigger->pNext;
3394 #ifndef SQLITE_OMIT_AUTOINCREMENT
3395 /* Remove any entries of the sqlite_sequence table associated with
3396 ** the table being dropped. This is done before the table is dropped
3397 ** at the btree level, in case the sqlite_sequence table needs to
3398 ** move as a result of the drop (can happen in auto-vacuum mode).
3400 if( pTab->tabFlags & TF_Autoincrement ){
3401 sqlite3NestedParse(pParse,
3402 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3403 pDb->zDbSName, pTab->zName
3406 #endif
3408 /* Drop all entries in the schema table that refer to the
3409 ** table. The program name loops through the schema table and deletes
3410 ** every row that refers to a table of the same name as the one being
3411 ** dropped. Triggers are handled separately because a trigger can be
3412 ** created in the temp database that refers to a table in another
3413 ** database.
3415 sqlite3NestedParse(pParse,
3416 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3417 " WHERE tbl_name=%Q and type!='trigger'",
3418 pDb->zDbSName, pTab->zName);
3419 if( !isView && !IsVirtual(pTab) ){
3420 destroyTable(pParse, pTab);
3423 /* Remove the table entry from SQLite's internal schema and modify
3424 ** the schema cookie.
3426 if( IsVirtual(pTab) ){
3427 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
3428 sqlite3MayAbort(pParse);
3430 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
3431 sqlite3ChangeCookie(pParse, iDb);
3432 sqliteViewResetAll(db, iDb);
3436 ** Return TRUE if shadow tables should be read-only in the current
3437 ** context.
3439 int sqlite3ReadOnlyShadowTables(sqlite3 *db){
3440 #ifndef SQLITE_OMIT_VIRTUALTABLE
3441 if( (db->flags & SQLITE_Defensive)!=0
3442 && db->pVtabCtx==0
3443 && db->nVdbeExec==0
3444 && !sqlite3VtabInSync(db)
3446 return 1;
3448 #endif
3449 return 0;
3453 ** Return true if it is not allowed to drop the given table
3455 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
3456 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
3457 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
3458 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
3459 return 1;
3461 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
3462 return 1;
3464 if( pTab->tabFlags & TF_Eponymous ){
3465 return 1;
3467 return 0;
3471 ** This routine is called to do the work of a DROP TABLE statement.
3472 ** pName is the name of the table to be dropped.
3474 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3475 Table *pTab;
3476 Vdbe *v;
3477 sqlite3 *db = pParse->db;
3478 int iDb;
3480 if( db->mallocFailed ){
3481 goto exit_drop_table;
3483 assert( pParse->nErr==0 );
3484 assert( pName->nSrc==1 );
3485 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3486 if( noErr ) db->suppressErr++;
3487 assert( isView==0 || isView==LOCATE_VIEW );
3488 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3489 if( noErr ) db->suppressErr--;
3491 if( pTab==0 ){
3492 if( noErr ){
3493 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3494 sqlite3ForceNotReadOnly(pParse);
3496 goto exit_drop_table;
3498 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3499 assert( iDb>=0 && iDb<db->nDb );
3501 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3502 ** it is initialized.
3504 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3505 goto exit_drop_table;
3507 #ifndef SQLITE_OMIT_AUTHORIZATION
3509 int code;
3510 const char *zTab = SCHEMA_TABLE(iDb);
3511 const char *zDb = db->aDb[iDb].zDbSName;
3512 const char *zArg2 = 0;
3513 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3514 goto exit_drop_table;
3516 if( isView ){
3517 if( !OMIT_TEMPDB && iDb==1 ){
3518 code = SQLITE_DROP_TEMP_VIEW;
3519 }else{
3520 code = SQLITE_DROP_VIEW;
3522 #ifndef SQLITE_OMIT_VIRTUALTABLE
3523 }else if( IsVirtual(pTab) ){
3524 code = SQLITE_DROP_VTABLE;
3525 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
3526 #endif
3527 }else{
3528 if( !OMIT_TEMPDB && iDb==1 ){
3529 code = SQLITE_DROP_TEMP_TABLE;
3530 }else{
3531 code = SQLITE_DROP_TABLE;
3534 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3535 goto exit_drop_table;
3537 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3538 goto exit_drop_table;
3541 #endif
3542 if( tableMayNotBeDropped(db, pTab) ){
3543 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3544 goto exit_drop_table;
3547 #ifndef SQLITE_OMIT_VIEW
3548 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3549 ** on a table.
3551 if( isView && !IsView(pTab) ){
3552 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3553 goto exit_drop_table;
3555 if( !isView && IsView(pTab) ){
3556 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3557 goto exit_drop_table;
3559 #endif
3561 /* Generate code to remove the table from the schema table
3562 ** on disk.
3564 v = sqlite3GetVdbe(pParse);
3565 if( v ){
3566 sqlite3BeginWriteOperation(pParse, 1, iDb);
3567 if( !isView ){
3568 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3569 sqlite3FkDropTable(pParse, pName, pTab);
3571 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
3574 exit_drop_table:
3575 sqlite3SrcListDelete(db, pName);
3579 ** This routine is called to create a new foreign key on the table
3580 ** currently under construction. pFromCol determines which columns
3581 ** in the current table point to the foreign key. If pFromCol==0 then
3582 ** connect the key to the last column inserted. pTo is the name of
3583 ** the table referred to (a.k.a the "parent" table). pToCol is a list
3584 ** of tables in the parent pTo table. flags contains all
3585 ** information about the conflict resolution algorithms specified
3586 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3588 ** An FKey structure is created and added to the table currently
3589 ** under construction in the pParse->pNewTable field.
3591 ** The foreign key is set for IMMEDIATE processing. A subsequent call
3592 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3594 void sqlite3CreateForeignKey(
3595 Parse *pParse, /* Parsing context */
3596 ExprList *pFromCol, /* Columns in this table that point to other table */
3597 Token *pTo, /* Name of the other table */
3598 ExprList *pToCol, /* Columns in the other table */
3599 int flags /* Conflict resolution algorithms. */
3601 sqlite3 *db = pParse->db;
3602 #ifndef SQLITE_OMIT_FOREIGN_KEY
3603 FKey *pFKey = 0;
3604 FKey *pNextTo;
3605 Table *p = pParse->pNewTable;
3606 i64 nByte;
3607 int i;
3608 int nCol;
3609 char *z;
3611 assert( pTo!=0 );
3612 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3613 if( pFromCol==0 ){
3614 int iCol = p->nCol-1;
3615 if( NEVER(iCol<0) ) goto fk_end;
3616 if( pToCol && pToCol->nExpr!=1 ){
3617 sqlite3ErrorMsg(pParse, "foreign key on %s"
3618 " should reference only one column of table %T",
3619 p->aCol[iCol].zCnName, pTo);
3620 goto fk_end;
3622 nCol = 1;
3623 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
3624 sqlite3ErrorMsg(pParse,
3625 "number of columns in foreign key does not match the number of "
3626 "columns in the referenced table");
3627 goto fk_end;
3628 }else{
3629 nCol = pFromCol->nExpr;
3631 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
3632 if( pToCol ){
3633 for(i=0; i<pToCol->nExpr; i++){
3634 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3637 pFKey = sqlite3DbMallocZero(db, nByte );
3638 if( pFKey==0 ){
3639 goto fk_end;
3641 pFKey->pFrom = p;
3642 assert( IsOrdinaryTable(p) );
3643 pFKey->pNextFrom = p->u.tab.pFKey;
3644 z = (char*)&pFKey->aCol[nCol];
3645 pFKey->zTo = z;
3646 if( IN_RENAME_OBJECT ){
3647 sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3649 memcpy(z, pTo->z, pTo->n);
3650 z[pTo->n] = 0;
3651 sqlite3Dequote(z);
3652 z += pTo->n+1;
3653 pFKey->nCol = nCol;
3654 if( pFromCol==0 ){
3655 pFKey->aCol[0].iFrom = p->nCol-1;
3656 }else{
3657 for(i=0; i<nCol; i++){
3658 int j;
3659 for(j=0; j<p->nCol; j++){
3660 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
3661 pFKey->aCol[i].iFrom = j;
3662 break;
3665 if( j>=p->nCol ){
3666 sqlite3ErrorMsg(pParse,
3667 "unknown column \"%s\" in foreign key definition",
3668 pFromCol->a[i].zEName);
3669 goto fk_end;
3671 if( IN_RENAME_OBJECT ){
3672 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3676 if( pToCol ){
3677 for(i=0; i<nCol; i++){
3678 int n = sqlite3Strlen30(pToCol->a[i].zEName);
3679 pFKey->aCol[i].zCol = z;
3680 if( IN_RENAME_OBJECT ){
3681 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
3683 memcpy(z, pToCol->a[i].zEName, n);
3684 z[n] = 0;
3685 z += n+1;
3688 pFKey->isDeferred = 0;
3689 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
3690 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
3692 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
3693 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3694 pFKey->zTo, (void *)pFKey
3696 if( pNextTo==pFKey ){
3697 sqlite3OomFault(db);
3698 goto fk_end;
3700 if( pNextTo ){
3701 assert( pNextTo->pPrevTo==0 );
3702 pFKey->pNextTo = pNextTo;
3703 pNextTo->pPrevTo = pFKey;
3706 /* Link the foreign key to the table as the last step.
3708 assert( IsOrdinaryTable(p) );
3709 p->u.tab.pFKey = pFKey;
3710 pFKey = 0;
3712 fk_end:
3713 sqlite3DbFree(db, pFKey);
3714 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3715 sqlite3ExprListDelete(db, pFromCol);
3716 sqlite3ExprListDelete(db, pToCol);
3720 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3721 ** clause is seen as part of a foreign key definition. The isDeferred
3722 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3723 ** The behavior of the most recently created foreign key is adjusted
3724 ** accordingly.
3726 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3727 #ifndef SQLITE_OMIT_FOREIGN_KEY
3728 Table *pTab;
3729 FKey *pFKey;
3730 if( (pTab = pParse->pNewTable)==0 ) return;
3731 if( NEVER(!IsOrdinaryTable(pTab)) ) return;
3732 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
3733 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3734 pFKey->isDeferred = (u8)isDeferred;
3735 #endif
3739 ** Generate code that will erase and refill index *pIdx. This is
3740 ** used to initialize a newly created index or to recompute the
3741 ** content of an index in response to a REINDEX command.
3743 ** if memRootPage is not negative, it means that the index is newly
3744 ** created. The register specified by memRootPage contains the
3745 ** root page number of the index. If memRootPage is negative, then
3746 ** the index already exists and must be cleared before being refilled and
3747 ** the root page number of the index is taken from pIndex->tnum.
3749 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3750 Table *pTab = pIndex->pTable; /* The table that is indexed */
3751 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
3752 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
3753 int iSorter; /* Cursor opened by OpenSorter (if in use) */
3754 int addr1; /* Address of top of loop */
3755 int addr2; /* Address to jump to for next iteration */
3756 Pgno tnum; /* Root page of index */
3757 int iPartIdxLabel; /* Jump to this label to skip a row */
3758 Vdbe *v; /* Generate code into this virtual machine */
3759 KeyInfo *pKey; /* KeyInfo for index */
3760 int regRecord; /* Register holding assembled index record */
3761 sqlite3 *db = pParse->db; /* The database connection */
3762 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3764 #ifndef SQLITE_OMIT_AUTHORIZATION
3765 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3766 db->aDb[iDb].zDbSName ) ){
3767 return;
3769 #endif
3771 /* Require a write-lock on the table to perform this operation */
3772 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3774 v = sqlite3GetVdbe(pParse);
3775 if( v==0 ) return;
3776 if( memRootPage>=0 ){
3777 tnum = (Pgno)memRootPage;
3778 }else{
3779 tnum = pIndex->tnum;
3781 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3782 assert( pKey!=0 || pParse->nErr );
3784 /* Open the sorter cursor if we are to use one. */
3785 iSorter = pParse->nTab++;
3786 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3787 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3789 /* Open the table. Loop through all rows of the table, inserting index
3790 ** records into the sorter. */
3791 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3792 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3793 regRecord = sqlite3GetTempReg(pParse);
3794 sqlite3MultiWrite(pParse);
3796 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3797 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3798 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3799 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3800 sqlite3VdbeJumpHere(v, addr1);
3801 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3802 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
3803 (char *)pKey, P4_KEYINFO);
3804 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3806 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3807 if( IsUniqueIndex(pIndex) ){
3808 int j2 = sqlite3VdbeGoto(v, 1);
3809 addr2 = sqlite3VdbeCurrentAddr(v);
3810 sqlite3VdbeVerifyAbortable(v, OE_Abort);
3811 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3812 pIndex->nKeyCol); VdbeCoverage(v);
3813 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3814 sqlite3VdbeJumpHere(v, j2);
3815 }else{
3816 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3817 ** abort. The exception is if one of the indexed expressions contains a
3818 ** user function that throws an exception when it is evaluated. But the
3819 ** overhead of adding a statement journal to a CREATE INDEX statement is
3820 ** very small (since most of the pages written do not contain content that
3821 ** needs to be restored if the statement aborts), so we call
3822 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3823 sqlite3MayAbort(pParse);
3824 addr2 = sqlite3VdbeCurrentAddr(v);
3826 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3827 if( !pIndex->bAscKeyBug ){
3828 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3829 ** faster by avoiding unnecessary seeks. But the optimization does
3830 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3831 ** with DESC primary keys, since those indexes have there keys in
3832 ** a different order from the main table.
3833 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3835 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3837 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3838 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3839 sqlite3ReleaseTempReg(pParse, regRecord);
3840 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3841 sqlite3VdbeJumpHere(v, addr1);
3843 sqlite3VdbeAddOp1(v, OP_Close, iTab);
3844 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3845 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3849 ** Allocate heap space to hold an Index object with nCol columns.
3851 ** Increase the allocation size to provide an extra nExtra bytes
3852 ** of 8-byte aligned space after the Index object and return a
3853 ** pointer to this extra space in *ppExtra.
3855 Index *sqlite3AllocateIndexObject(
3856 sqlite3 *db, /* Database connection */
3857 i16 nCol, /* Total number of columns in the index */
3858 int nExtra, /* Number of bytes of extra space to alloc */
3859 char **ppExtra /* Pointer to the "extra" space */
3861 Index *p; /* Allocated index object */
3862 int nByte; /* Bytes of space for Index object + arrays */
3864 nByte = ROUND8(sizeof(Index)) + /* Index structure */
3865 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
3866 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
3867 sizeof(i16)*nCol + /* Index.aiColumn */
3868 sizeof(u8)*nCol); /* Index.aSortOrder */
3869 p = sqlite3DbMallocZero(db, nByte + nExtra);
3870 if( p ){
3871 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3872 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3873 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3874 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
3875 p->aSortOrder = (u8*)pExtra;
3876 p->nColumn = nCol;
3877 p->nKeyCol = nCol - 1;
3878 *ppExtra = ((char*)p) + nByte;
3880 return p;
3884 ** If expression list pList contains an expression that was parsed with
3885 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3886 ** pParse and return non-zero. Otherwise, return zero.
3888 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
3889 if( pList ){
3890 int i;
3891 for(i=0; i<pList->nExpr; i++){
3892 if( pList->a[i].fg.bNulls ){
3893 u8 sf = pList->a[i].fg.sortFlags;
3894 sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
3895 (sf==0 || sf==3) ? "FIRST" : "LAST"
3897 return 1;
3901 return 0;
3905 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
3906 ** and pTblList is the name of the table that is to be indexed. Both will
3907 ** be NULL for a primary key or an index that is created to satisfy a
3908 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
3909 ** as the table to be indexed. pParse->pNewTable is a table that is
3910 ** currently being constructed by a CREATE TABLE statement.
3912 ** pList is a list of columns to be indexed. pList will be NULL if this
3913 ** is a primary key or unique-constraint on the most recent column added
3914 ** to the table currently under construction.
3916 void sqlite3CreateIndex(
3917 Parse *pParse, /* All information about this parse */
3918 Token *pName1, /* First part of index name. May be NULL */
3919 Token *pName2, /* Second part of index name. May be NULL */
3920 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3921 ExprList *pList, /* A list of columns to be indexed */
3922 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3923 Token *pStart, /* The CREATE token that begins this statement */
3924 Expr *pPIWhere, /* WHERE clause for partial indices */
3925 int sortOrder, /* Sort order of primary key when pList==NULL */
3926 int ifNotExist, /* Omit error if index already exists */
3927 u8 idxType /* The index type */
3929 Table *pTab = 0; /* Table to be indexed */
3930 Index *pIndex = 0; /* The index to be created */
3931 char *zName = 0; /* Name of the index */
3932 int nName; /* Number of characters in zName */
3933 int i, j;
3934 DbFixer sFix; /* For assigning database names to pTable */
3935 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
3936 sqlite3 *db = pParse->db;
3937 Db *pDb; /* The specific table containing the indexed database */
3938 int iDb; /* Index of the database that is being written */
3939 Token *pName = 0; /* Unqualified name of the index to create */
3940 struct ExprList_item *pListItem; /* For looping over pList */
3941 int nExtra = 0; /* Space allocated for zExtra[] */
3942 int nExtraCol; /* Number of extra columns needed */
3943 char *zExtra = 0; /* Extra space after the Index object */
3944 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
3946 assert( db->pParse==pParse );
3947 if( pParse->nErr ){
3948 goto exit_create_index;
3950 assert( db->mallocFailed==0 );
3951 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3952 goto exit_create_index;
3954 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3955 goto exit_create_index;
3957 if( sqlite3HasExplicitNulls(pParse, pList) ){
3958 goto exit_create_index;
3962 ** Find the table that is to be indexed. Return early if not found.
3964 if( pTblName!=0 ){
3966 /* Use the two-part index name to determine the database
3967 ** to search for the table. 'Fix' the table name to this db
3968 ** before looking up the table.
3970 assert( pName1 && pName2 );
3971 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3972 if( iDb<0 ) goto exit_create_index;
3973 assert( pName && pName->z );
3975 #ifndef SQLITE_OMIT_TEMPDB
3976 /* If the index name was unqualified, check if the table
3977 ** is a temp table. If so, set the database to 1. Do not do this
3978 ** if initializing a database schema.
3980 if( !db->init.busy ){
3981 pTab = sqlite3SrcListLookup(pParse, pTblName);
3982 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3983 iDb = 1;
3986 #endif
3988 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3989 if( sqlite3FixSrcList(&sFix, pTblName) ){
3990 /* Because the parser constructs pTblName from a single identifier,
3991 ** sqlite3FixSrcList can never fail. */
3992 assert(0);
3994 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3995 assert( db->mallocFailed==0 || pTab==0 );
3996 if( pTab==0 ) goto exit_create_index;
3997 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3998 sqlite3ErrorMsg(pParse,
3999 "cannot create a TEMP index on non-TEMP table \"%s\"",
4000 pTab->zName);
4001 goto exit_create_index;
4003 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
4004 }else{
4005 assert( pName==0 );
4006 assert( pStart==0 );
4007 pTab = pParse->pNewTable;
4008 if( !pTab ) goto exit_create_index;
4009 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4011 pDb = &db->aDb[iDb];
4013 assert( pTab!=0 );
4014 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
4015 && db->init.busy==0
4016 && pTblName!=0
4017 #if SQLITE_USER_AUTHENTICATION
4018 && sqlite3UserAuthTable(pTab->zName)==0
4019 #endif
4021 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
4022 goto exit_create_index;
4024 #ifndef SQLITE_OMIT_VIEW
4025 if( IsView(pTab) ){
4026 sqlite3ErrorMsg(pParse, "views may not be indexed");
4027 goto exit_create_index;
4029 #endif
4030 #ifndef SQLITE_OMIT_VIRTUALTABLE
4031 if( IsVirtual(pTab) ){
4032 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
4033 goto exit_create_index;
4035 #endif
4038 ** Find the name of the index. Make sure there is not already another
4039 ** index or table with the same name.
4041 ** Exception: If we are reading the names of permanent indices from the
4042 ** sqlite_schema table (because some other process changed the schema) and
4043 ** one of the index names collides with the name of a temporary table or
4044 ** index, then we will continue to process this index.
4046 ** If pName==0 it means that we are
4047 ** dealing with a primary key or UNIQUE constraint. We have to invent our
4048 ** own name.
4050 if( pName ){
4051 zName = sqlite3NameFromToken(db, pName);
4052 if( zName==0 ) goto exit_create_index;
4053 assert( pName->z!=0 );
4054 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
4055 goto exit_create_index;
4057 if( !IN_RENAME_OBJECT ){
4058 if( !db->init.busy ){
4059 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
4060 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
4061 goto exit_create_index;
4064 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
4065 if( !ifNotExist ){
4066 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
4067 }else{
4068 assert( !db->init.busy );
4069 sqlite3CodeVerifySchema(pParse, iDb);
4070 sqlite3ForceNotReadOnly(pParse);
4072 goto exit_create_index;
4075 }else{
4076 int n;
4077 Index *pLoop;
4078 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
4079 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
4080 if( zName==0 ){
4081 goto exit_create_index;
4084 /* Automatic index names generated from within sqlite3_declare_vtab()
4085 ** must have names that are distinct from normal automatic index names.
4086 ** The following statement converts "sqlite3_autoindex..." into
4087 ** "sqlite3_butoindex..." in order to make the names distinct.
4088 ** The "vtab_err.test" test demonstrates the need of this statement. */
4089 if( IN_SPECIAL_PARSE ) zName[7]++;
4092 /* Check for authorization to create an index.
4094 #ifndef SQLITE_OMIT_AUTHORIZATION
4095 if( !IN_RENAME_OBJECT ){
4096 const char *zDb = pDb->zDbSName;
4097 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
4098 goto exit_create_index;
4100 i = SQLITE_CREATE_INDEX;
4101 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
4102 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
4103 goto exit_create_index;
4106 #endif
4108 /* If pList==0, it means this routine was called to make a primary
4109 ** key out of the last column added to the table under construction.
4110 ** So create a fake list to simulate this.
4112 if( pList==0 ){
4113 Token prevCol;
4114 Column *pCol = &pTab->aCol[pTab->nCol-1];
4115 pCol->colFlags |= COLFLAG_UNIQUE;
4116 sqlite3TokenInit(&prevCol, pCol->zCnName);
4117 pList = sqlite3ExprListAppend(pParse, 0,
4118 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
4119 if( pList==0 ) goto exit_create_index;
4120 assert( pList->nExpr==1 );
4121 sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
4122 }else{
4123 sqlite3ExprListCheckLength(pParse, pList, "index");
4124 if( pParse->nErr ) goto exit_create_index;
4127 /* Figure out how many bytes of space are required to store explicitly
4128 ** specified collation sequence names.
4130 for(i=0; i<pList->nExpr; i++){
4131 Expr *pExpr = pList->a[i].pExpr;
4132 assert( pExpr!=0 );
4133 if( pExpr->op==TK_COLLATE ){
4134 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4135 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
4140 ** Allocate the index structure.
4142 nName = sqlite3Strlen30(zName);
4143 nExtraCol = pPk ? pPk->nKeyCol : 1;
4144 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
4145 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
4146 nName + nExtra + 1, &zExtra);
4147 if( db->mallocFailed ){
4148 goto exit_create_index;
4150 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
4151 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
4152 pIndex->zName = zExtra;
4153 zExtra += nName + 1;
4154 memcpy(pIndex->zName, zName, nName+1);
4155 pIndex->pTable = pTab;
4156 pIndex->onError = (u8)onError;
4157 pIndex->uniqNotNull = onError!=OE_None;
4158 pIndex->idxType = idxType;
4159 pIndex->pSchema = db->aDb[iDb].pSchema;
4160 pIndex->nKeyCol = pList->nExpr;
4161 if( pPIWhere ){
4162 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
4163 pIndex->pPartIdxWhere = pPIWhere;
4164 pPIWhere = 0;
4166 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4168 /* Check to see if we should honor DESC requests on index columns
4170 if( pDb->pSchema->file_format>=4 ){
4171 sortOrderMask = -1; /* Honor DESC */
4172 }else{
4173 sortOrderMask = 0; /* Ignore DESC */
4176 /* Analyze the list of expressions that form the terms of the index and
4177 ** report any errors. In the common case where the expression is exactly
4178 ** a table column, store that column in aiColumn[]. For general expressions,
4179 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4181 ** TODO: Issue a warning if two or more columns of the index are identical.
4182 ** TODO: Issue a warning if the table primary key is used as part of the
4183 ** index key.
4185 pListItem = pList->a;
4186 if( IN_RENAME_OBJECT ){
4187 pIndex->aColExpr = pList;
4188 pList = 0;
4190 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
4191 Expr *pCExpr; /* The i-th index expression */
4192 int requestedSortOrder; /* ASC or DESC on the i-th expression */
4193 const char *zColl; /* Collation sequence name */
4195 sqlite3StringToId(pListItem->pExpr);
4196 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
4197 if( pParse->nErr ) goto exit_create_index;
4198 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
4199 if( pCExpr->op!=TK_COLUMN ){
4200 if( pTab==pParse->pNewTable ){
4201 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
4202 "UNIQUE constraints");
4203 goto exit_create_index;
4205 if( pIndex->aColExpr==0 ){
4206 pIndex->aColExpr = pList;
4207 pList = 0;
4209 j = XN_EXPR;
4210 pIndex->aiColumn[i] = XN_EXPR;
4211 pIndex->uniqNotNull = 0;
4212 pIndex->bHasExpr = 1;
4213 }else{
4214 j = pCExpr->iColumn;
4215 assert( j<=0x7fff );
4216 if( j<0 ){
4217 j = pTab->iPKey;
4218 }else{
4219 if( pTab->aCol[j].notNull==0 ){
4220 pIndex->uniqNotNull = 0;
4222 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
4223 pIndex->bHasVCol = 1;
4224 pIndex->bHasExpr = 1;
4227 pIndex->aiColumn[i] = (i16)j;
4229 zColl = 0;
4230 if( pListItem->pExpr->op==TK_COLLATE ){
4231 int nColl;
4232 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
4233 zColl = pListItem->pExpr->u.zToken;
4234 nColl = sqlite3Strlen30(zColl) + 1;
4235 assert( nExtra>=nColl );
4236 memcpy(zExtra, zColl, nColl);
4237 zColl = zExtra;
4238 zExtra += nColl;
4239 nExtra -= nColl;
4240 }else if( j>=0 ){
4241 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
4243 if( !zColl ) zColl = sqlite3StrBINARY;
4244 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
4245 goto exit_create_index;
4247 pIndex->azColl[i] = zColl;
4248 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
4249 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
4252 /* Append the table key to the end of the index. For WITHOUT ROWID
4253 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
4254 ** normal tables (when pPk==0) this will be the rowid.
4256 if( pPk ){
4257 for(j=0; j<pPk->nKeyCol; j++){
4258 int x = pPk->aiColumn[j];
4259 assert( x>=0 );
4260 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
4261 pIndex->nColumn--;
4262 }else{
4263 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
4264 pIndex->aiColumn[i] = x;
4265 pIndex->azColl[i] = pPk->azColl[j];
4266 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
4267 i++;
4270 assert( i==pIndex->nColumn );
4271 }else{
4272 pIndex->aiColumn[i] = XN_ROWID;
4273 pIndex->azColl[i] = sqlite3StrBINARY;
4275 sqlite3DefaultRowEst(pIndex);
4276 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
4278 /* If this index contains every column of its table, then mark
4279 ** it as a covering index */
4280 assert( HasRowid(pTab)
4281 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
4282 recomputeColumnsNotIndexed(pIndex);
4283 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
4284 pIndex->isCovering = 1;
4285 for(j=0; j<pTab->nCol; j++){
4286 if( j==pTab->iPKey ) continue;
4287 if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
4288 pIndex->isCovering = 0;
4289 break;
4293 if( pTab==pParse->pNewTable ){
4294 /* This routine has been called to create an automatic index as a
4295 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4296 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4297 ** i.e. one of:
4299 ** CREATE TABLE t(x PRIMARY KEY, y);
4300 ** CREATE TABLE t(x, y, UNIQUE(x, y));
4302 ** Either way, check to see if the table already has such an index. If
4303 ** so, don't bother creating this one. This only applies to
4304 ** automatically created indices. Users can do as they wish with
4305 ** explicit indices.
4307 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4308 ** (and thus suppressing the second one) even if they have different
4309 ** sort orders.
4311 ** If there are different collating sequences or if the columns of
4312 ** the constraint occur in different orders, then the constraints are
4313 ** considered distinct and both result in separate indices.
4315 Index *pIdx;
4316 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4317 int k;
4318 assert( IsUniqueIndex(pIdx) );
4319 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
4320 assert( IsUniqueIndex(pIndex) );
4322 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
4323 for(k=0; k<pIdx->nKeyCol; k++){
4324 const char *z1;
4325 const char *z2;
4326 assert( pIdx->aiColumn[k]>=0 );
4327 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
4328 z1 = pIdx->azColl[k];
4329 z2 = pIndex->azColl[k];
4330 if( sqlite3StrICmp(z1, z2) ) break;
4332 if( k==pIdx->nKeyCol ){
4333 if( pIdx->onError!=pIndex->onError ){
4334 /* This constraint creates the same index as a previous
4335 ** constraint specified somewhere in the CREATE TABLE statement.
4336 ** However the ON CONFLICT clauses are different. If both this
4337 ** constraint and the previous equivalent constraint have explicit
4338 ** ON CONFLICT clauses this is an error. Otherwise, use the
4339 ** explicitly specified behavior for the index.
4341 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
4342 sqlite3ErrorMsg(pParse,
4343 "conflicting ON CONFLICT clauses specified", 0);
4345 if( pIdx->onError==OE_Default ){
4346 pIdx->onError = pIndex->onError;
4349 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
4350 if( IN_RENAME_OBJECT ){
4351 pIndex->pNext = pParse->pNewIndex;
4352 pParse->pNewIndex = pIndex;
4353 pIndex = 0;
4355 goto exit_create_index;
4360 if( !IN_RENAME_OBJECT ){
4362 /* Link the new Index structure to its table and to the other
4363 ** in-memory database structures.
4365 assert( pParse->nErr==0 );
4366 if( db->init.busy ){
4367 Index *p;
4368 assert( !IN_SPECIAL_PARSE );
4369 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
4370 if( pTblName!=0 ){
4371 pIndex->tnum = db->init.newTnum;
4372 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
4373 sqlite3ErrorMsg(pParse, "invalid rootpage");
4374 pParse->rc = SQLITE_CORRUPT_BKPT;
4375 goto exit_create_index;
4378 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
4379 pIndex->zName, pIndex);
4380 if( p ){
4381 assert( p==pIndex ); /* Malloc must have failed */
4382 sqlite3OomFault(db);
4383 goto exit_create_index;
4385 db->mDbFlags |= DBFLAG_SchemaChange;
4388 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4389 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4390 ** emit code to allocate the index rootpage on disk and make an entry for
4391 ** the index in the sqlite_schema table and populate the index with
4392 ** content. But, do not do this if we are simply reading the sqlite_schema
4393 ** table to parse the schema, or if this index is the PRIMARY KEY index
4394 ** of a WITHOUT ROWID table.
4396 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4397 ** or UNIQUE index in a CREATE TABLE statement. Since the table
4398 ** has just been created, it contains no data and the index initialization
4399 ** step can be skipped.
4401 else if( HasRowid(pTab) || pTblName!=0 ){
4402 Vdbe *v;
4403 char *zStmt;
4404 int iMem = ++pParse->nMem;
4406 v = sqlite3GetVdbe(pParse);
4407 if( v==0 ) goto exit_create_index;
4409 sqlite3BeginWriteOperation(pParse, 1, iDb);
4411 /* Create the rootpage for the index using CreateIndex. But before
4412 ** doing so, code a Noop instruction and store its address in
4413 ** Index.tnum. This is required in case this index is actually a
4414 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4415 ** that case the convertToWithoutRowidTable() routine will replace
4416 ** the Noop with a Goto to jump over the VDBE code generated below. */
4417 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
4418 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
4420 /* Gather the complete text of the CREATE INDEX statement into
4421 ** the zStmt variable
4423 assert( pName!=0 || pStart==0 );
4424 if( pStart ){
4425 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
4426 if( pName->z[n-1]==';' ) n--;
4427 /* A named index with an explicit CREATE INDEX statement */
4428 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
4429 onError==OE_None ? "" : " UNIQUE", n, pName->z);
4430 }else{
4431 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4432 /* zStmt = sqlite3MPrintf(""); */
4433 zStmt = 0;
4436 /* Add an entry in sqlite_schema for this index
4438 sqlite3NestedParse(pParse,
4439 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
4440 db->aDb[iDb].zDbSName,
4441 pIndex->zName,
4442 pTab->zName,
4443 iMem,
4444 zStmt
4446 sqlite3DbFree(db, zStmt);
4448 /* Fill the index with data and reparse the schema. Code an OP_Expire
4449 ** to invalidate all pre-compiled statements.
4451 if( pTblName ){
4452 sqlite3RefillIndex(pParse, pIndex, iMem);
4453 sqlite3ChangeCookie(pParse, iDb);
4454 sqlite3VdbeAddParseSchemaOp(v, iDb,
4455 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
4456 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
4459 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
4462 if( db->init.busy || pTblName==0 ){
4463 pIndex->pNext = pTab->pIndex;
4464 pTab->pIndex = pIndex;
4465 pIndex = 0;
4467 else if( IN_RENAME_OBJECT ){
4468 assert( pParse->pNewIndex==0 );
4469 pParse->pNewIndex = pIndex;
4470 pIndex = 0;
4473 /* Clean up before exiting */
4474 exit_create_index:
4475 if( pIndex ) sqlite3FreeIndex(db, pIndex);
4476 if( pTab ){
4477 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
4478 ** The list was already ordered when this routine was entered, so at this
4479 ** point at most a single index (the newly added index) will be out of
4480 ** order. So we have to reorder at most one index. */
4481 Index **ppFrom;
4482 Index *pThis;
4483 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
4484 Index *pNext;
4485 if( pThis->onError!=OE_Replace ) continue;
4486 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4487 *ppFrom = pNext;
4488 pThis->pNext = pNext->pNext;
4489 pNext->pNext = pThis;
4490 ppFrom = &pNext->pNext;
4492 break;
4494 #ifdef SQLITE_DEBUG
4495 /* Verify that all REPLACE indexes really are now at the end
4496 ** of the index list. In other words, no other index type ever
4497 ** comes after a REPLACE index on the list. */
4498 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
4499 assert( pThis->onError!=OE_Replace
4500 || pThis->pNext==0
4501 || pThis->pNext->onError==OE_Replace );
4503 #endif
4505 sqlite3ExprDelete(db, pPIWhere);
4506 sqlite3ExprListDelete(db, pList);
4507 sqlite3SrcListDelete(db, pTblName);
4508 sqlite3DbFree(db, zName);
4512 ** Fill the Index.aiRowEst[] array with default information - information
4513 ** to be used when we have not run the ANALYZE command.
4515 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4516 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
4517 ** number of rows in the table that match any particular value of the
4518 ** first column of the index. aiRowEst[2] is an estimate of the number
4519 ** of rows that match any particular combination of the first 2 columns
4520 ** of the index. And so forth. It must always be the case that
4522 ** aiRowEst[N]<=aiRowEst[N-1]
4523 ** aiRowEst[N]>=1
4525 ** Apart from that, we have little to go on besides intuition as to
4526 ** how aiRowEst[] should be initialized. The numbers generated here
4527 ** are based on typical values found in actual indices.
4529 void sqlite3DefaultRowEst(Index *pIdx){
4530 /* 10, 9, 8, 7, 6 */
4531 static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
4532 LogEst *a = pIdx->aiRowLogEst;
4533 LogEst x;
4534 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
4535 int i;
4537 /* Indexes with default row estimates should not have stat1 data */
4538 assert( !pIdx->hasStat1 );
4540 /* Set the first entry (number of rows in the index) to the estimated
4541 ** number of rows in the table, or half the number of rows in the table
4542 ** for a partial index.
4544 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
4545 ** table but other parts we are having to guess at, then do not let the
4546 ** estimated number of rows in the table be less than 1000 (LogEst 99).
4547 ** Failure to do this can cause the indexes for which we do not have
4548 ** stat1 data to be ignored by the query planner.
4550 x = pIdx->pTable->nRowLogEst;
4551 assert( 99==sqlite3LogEst(1000) );
4552 if( x<99 ){
4553 pIdx->pTable->nRowLogEst = x = 99;
4555 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
4556 a[0] = x;
4558 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4559 ** 6 and each subsequent value (if any) is 5. */
4560 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4561 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4562 a[i] = 23; assert( 23==sqlite3LogEst(5) );
4565 assert( 0==sqlite3LogEst(1) );
4566 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
4570 ** This routine will drop an existing named index. This routine
4571 ** implements the DROP INDEX statement.
4573 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
4574 Index *pIndex;
4575 Vdbe *v;
4576 sqlite3 *db = pParse->db;
4577 int iDb;
4579 if( db->mallocFailed ){
4580 goto exit_drop_index;
4582 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
4583 assert( pName->nSrc==1 );
4584 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4585 goto exit_drop_index;
4587 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
4588 if( pIndex==0 ){
4589 if( !ifExists ){
4590 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
4591 }else{
4592 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
4593 sqlite3ForceNotReadOnly(pParse);
4595 pParse->checkSchema = 1;
4596 goto exit_drop_index;
4598 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
4599 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4600 "or PRIMARY KEY constraint cannot be dropped", 0);
4601 goto exit_drop_index;
4603 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4604 #ifndef SQLITE_OMIT_AUTHORIZATION
4606 int code = SQLITE_DROP_INDEX;
4607 Table *pTab = pIndex->pTable;
4608 const char *zDb = db->aDb[iDb].zDbSName;
4609 const char *zTab = SCHEMA_TABLE(iDb);
4610 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4611 goto exit_drop_index;
4613 if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
4614 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4615 goto exit_drop_index;
4618 #endif
4620 /* Generate code to remove the index and from the schema table */
4621 v = sqlite3GetVdbe(pParse);
4622 if( v ){
4623 sqlite3BeginWriteOperation(pParse, 1, iDb);
4624 sqlite3NestedParse(pParse,
4625 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
4626 db->aDb[iDb].zDbSName, pIndex->zName
4628 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
4629 sqlite3ChangeCookie(pParse, iDb);
4630 destroyRootPage(pParse, pIndex->tnum, iDb);
4631 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
4634 exit_drop_index:
4635 sqlite3SrcListDelete(db, pName);
4639 ** pArray is a pointer to an array of objects. Each object in the
4640 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4641 ** to extend the array so that there is space for a new object at the end.
4643 ** When this function is called, *pnEntry contains the current size of
4644 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4645 ** in total).
4647 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4648 ** space allocated for the new object is zeroed, *pnEntry updated to
4649 ** reflect the new size of the array and a pointer to the new allocation
4650 ** returned. *pIdx is set to the index of the new array entry in this case.
4652 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4653 ** unchanged and a copy of pArray returned.
4655 void *sqlite3ArrayAllocate(
4656 sqlite3 *db, /* Connection to notify of malloc failures */
4657 void *pArray, /* Array of objects. Might be reallocated */
4658 int szEntry, /* Size of each object in the array */
4659 int *pnEntry, /* Number of objects currently in use */
4660 int *pIdx /* Write the index of a new slot here */
4662 char *z;
4663 sqlite3_int64 n = *pIdx = *pnEntry;
4664 if( (n & (n-1))==0 ){
4665 sqlite3_int64 sz = (n==0) ? 1 : 2*n;
4666 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
4667 if( pNew==0 ){
4668 *pIdx = -1;
4669 return pArray;
4671 pArray = pNew;
4673 z = (char*)pArray;
4674 memset(&z[n * szEntry], 0, szEntry);
4675 ++*pnEntry;
4676 return pArray;
4680 ** Append a new element to the given IdList. Create a new IdList if
4681 ** need be.
4683 ** A new IdList is returned, or NULL if malloc() fails.
4685 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
4686 sqlite3 *db = pParse->db;
4687 int i;
4688 if( pList==0 ){
4689 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
4690 if( pList==0 ) return 0;
4691 }else{
4692 IdList *pNew;
4693 pNew = sqlite3DbRealloc(db, pList,
4694 sizeof(IdList) + pList->nId*sizeof(pList->a));
4695 if( pNew==0 ){
4696 sqlite3IdListDelete(db, pList);
4697 return 0;
4699 pList = pNew;
4701 i = pList->nId++;
4702 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4703 if( IN_RENAME_OBJECT && pList->a[i].zName ){
4704 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
4706 return pList;
4710 ** Delete an IdList.
4712 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4713 int i;
4714 assert( db!=0 );
4715 if( pList==0 ) return;
4716 assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */
4717 for(i=0; i<pList->nId; i++){
4718 sqlite3DbFree(db, pList->a[i].zName);
4720 sqlite3DbNNFreeNN(db, pList);
4724 ** Return the index in pList of the identifier named zId. Return -1
4725 ** if not found.
4727 int sqlite3IdListIndex(IdList *pList, const char *zName){
4728 int i;
4729 assert( pList!=0 );
4730 for(i=0; i<pList->nId; i++){
4731 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4733 return -1;
4737 ** Maximum size of a SrcList object.
4738 ** The SrcList object is used to represent the FROM clause of a
4739 ** SELECT statement, and the query planner cannot deal with more
4740 ** than 64 tables in a join. So any value larger than 64 here
4741 ** is sufficient for most uses. Smaller values, like say 10, are
4742 ** appropriate for small and memory-limited applications.
4744 #ifndef SQLITE_MAX_SRCLIST
4745 # define SQLITE_MAX_SRCLIST 200
4746 #endif
4749 ** Expand the space allocated for the given SrcList object by
4750 ** creating nExtra new slots beginning at iStart. iStart is zero based.
4751 ** New slots are zeroed.
4753 ** For example, suppose a SrcList initially contains two entries: A,B.
4754 ** To append 3 new entries onto the end, do this:
4756 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4758 ** After the call above it would contain: A, B, nil, nil, nil.
4759 ** If the iStart argument had been 1 instead of 2, then the result
4760 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
4761 ** the iStart value would be 0. The result then would
4762 ** be: nil, nil, nil, A, B.
4764 ** If a memory allocation fails or the SrcList becomes too large, leave
4765 ** the original SrcList unchanged, return NULL, and leave an error message
4766 ** in pParse.
4768 SrcList *sqlite3SrcListEnlarge(
4769 Parse *pParse, /* Parsing context into which errors are reported */
4770 SrcList *pSrc, /* The SrcList to be enlarged */
4771 int nExtra, /* Number of new slots to add to pSrc->a[] */
4772 int iStart /* Index in pSrc->a[] of first new slot */
4774 int i;
4776 /* Sanity checking on calling parameters */
4777 assert( iStart>=0 );
4778 assert( nExtra>=1 );
4779 assert( pSrc!=0 );
4780 assert( iStart<=pSrc->nSrc );
4782 /* Allocate additional space if needed */
4783 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4784 SrcList *pNew;
4785 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4786 sqlite3 *db = pParse->db;
4788 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4789 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4790 SQLITE_MAX_SRCLIST);
4791 return 0;
4793 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4794 pNew = sqlite3DbRealloc(db, pSrc,
4795 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4796 if( pNew==0 ){
4797 assert( db->mallocFailed );
4798 return 0;
4800 pSrc = pNew;
4801 pSrc->nAlloc = nAlloc;
4804 /* Move existing slots that come after the newly inserted slots
4805 ** out of the way */
4806 for(i=pSrc->nSrc-1; i>=iStart; i--){
4807 pSrc->a[i+nExtra] = pSrc->a[i];
4809 pSrc->nSrc += nExtra;
4811 /* Zero the newly allocated slots */
4812 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4813 for(i=iStart; i<iStart+nExtra; i++){
4814 pSrc->a[i].iCursor = -1;
4817 /* Return a pointer to the enlarged SrcList */
4818 return pSrc;
4823 ** Append a new table name to the given SrcList. Create a new SrcList if
4824 ** need be. A new entry is created in the SrcList even if pTable is NULL.
4826 ** A SrcList is returned, or NULL if there is an OOM error or if the
4827 ** SrcList grows to large. The returned
4828 ** SrcList might be the same as the SrcList that was input or it might be
4829 ** a new one. If an OOM error does occurs, then the prior value of pList
4830 ** that is input to this routine is automatically freed.
4832 ** If pDatabase is not null, it means that the table has an optional
4833 ** database name prefix. Like this: "database.table". The pDatabase
4834 ** points to the table name and the pTable points to the database name.
4835 ** The SrcList.a[].zName field is filled with the table name which might
4836 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4837 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4838 ** or with NULL if no database is specified.
4840 ** In other words, if call like this:
4842 ** sqlite3SrcListAppend(D,A,B,0);
4844 ** Then B is a table name and the database name is unspecified. If called
4845 ** like this:
4847 ** sqlite3SrcListAppend(D,A,B,C);
4849 ** Then C is the table name and B is the database name. If C is defined
4850 ** then so is B. In other words, we never have a case where:
4852 ** sqlite3SrcListAppend(D,A,0,C);
4854 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
4855 ** before being added to the SrcList.
4857 SrcList *sqlite3SrcListAppend(
4858 Parse *pParse, /* Parsing context, in which errors are reported */
4859 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
4860 Token *pTable, /* Table to append */
4861 Token *pDatabase /* Database of the table */
4863 SrcItem *pItem;
4864 sqlite3 *db;
4865 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
4866 assert( pParse!=0 );
4867 assert( pParse->db!=0 );
4868 db = pParse->db;
4869 if( pList==0 ){
4870 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4871 if( pList==0 ) return 0;
4872 pList->nAlloc = 1;
4873 pList->nSrc = 1;
4874 memset(&pList->a[0], 0, sizeof(pList->a[0]));
4875 pList->a[0].iCursor = -1;
4876 }else{
4877 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4878 if( pNew==0 ){
4879 sqlite3SrcListDelete(db, pList);
4880 return 0;
4881 }else{
4882 pList = pNew;
4885 pItem = &pList->a[pList->nSrc-1];
4886 if( pDatabase && pDatabase->z==0 ){
4887 pDatabase = 0;
4889 if( pDatabase ){
4890 pItem->zName = sqlite3NameFromToken(db, pDatabase);
4891 pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4892 }else{
4893 pItem->zName = sqlite3NameFromToken(db, pTable);
4894 pItem->zDatabase = 0;
4896 return pList;
4900 ** Assign VdbeCursor index numbers to all tables in a SrcList
4902 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4903 int i;
4904 SrcItem *pItem;
4905 assert( pList || pParse->db->mallocFailed );
4906 if( ALWAYS(pList) ){
4907 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4908 if( pItem->iCursor>=0 ) continue;
4909 pItem->iCursor = pParse->nTab++;
4910 if( pItem->pSelect ){
4911 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4918 ** Delete an entire SrcList including all its substructure.
4920 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4921 int i;
4922 SrcItem *pItem;
4923 assert( db!=0 );
4924 if( pList==0 ) return;
4925 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4926 if( pItem->zDatabase ) sqlite3DbNNFreeNN(db, pItem->zDatabase);
4927 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
4928 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
4929 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4930 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4931 sqlite3DeleteTable(db, pItem->pTab);
4932 if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
4933 if( pItem->fg.isUsing ){
4934 sqlite3IdListDelete(db, pItem->u3.pUsing);
4935 }else if( pItem->u3.pOn ){
4936 sqlite3ExprDelete(db, pItem->u3.pOn);
4939 sqlite3DbNNFreeNN(db, pList);
4943 ** This routine is called by the parser to add a new term to the
4944 ** end of a growing FROM clause. The "p" parameter is the part of
4945 ** the FROM clause that has already been constructed. "p" is NULL
4946 ** if this is the first term of the FROM clause. pTable and pDatabase
4947 ** are the name of the table and database named in the FROM clause term.
4948 ** pDatabase is NULL if the database name qualifier is missing - the
4949 ** usual case. If the term has an alias, then pAlias points to the
4950 ** alias token. If the term is a subquery, then pSubquery is the
4951 ** SELECT statement that the subquery encodes. The pTable and
4952 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
4953 ** parameters are the content of the ON and USING clauses.
4955 ** Return a new SrcList which encodes is the FROM with the new
4956 ** term added.
4958 SrcList *sqlite3SrcListAppendFromTerm(
4959 Parse *pParse, /* Parsing context */
4960 SrcList *p, /* The left part of the FROM clause already seen */
4961 Token *pTable, /* Name of the table to add to the FROM clause */
4962 Token *pDatabase, /* Name of the database containing pTable */
4963 Token *pAlias, /* The right-hand side of the AS subexpression */
4964 Select *pSubquery, /* A subquery used in place of a table name */
4965 OnOrUsing *pOnUsing /* Either the ON clause or the USING clause */
4967 SrcItem *pItem;
4968 sqlite3 *db = pParse->db;
4969 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
4970 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4971 (pOnUsing->pOn ? "ON" : "USING")
4973 goto append_from_error;
4975 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4976 if( p==0 ){
4977 goto append_from_error;
4979 assert( p->nSrc>0 );
4980 pItem = &p->a[p->nSrc-1];
4981 assert( (pTable==0)==(pDatabase==0) );
4982 assert( pItem->zName==0 || pDatabase!=0 );
4983 if( IN_RENAME_OBJECT && pItem->zName ){
4984 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4985 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4987 assert( pAlias!=0 );
4988 if( pAlias->n ){
4989 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4991 if( pSubquery ){
4992 pItem->pSelect = pSubquery;
4993 if( pSubquery->selFlags & SF_NestedFrom ){
4994 pItem->fg.isNestedFrom = 1;
4997 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
4998 assert( pItem->fg.isUsing==0 );
4999 if( pOnUsing==0 ){
5000 pItem->u3.pOn = 0;
5001 }else if( pOnUsing->pUsing ){
5002 pItem->fg.isUsing = 1;
5003 pItem->u3.pUsing = pOnUsing->pUsing;
5004 }else{
5005 pItem->u3.pOn = pOnUsing->pOn;
5007 return p;
5009 append_from_error:
5010 assert( p==0 );
5011 sqlite3ClearOnOrUsing(db, pOnUsing);
5012 sqlite3SelectDelete(db, pSubquery);
5013 return 0;
5017 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5018 ** element of the source-list passed as the second argument.
5020 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
5021 assert( pIndexedBy!=0 );
5022 if( p && pIndexedBy->n>0 ){
5023 SrcItem *pItem;
5024 assert( p->nSrc>0 );
5025 pItem = &p->a[p->nSrc-1];
5026 assert( pItem->fg.notIndexed==0 );
5027 assert( pItem->fg.isIndexedBy==0 );
5028 assert( pItem->fg.isTabFunc==0 );
5029 if( pIndexedBy->n==1 && !pIndexedBy->z ){
5030 /* A "NOT INDEXED" clause was supplied. See parse.y
5031 ** construct "indexed_opt" for details. */
5032 pItem->fg.notIndexed = 1;
5033 }else{
5034 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
5035 pItem->fg.isIndexedBy = 1;
5036 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
5042 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
5043 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
5044 ** are deleted by this function.
5046 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
5047 assert( p1 && p1->nSrc==1 );
5048 if( p2 ){
5049 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
5050 if( pNew==0 ){
5051 sqlite3SrcListDelete(pParse->db, p2);
5052 }else{
5053 p1 = pNew;
5054 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
5055 sqlite3DbFree(pParse->db, p2);
5056 p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
5059 return p1;
5063 ** Add the list of function arguments to the SrcList entry for a
5064 ** table-valued-function.
5066 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
5067 if( p ){
5068 SrcItem *pItem = &p->a[p->nSrc-1];
5069 assert( pItem->fg.notIndexed==0 );
5070 assert( pItem->fg.isIndexedBy==0 );
5071 assert( pItem->fg.isTabFunc==0 );
5072 pItem->u1.pFuncArg = pList;
5073 pItem->fg.isTabFunc = 1;
5074 }else{
5075 sqlite3ExprListDelete(pParse->db, pList);
5080 ** When building up a FROM clause in the parser, the join operator
5081 ** is initially attached to the left operand. But the code generator
5082 ** expects the join operator to be on the right operand. This routine
5083 ** Shifts all join operators from left to right for an entire FROM
5084 ** clause.
5086 ** Example: Suppose the join is like this:
5088 ** A natural cross join B
5090 ** The operator is "natural cross join". The A and B operands are stored
5091 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
5092 ** operator with A. This routine shifts that operator over to B.
5094 ** Additional changes:
5096 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
5097 ** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
5098 ** code generator can easily tell that the table is part of
5099 ** the left operand of at least one RIGHT JOIN.
5101 void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
5102 (void)pParse;
5103 if( p && p->nSrc>1 ){
5104 int i = p->nSrc-1;
5105 u8 allFlags = 0;
5107 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
5108 }while( (--i)>0 );
5109 p->a[0].fg.jointype = 0;
5111 /* All terms to the left of a RIGHT JOIN should be tagged with the
5112 ** JT_LTORJ flags */
5113 if( allFlags & JT_RIGHT ){
5114 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
5115 i--;
5116 assert( i>=0 );
5118 p->a[i].fg.jointype |= JT_LTORJ;
5119 }while( (--i)>=0 );
5125 ** Generate VDBE code for a BEGIN statement.
5127 void sqlite3BeginTransaction(Parse *pParse, int type){
5128 sqlite3 *db;
5129 Vdbe *v;
5130 int i;
5132 assert( pParse!=0 );
5133 db = pParse->db;
5134 assert( db!=0 );
5135 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
5136 return;
5138 v = sqlite3GetVdbe(pParse);
5139 if( !v ) return;
5140 if( type!=TK_DEFERRED ){
5141 for(i=0; i<db->nDb; i++){
5142 int eTxnType;
5143 Btree *pBt = db->aDb[i].pBt;
5144 if( pBt && sqlite3BtreeIsReadonly(pBt) ){
5145 eTxnType = 0; /* Read txn */
5146 }else if( type==TK_EXCLUSIVE ){
5147 eTxnType = 2; /* Exclusive txn */
5148 }else{
5149 eTxnType = 1; /* Write txn */
5151 sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
5152 sqlite3VdbeUsesBtree(v, i);
5155 sqlite3VdbeAddOp0(v, OP_AutoCommit);
5159 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
5160 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
5161 ** code is generated for a COMMIT.
5163 void sqlite3EndTransaction(Parse *pParse, int eType){
5164 Vdbe *v;
5165 int isRollback;
5167 assert( pParse!=0 );
5168 assert( pParse->db!=0 );
5169 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
5170 isRollback = eType==TK_ROLLBACK;
5171 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
5172 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
5173 return;
5175 v = sqlite3GetVdbe(pParse);
5176 if( v ){
5177 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
5182 ** This function is called by the parser when it parses a command to create,
5183 ** release or rollback an SQL savepoint.
5185 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
5186 char *zName = sqlite3NameFromToken(pParse->db, pName);
5187 if( zName ){
5188 Vdbe *v = sqlite3GetVdbe(pParse);
5189 #ifndef SQLITE_OMIT_AUTHORIZATION
5190 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5191 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
5192 #endif
5193 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
5194 sqlite3DbFree(pParse->db, zName);
5195 return;
5197 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
5202 ** Make sure the TEMP database is open and available for use. Return
5203 ** the number of errors. Leave any error messages in the pParse structure.
5205 int sqlite3OpenTempDatabase(Parse *pParse){
5206 sqlite3 *db = pParse->db;
5207 if( db->aDb[1].pBt==0 && !pParse->explain ){
5208 int rc;
5209 Btree *pBt;
5210 static const int flags =
5211 SQLITE_OPEN_READWRITE |
5212 SQLITE_OPEN_CREATE |
5213 SQLITE_OPEN_EXCLUSIVE |
5214 SQLITE_OPEN_DELETEONCLOSE |
5215 SQLITE_OPEN_TEMP_DB;
5217 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
5218 if( rc!=SQLITE_OK ){
5219 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
5220 "file for storing temporary tables");
5221 pParse->rc = rc;
5222 return 1;
5224 db->aDb[1].pBt = pBt;
5225 assert( db->aDb[1].pSchema );
5226 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
5227 sqlite3OomFault(db);
5228 return 1;
5231 return 0;
5235 ** Record the fact that the schema cookie will need to be verified
5236 ** for database iDb. The code to actually verify the schema cookie
5237 ** will occur at the end of the top-level VDBE and will be generated
5238 ** later, by sqlite3FinishCoding().
5240 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
5241 assert( iDb>=0 && iDb<pToplevel->db->nDb );
5242 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
5243 assert( iDb<SQLITE_MAX_DB );
5244 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
5245 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
5246 DbMaskSet(pToplevel->cookieMask, iDb);
5247 if( !OMIT_TEMPDB && iDb==1 ){
5248 sqlite3OpenTempDatabase(pToplevel);
5252 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
5253 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
5258 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
5259 ** attached database. Otherwise, invoke it for the database named zDb only.
5261 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
5262 sqlite3 *db = pParse->db;
5263 int i;
5264 for(i=0; i<db->nDb; i++){
5265 Db *pDb = &db->aDb[i];
5266 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
5267 sqlite3CodeVerifySchema(pParse, i);
5273 ** Generate VDBE code that prepares for doing an operation that
5274 ** might change the database.
5276 ** This routine starts a new transaction if we are not already within
5277 ** a transaction. If we are already within a transaction, then a checkpoint
5278 ** is set if the setStatement parameter is true. A checkpoint should
5279 ** be set for operations that might fail (due to a constraint) part of
5280 ** the way through and which will need to undo some writes without having to
5281 ** rollback the whole transaction. For operations where all constraints
5282 ** can be checked before any changes are made to the database, it is never
5283 ** necessary to undo a write and the checkpoint should not be set.
5285 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
5286 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5287 sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
5288 DbMaskSet(pToplevel->writeMask, iDb);
5289 pToplevel->isMultiWrite |= setStatement;
5293 ** Indicate that the statement currently under construction might write
5294 ** more than one entry (example: deleting one row then inserting another,
5295 ** inserting multiple rows in a table, or inserting a row and index entries.)
5296 ** If an abort occurs after some of these writes have completed, then it will
5297 ** be necessary to undo the completed writes.
5299 void sqlite3MultiWrite(Parse *pParse){
5300 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5301 pToplevel->isMultiWrite = 1;
5305 ** The code generator calls this routine if is discovers that it is
5306 ** possible to abort a statement prior to completion. In order to
5307 ** perform this abort without corrupting the database, we need to make
5308 ** sure that the statement is protected by a statement transaction.
5310 ** Technically, we only need to set the mayAbort flag if the
5311 ** isMultiWrite flag was previously set. There is a time dependency
5312 ** such that the abort must occur after the multiwrite. This makes
5313 ** some statements involving the REPLACE conflict resolution algorithm
5314 ** go a little faster. But taking advantage of this time dependency
5315 ** makes it more difficult to prove that the code is correct (in
5316 ** particular, it prevents us from writing an effective
5317 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
5318 ** to take the safe route and skip the optimization.
5320 void sqlite3MayAbort(Parse *pParse){
5321 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5322 pToplevel->mayAbort = 1;
5326 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5327 ** error. The onError parameter determines which (if any) of the statement
5328 ** and/or current transaction is rolled back.
5330 void sqlite3HaltConstraint(
5331 Parse *pParse, /* Parsing context */
5332 int errCode, /* extended error code */
5333 int onError, /* Constraint type */
5334 char *p4, /* Error message */
5335 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
5336 u8 p5Errmsg /* P5_ErrMsg type */
5338 Vdbe *v;
5339 assert( pParse->pVdbe!=0 );
5340 v = sqlite3GetVdbe(pParse);
5341 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
5342 if( onError==OE_Abort ){
5343 sqlite3MayAbort(pParse);
5345 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
5346 sqlite3VdbeChangeP5(v, p5Errmsg);
5350 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5352 void sqlite3UniqueConstraint(
5353 Parse *pParse, /* Parsing context */
5354 int onError, /* Constraint type */
5355 Index *pIdx /* The index that triggers the constraint */
5357 char *zErr;
5358 int j;
5359 StrAccum errMsg;
5360 Table *pTab = pIdx->pTable;
5362 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
5363 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
5364 if( pIdx->aColExpr ){
5365 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
5366 }else{
5367 for(j=0; j<pIdx->nKeyCol; j++){
5368 char *zCol;
5369 assert( pIdx->aiColumn[j]>=0 );
5370 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
5371 if( j ) sqlite3_str_append(&errMsg, ", ", 2);
5372 sqlite3_str_appendall(&errMsg, pTab->zName);
5373 sqlite3_str_append(&errMsg, ".", 1);
5374 sqlite3_str_appendall(&errMsg, zCol);
5377 zErr = sqlite3StrAccumFinish(&errMsg);
5378 sqlite3HaltConstraint(pParse,
5379 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
5380 : SQLITE_CONSTRAINT_UNIQUE,
5381 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
5386 ** Code an OP_Halt due to non-unique rowid.
5388 void sqlite3RowidConstraint(
5389 Parse *pParse, /* Parsing context */
5390 int onError, /* Conflict resolution algorithm */
5391 Table *pTab /* The table with the non-unique rowid */
5393 char *zMsg;
5394 int rc;
5395 if( pTab->iPKey>=0 ){
5396 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
5397 pTab->aCol[pTab->iPKey].zCnName);
5398 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
5399 }else{
5400 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
5401 rc = SQLITE_CONSTRAINT_ROWID;
5403 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
5404 P5_ConstraintUnique);
5408 ** Check to see if pIndex uses the collating sequence pColl. Return
5409 ** true if it does and false if it does not.
5411 #ifndef SQLITE_OMIT_REINDEX
5412 static int collationMatch(const char *zColl, Index *pIndex){
5413 int i;
5414 assert( zColl!=0 );
5415 for(i=0; i<pIndex->nColumn; i++){
5416 const char *z = pIndex->azColl[i];
5417 assert( z!=0 || pIndex->aiColumn[i]<0 );
5418 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
5419 return 1;
5422 return 0;
5424 #endif
5427 ** Recompute all indices of pTab that use the collating sequence pColl.
5428 ** If pColl==0 then recompute all indices of pTab.
5430 #ifndef SQLITE_OMIT_REINDEX
5431 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
5432 if( !IsVirtual(pTab) ){
5433 Index *pIndex; /* An index associated with pTab */
5435 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
5436 if( zColl==0 || collationMatch(zColl, pIndex) ){
5437 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5438 sqlite3BeginWriteOperation(pParse, 0, iDb);
5439 sqlite3RefillIndex(pParse, pIndex, -1);
5444 #endif
5447 ** Recompute all indices of all tables in all databases where the
5448 ** indices use the collating sequence pColl. If pColl==0 then recompute
5449 ** all indices everywhere.
5451 #ifndef SQLITE_OMIT_REINDEX
5452 static void reindexDatabases(Parse *pParse, char const *zColl){
5453 Db *pDb; /* A single database */
5454 int iDb; /* The database index number */
5455 sqlite3 *db = pParse->db; /* The database connection */
5456 HashElem *k; /* For looping over tables in pDb */
5457 Table *pTab; /* A table in the database */
5459 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
5460 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
5461 assert( pDb!=0 );
5462 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
5463 pTab = (Table*)sqliteHashData(k);
5464 reindexTable(pParse, pTab, zColl);
5468 #endif
5471 ** Generate code for the REINDEX command.
5473 ** REINDEX -- 1
5474 ** REINDEX <collation> -- 2
5475 ** REINDEX ?<database>.?<tablename> -- 3
5476 ** REINDEX ?<database>.?<indexname> -- 4
5478 ** Form 1 causes all indices in all attached databases to be rebuilt.
5479 ** Form 2 rebuilds all indices in all databases that use the named
5480 ** collating function. Forms 3 and 4 rebuild the named index or all
5481 ** indices associated with the named table.
5483 #ifndef SQLITE_OMIT_REINDEX
5484 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
5485 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
5486 char *z; /* Name of a table or index */
5487 const char *zDb; /* Name of the database */
5488 Table *pTab; /* A table in the database */
5489 Index *pIndex; /* An index associated with pTab */
5490 int iDb; /* The database index number */
5491 sqlite3 *db = pParse->db; /* The database connection */
5492 Token *pObjName; /* Name of the table or index to be reindexed */
5494 /* Read the database schema. If an error occurs, leave an error message
5495 ** and code in pParse and return NULL. */
5496 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
5497 return;
5500 if( pName1==0 ){
5501 reindexDatabases(pParse, 0);
5502 return;
5503 }else if( NEVER(pName2==0) || pName2->z==0 ){
5504 char *zColl;
5505 assert( pName1->z );
5506 zColl = sqlite3NameFromToken(pParse->db, pName1);
5507 if( !zColl ) return;
5508 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
5509 if( pColl ){
5510 reindexDatabases(pParse, zColl);
5511 sqlite3DbFree(db, zColl);
5512 return;
5514 sqlite3DbFree(db, zColl);
5516 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
5517 if( iDb<0 ) return;
5518 z = sqlite3NameFromToken(db, pObjName);
5519 if( z==0 ) return;
5520 zDb = db->aDb[iDb].zDbSName;
5521 pTab = sqlite3FindTable(db, z, zDb);
5522 if( pTab ){
5523 reindexTable(pParse, pTab, 0);
5524 sqlite3DbFree(db, z);
5525 return;
5527 pIndex = sqlite3FindIndex(db, z, zDb);
5528 sqlite3DbFree(db, z);
5529 if( pIndex ){
5530 sqlite3BeginWriteOperation(pParse, 0, iDb);
5531 sqlite3RefillIndex(pParse, pIndex, -1);
5532 return;
5534 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
5536 #endif
5539 ** Return a KeyInfo structure that is appropriate for the given Index.
5541 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5542 ** when it has finished using it.
5544 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
5545 int i;
5546 int nCol = pIdx->nColumn;
5547 int nKey = pIdx->nKeyCol;
5548 KeyInfo *pKey;
5549 if( pParse->nErr ) return 0;
5550 if( pIdx->uniqNotNull ){
5551 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
5552 }else{
5553 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
5555 if( pKey ){
5556 assert( sqlite3KeyInfoIsWriteable(pKey) );
5557 for(i=0; i<nCol; i++){
5558 const char *zColl = pIdx->azColl[i];
5559 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
5560 sqlite3LocateCollSeq(pParse, zColl);
5561 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
5562 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
5564 if( pParse->nErr ){
5565 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
5566 if( pIdx->bNoQuery==0 ){
5567 /* Deactivate the index because it contains an unknown collating
5568 ** sequence. The only way to reactive the index is to reload the
5569 ** schema. Adding the missing collating sequence later does not
5570 ** reactive the index. The application had the chance to register
5571 ** the missing index using the collation-needed callback. For
5572 ** simplicity, SQLite will not give the application a second chance.
5574 pIdx->bNoQuery = 1;
5575 pParse->rc = SQLITE_ERROR_RETRY;
5577 sqlite3KeyInfoUnref(pKey);
5578 pKey = 0;
5581 return pKey;
5584 #ifndef SQLITE_OMIT_CTE
5586 ** Create a new CTE object
5588 Cte *sqlite3CteNew(
5589 Parse *pParse, /* Parsing context */
5590 Token *pName, /* Name of the common-table */
5591 ExprList *pArglist, /* Optional column name list for the table */
5592 Select *pQuery, /* Query used to initialize the table */
5593 u8 eM10d /* The MATERIALIZED flag */
5595 Cte *pNew;
5596 sqlite3 *db = pParse->db;
5598 pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
5599 assert( pNew!=0 || db->mallocFailed );
5601 if( db->mallocFailed ){
5602 sqlite3ExprListDelete(db, pArglist);
5603 sqlite3SelectDelete(db, pQuery);
5604 }else{
5605 pNew->pSelect = pQuery;
5606 pNew->pCols = pArglist;
5607 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
5608 pNew->eM10d = eM10d;
5610 return pNew;
5614 ** Clear information from a Cte object, but do not deallocate storage
5615 ** for the object itself.
5617 static void cteClear(sqlite3 *db, Cte *pCte){
5618 assert( pCte!=0 );
5619 sqlite3ExprListDelete(db, pCte->pCols);
5620 sqlite3SelectDelete(db, pCte->pSelect);
5621 sqlite3DbFree(db, pCte->zName);
5625 ** Free the contents of the CTE object passed as the second argument.
5627 void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
5628 assert( pCte!=0 );
5629 cteClear(db, pCte);
5630 sqlite3DbFree(db, pCte);
5634 ** This routine is invoked once per CTE by the parser while parsing a
5635 ** WITH clause. The CTE described by the third argument is added to
5636 ** the WITH clause of the second argument. If the second argument is
5637 ** NULL, then a new WITH argument is created.
5639 With *sqlite3WithAdd(
5640 Parse *pParse, /* Parsing context */
5641 With *pWith, /* Existing WITH clause, or NULL */
5642 Cte *pCte /* CTE to add to the WITH clause */
5644 sqlite3 *db = pParse->db;
5645 With *pNew;
5646 char *zName;
5648 if( pCte==0 ){
5649 return pWith;
5652 /* Check that the CTE name is unique within this WITH clause. If
5653 ** not, store an error in the Parse structure. */
5654 zName = pCte->zName;
5655 if( zName && pWith ){
5656 int i;
5657 for(i=0; i<pWith->nCte; i++){
5658 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5659 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
5664 if( pWith ){
5665 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
5666 pNew = sqlite3DbRealloc(db, pWith, nByte);
5667 }else{
5668 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
5670 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
5672 if( db->mallocFailed ){
5673 sqlite3CteDelete(db, pCte);
5674 pNew = pWith;
5675 }else{
5676 pNew->a[pNew->nCte++] = *pCte;
5677 sqlite3DbFree(db, pCte);
5680 return pNew;
5684 ** Free the contents of the With object passed as the second argument.
5686 void sqlite3WithDelete(sqlite3 *db, With *pWith){
5687 if( pWith ){
5688 int i;
5689 for(i=0; i<pWith->nCte; i++){
5690 cteClear(db, &pWith->a[i]);
5692 sqlite3DbFree(db, pWith);
5695 #endif /* !defined(SQLITE_OMIT_CTE) */