establish default sqlcipher log level and target upon first activation
[sqlcipher.git] / src / build.c
blob4e46ea0b5977c9e284857e3c55559eae190ea641
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( !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);
876 void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){
877 sqlite3DeleteTable(db, (Table*)pTable);
882 ** Unlink the given table from the hash tables and the delete the
883 ** table structure with all its indices and foreign keys.
885 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
886 Table *p;
887 Db *pDb;
889 assert( db!=0 );
890 assert( iDb>=0 && iDb<db->nDb );
891 assert( zTabName );
892 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
893 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
894 pDb = &db->aDb[iDb];
895 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
896 sqlite3DeleteTable(db, p);
897 db->mDbFlags |= DBFLAG_SchemaChange;
901 ** Given a token, return a string that consists of the text of that
902 ** token. Space to hold the returned string
903 ** is obtained from sqliteMalloc() and must be freed by the calling
904 ** function.
906 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
907 ** surround the body of the token are removed.
909 ** Tokens are often just pointers into the original SQL text and so
910 ** are not \000 terminated and are not persistent. The returned string
911 ** is \000 terminated and is persistent.
913 char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
914 char *zName;
915 if( pName ){
916 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
917 sqlite3Dequote(zName);
918 }else{
919 zName = 0;
921 return zName;
925 ** Open the sqlite_schema table stored in database number iDb for
926 ** writing. The table is opened using cursor 0.
928 void sqlite3OpenSchemaTable(Parse *p, int iDb){
929 Vdbe *v = sqlite3GetVdbe(p);
930 sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
931 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
932 if( p->nTab==0 ){
933 p->nTab = 1;
938 ** Parameter zName points to a nul-terminated buffer containing the name
939 ** of a database ("main", "temp" or the name of an attached db). This
940 ** function returns the index of the named database in db->aDb[], or
941 ** -1 if the named db cannot be found.
943 int sqlite3FindDbName(sqlite3 *db, const char *zName){
944 int i = -1; /* Database number */
945 if( zName ){
946 Db *pDb;
947 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
948 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
949 /* "main" is always an acceptable alias for the primary database
950 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
951 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
954 return i;
958 ** The token *pName contains the name of a database (either "main" or
959 ** "temp" or the name of an attached db). This routine returns the
960 ** index of the named database in db->aDb[], or -1 if the named db
961 ** does not exist.
963 int sqlite3FindDb(sqlite3 *db, Token *pName){
964 int i; /* Database number */
965 char *zName; /* Name we are searching for */
966 zName = sqlite3NameFromToken(db, pName);
967 i = sqlite3FindDbName(db, zName);
968 sqlite3DbFree(db, zName);
969 return i;
972 /* The table or view or trigger name is passed to this routine via tokens
973 ** pName1 and pName2. If the table name was fully qualified, for example:
975 ** CREATE TABLE xxx.yyy (...);
977 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
978 ** the table name is not fully qualified, i.e.:
980 ** CREATE TABLE yyy(...);
982 ** Then pName1 is set to "yyy" and pName2 is "".
984 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
985 ** pName2) that stores the unqualified table name. The index of the
986 ** database "xxx" is returned.
988 int sqlite3TwoPartName(
989 Parse *pParse, /* Parsing and code generating context */
990 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
991 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
992 Token **pUnqual /* Write the unqualified object name here */
994 int iDb; /* Database holding the object */
995 sqlite3 *db = pParse->db;
997 assert( pName2!=0 );
998 if( pName2->n>0 ){
999 if( db->init.busy ) {
1000 sqlite3ErrorMsg(pParse, "corrupt database");
1001 return -1;
1003 *pUnqual = pName2;
1004 iDb = sqlite3FindDb(db, pName1);
1005 if( iDb<0 ){
1006 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
1007 return -1;
1009 }else{
1010 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
1011 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
1012 iDb = db->init.iDb;
1013 *pUnqual = pName1;
1015 return iDb;
1019 ** True if PRAGMA writable_schema is ON
1021 int sqlite3WritableSchema(sqlite3 *db){
1022 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
1023 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1024 SQLITE_WriteSchema );
1025 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1026 SQLITE_Defensive );
1027 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1028 (SQLITE_WriteSchema|SQLITE_Defensive) );
1029 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
1033 ** This routine is used to check if the UTF-8 string zName is a legal
1034 ** unqualified name for a new schema object (table, index, view or
1035 ** trigger). All names are legal except those that begin with the string
1036 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
1037 ** is reserved for internal use.
1039 ** When parsing the sqlite_schema table, this routine also checks to
1040 ** make sure the "type", "name", and "tbl_name" columns are consistent
1041 ** with the SQL.
1043 int sqlite3CheckObjectName(
1044 Parse *pParse, /* Parsing context */
1045 const char *zName, /* Name of the object to check */
1046 const char *zType, /* Type of this object */
1047 const char *zTblName /* Parent table name for triggers and indexes */
1049 sqlite3 *db = pParse->db;
1050 if( sqlite3WritableSchema(db)
1051 || db->init.imposterTable
1052 || !sqlite3Config.bExtraSchemaChecks
1054 /* Skip these error checks for writable_schema=ON */
1055 return SQLITE_OK;
1057 if( db->init.busy ){
1058 if( sqlite3_stricmp(zType, db->init.azInit[0])
1059 || sqlite3_stricmp(zName, db->init.azInit[1])
1060 || sqlite3_stricmp(zTblName, db->init.azInit[2])
1062 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
1063 return SQLITE_ERROR;
1065 }else{
1066 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
1067 || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
1069 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
1070 zName);
1071 return SQLITE_ERROR;
1075 return SQLITE_OK;
1079 ** Return the PRIMARY KEY index of a table
1081 Index *sqlite3PrimaryKeyIndex(Table *pTab){
1082 Index *p;
1083 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
1084 return p;
1088 ** Convert an table column number into a index column number. That is,
1089 ** for the column iCol in the table (as defined by the CREATE TABLE statement)
1090 ** find the (first) offset of that column in index pIdx. Or return -1
1091 ** if column iCol is not used in index pIdx.
1093 i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
1094 int i;
1095 for(i=0; i<pIdx->nColumn; i++){
1096 if( iCol==pIdx->aiColumn[i] ) return i;
1098 return -1;
1101 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1102 /* Convert a storage column number into a table column number.
1104 ** The storage column number (0,1,2,....) is the index of the value
1105 ** as it appears in the record on disk. The true column number
1106 ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
1108 ** The storage column number is less than the table column number if
1109 ** and only there are VIRTUAL columns to the left.
1111 ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
1113 i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
1114 if( pTab->tabFlags & TF_HasVirtual ){
1115 int i;
1116 for(i=0; i<=iCol; i++){
1117 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
1120 return iCol;
1122 #endif
1124 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1125 /* Convert a table column number into a storage column number.
1127 ** The storage column number (0,1,2,....) is the index of the value
1128 ** as it appears in the record on disk. Or, if the input column is
1129 ** the N-th virtual column (zero-based) then the storage number is
1130 ** the number of non-virtual columns in the table plus N.
1132 ** The true column number is the index (0,1,2,...) of the column in
1133 ** the CREATE TABLE statement.
1135 ** If the input column is a VIRTUAL column, then it should not appear
1136 ** in storage. But the value sometimes is cached in registers that
1137 ** follow the range of registers used to construct storage. This
1138 ** avoids computing the same VIRTUAL column multiple times, and provides
1139 ** values for use by OP_Param opcodes in triggers. Hence, if the
1140 ** input column is a VIRTUAL table, put it after all the other columns.
1142 ** In the following, N means "normal column", S means STORED, and
1143 ** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
1145 ** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
1146 ** -- 0 1 2 3 4 5 6 7 8
1148 ** Then the mapping from this function is as follows:
1150 ** INPUTS: 0 1 2 3 4 5 6 7 8
1151 ** OUTPUTS: 0 1 6 2 3 7 4 5 8
1153 ** So, in other words, this routine shifts all the virtual columns to
1154 ** the end.
1156 ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
1157 ** this routine is a no-op macro. If the pTab does not have any virtual
1158 ** columns, then this routine is no-op that always return iCol. If iCol
1159 ** is negative (indicating the ROWID column) then this routine return iCol.
1161 i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
1162 int i;
1163 i16 n;
1164 assert( iCol<pTab->nCol );
1165 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
1166 for(i=0, n=0; i<iCol; i++){
1167 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
1169 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
1170 /* iCol is a virtual column itself */
1171 return pTab->nNVCol + i - n;
1172 }else{
1173 /* iCol is a normal or stored column */
1174 return n;
1177 #endif
1180 ** Insert a single OP_JournalMode query opcode in order to force the
1181 ** prepared statement to return false for sqlite3_stmt_readonly(). This
1182 ** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
1183 ** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
1184 ** will return false for sqlite3_stmt_readonly() even if that statement
1185 ** is a read-only no-op.
1187 static void sqlite3ForceNotReadOnly(Parse *pParse){
1188 int iReg = ++pParse->nMem;
1189 Vdbe *v = sqlite3GetVdbe(pParse);
1190 if( v ){
1191 sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
1192 sqlite3VdbeUsesBtree(v, 0);
1197 ** Begin constructing a new table representation in memory. This is
1198 ** the first of several action routines that get called in response
1199 ** to a CREATE TABLE statement. In particular, this routine is called
1200 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
1201 ** flag is true if the table should be stored in the auxiliary database
1202 ** file instead of in the main database file. This is normally the case
1203 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
1204 ** CREATE and TABLE.
1206 ** The new table record is initialized and put in pParse->pNewTable.
1207 ** As more of the CREATE TABLE statement is parsed, additional action
1208 ** routines will be called to add more information to this record.
1209 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
1210 ** is called to complete the construction of the new table record.
1212 void sqlite3StartTable(
1213 Parse *pParse, /* Parser context */
1214 Token *pName1, /* First part of the name of the table or view */
1215 Token *pName2, /* Second part of the name of the table or view */
1216 int isTemp, /* True if this is a TEMP table */
1217 int isView, /* True if this is a VIEW */
1218 int isVirtual, /* True if this is a VIRTUAL table */
1219 int noErr /* Do nothing if table already exists */
1221 Table *pTable;
1222 char *zName = 0; /* The name of the new table */
1223 sqlite3 *db = pParse->db;
1224 Vdbe *v;
1225 int iDb; /* Database number to create the table in */
1226 Token *pName; /* Unqualified name of the table to create */
1228 if( db->init.busy && db->init.newTnum==1 ){
1229 /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */
1230 iDb = db->init.iDb;
1231 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
1232 pName = pName1;
1233 }else{
1234 /* The common case */
1235 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1236 if( iDb<0 ) return;
1237 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
1238 /* If creating a temp table, the name may not be qualified. Unless
1239 ** the database name is "temp" anyway. */
1240 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
1241 return;
1243 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
1244 zName = sqlite3NameFromToken(db, pName);
1245 if( IN_RENAME_OBJECT ){
1246 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
1249 pParse->sNameToken = *pName;
1250 if( zName==0 ) return;
1251 if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
1252 goto begin_table_error;
1254 if( db->init.iDb==1 ) isTemp = 1;
1255 #ifndef SQLITE_OMIT_AUTHORIZATION
1256 assert( isTemp==0 || isTemp==1 );
1257 assert( isView==0 || isView==1 );
1259 static const u8 aCode[] = {
1260 SQLITE_CREATE_TABLE,
1261 SQLITE_CREATE_TEMP_TABLE,
1262 SQLITE_CREATE_VIEW,
1263 SQLITE_CREATE_TEMP_VIEW
1265 char *zDb = db->aDb[iDb].zDbSName;
1266 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1267 goto begin_table_error;
1269 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
1270 zName, 0, zDb) ){
1271 goto begin_table_error;
1274 #endif
1276 /* Make sure the new table name does not collide with an existing
1277 ** index or table name in the same database. Issue an error message if
1278 ** it does. The exception is if the statement being parsed was passed
1279 ** to an sqlite3_declare_vtab() call. In that case only the column names
1280 ** and types will be used, so there is no need to test for namespace
1281 ** collisions.
1283 if( !IN_SPECIAL_PARSE ){
1284 char *zDb = db->aDb[iDb].zDbSName;
1285 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1286 goto begin_table_error;
1288 pTable = sqlite3FindTable(db, zName, zDb);
1289 if( pTable ){
1290 if( !noErr ){
1291 sqlite3ErrorMsg(pParse, "%s %T already exists",
1292 (IsView(pTable)? "view" : "table"), pName);
1293 }else{
1294 assert( !db->init.busy || CORRUPT_DB );
1295 sqlite3CodeVerifySchema(pParse, iDb);
1296 sqlite3ForceNotReadOnly(pParse);
1298 goto begin_table_error;
1300 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
1301 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
1302 goto begin_table_error;
1306 pTable = sqlite3DbMallocZero(db, sizeof(Table));
1307 if( pTable==0 ){
1308 assert( db->mallocFailed );
1309 pParse->rc = SQLITE_NOMEM_BKPT;
1310 pParse->nErr++;
1311 goto begin_table_error;
1313 pTable->zName = zName;
1314 pTable->iPKey = -1;
1315 pTable->pSchema = db->aDb[iDb].pSchema;
1316 pTable->nTabRef = 1;
1317 #ifdef SQLITE_DEFAULT_ROWEST
1318 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
1319 #else
1320 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
1321 #endif
1322 assert( pParse->pNewTable==0 );
1323 pParse->pNewTable = pTable;
1325 /* Begin generating the code that will insert the table record into
1326 ** the schema table. Note in particular that we must go ahead
1327 ** and allocate the record number for the table entry now. Before any
1328 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
1329 ** indices to be created and the table record must come before the
1330 ** indices. Hence, the record number for the table must be allocated
1331 ** now.
1333 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1334 int addr1;
1335 int fileFormat;
1336 int reg1, reg2, reg3;
1337 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
1338 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
1339 sqlite3BeginWriteOperation(pParse, 1, iDb);
1341 #ifndef SQLITE_OMIT_VIRTUALTABLE
1342 if( isVirtual ){
1343 sqlite3VdbeAddOp0(v, OP_VBegin);
1345 #endif
1347 /* If the file format and encoding in the database have not been set,
1348 ** set them now.
1350 reg1 = pParse->regRowid = ++pParse->nMem;
1351 reg2 = pParse->regRoot = ++pParse->nMem;
1352 reg3 = ++pParse->nMem;
1353 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
1354 sqlite3VdbeUsesBtree(v, iDb);
1355 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
1356 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1357 1 : SQLITE_MAX_FILE_FORMAT;
1358 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
1359 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
1360 sqlite3VdbeJumpHere(v, addr1);
1362 /* This just creates a place-holder record in the sqlite_schema table.
1363 ** The record created does not contain anything yet. It will be replaced
1364 ** by the real entry in code generated at sqlite3EndTable().
1366 ** The rowid for the new entry is left in register pParse->regRowid.
1367 ** The root page number of the new table is left in reg pParse->regRoot.
1368 ** The rowid and root page number values are needed by the code that
1369 ** sqlite3EndTable will generate.
1371 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1372 if( isView || isVirtual ){
1373 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1374 }else
1375 #endif
1377 assert( !pParse->bReturning );
1378 pParse->u1.addrCrTab =
1379 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
1381 sqlite3OpenSchemaTable(pParse, iDb);
1382 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1383 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
1384 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1385 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1386 sqlite3VdbeAddOp0(v, OP_Close);
1389 /* Normal (non-error) return. */
1390 return;
1392 /* If an error occurs, we jump here */
1393 begin_table_error:
1394 pParse->checkSchema = 1;
1395 sqlite3DbFree(db, zName);
1396 return;
1399 /* Set properties of a table column based on the (magical)
1400 ** name of the column.
1402 #if SQLITE_ENABLE_HIDDEN_COLUMNS
1403 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
1404 if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
1405 pCol->colFlags |= COLFLAG_HIDDEN;
1406 if( pTab ) pTab->tabFlags |= TF_HasHidden;
1407 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
1408 pTab->tabFlags |= TF_OOOHidden;
1411 #endif
1414 ** Clean up the data structures associated with the RETURNING clause.
1416 static void sqlite3DeleteReturning(sqlite3 *db, void *pArg){
1417 Returning *pRet = (Returning*)pArg;
1418 Hash *pHash;
1419 pHash = &(db->aDb[1].pSchema->trigHash);
1420 sqlite3HashInsert(pHash, pRet->zName, 0);
1421 sqlite3ExprListDelete(db, pRet->pReturnEL);
1422 sqlite3DbFree(db, pRet);
1426 ** Add the RETURNING clause to the parse currently underway.
1428 ** This routine creates a special TEMP trigger that will fire for each row
1429 ** of the DML statement. That TEMP trigger contains a single SELECT
1430 ** statement with a result set that is the argument of the RETURNING clause.
1431 ** The trigger has the Trigger.bReturning flag and an opcode of
1432 ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
1433 ** knows to handle it specially. The TEMP trigger is automatically
1434 ** removed at the end of the parse.
1436 ** When this routine is called, we do not yet know if the RETURNING clause
1437 ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
1438 ** RETURNING trigger instead. It will then be converted into the appropriate
1439 ** type on the first call to sqlite3TriggersExist().
1441 void sqlite3AddReturning(Parse *pParse, ExprList *pList){
1442 Returning *pRet;
1443 Hash *pHash;
1444 sqlite3 *db = pParse->db;
1445 if( pParse->pNewTrigger ){
1446 sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
1447 }else{
1448 assert( pParse->bReturning==0 || pParse->ifNotExists );
1450 pParse->bReturning = 1;
1451 pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
1452 if( pRet==0 ){
1453 sqlite3ExprListDelete(db, pList);
1454 return;
1456 pParse->u1.pReturning = pRet;
1457 pRet->pParse = pParse;
1458 pRet->pReturnEL = pList;
1459 sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);
1460 testcase( pParse->earlyCleanup );
1461 if( db->mallocFailed ) return;
1462 sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
1463 "sqlite_returning_%p", pParse);
1464 pRet->retTrig.zName = pRet->zName;
1465 pRet->retTrig.op = TK_RETURNING;
1466 pRet->retTrig.tr_tm = TRIGGER_AFTER;
1467 pRet->retTrig.bReturning = 1;
1468 pRet->retTrig.pSchema = db->aDb[1].pSchema;
1469 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
1470 pRet->retTrig.step_list = &pRet->retTStep;
1471 pRet->retTStep.op = TK_RETURNING;
1472 pRet->retTStep.pTrig = &pRet->retTrig;
1473 pRet->retTStep.pExprList = pList;
1474 pHash = &(db->aDb[1].pSchema->trigHash);
1475 assert( sqlite3HashFind(pHash, pRet->zName)==0
1476 || pParse->nErr || pParse->ifNotExists );
1477 if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
1478 ==&pRet->retTrig ){
1479 sqlite3OomFault(db);
1484 ** Add a new column to the table currently being constructed.
1486 ** The parser calls this routine once for each column declaration
1487 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1488 ** first to get things going. Then this routine is called for each
1489 ** column.
1491 void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
1492 Table *p;
1493 int i;
1494 char *z;
1495 char *zType;
1496 Column *pCol;
1497 sqlite3 *db = pParse->db;
1498 u8 hName;
1499 Column *aNew;
1500 u8 eType = COLTYPE_CUSTOM;
1501 u8 szEst = 1;
1502 char affinity = SQLITE_AFF_BLOB;
1504 if( (p = pParse->pNewTable)==0 ) return;
1505 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1506 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1507 return;
1509 if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
1511 /* Because keywords GENERATE ALWAYS can be converted into identifiers
1512 ** by the parser, we can sometimes end up with a typename that ends
1513 ** with "generated always". Check for this case and omit the surplus
1514 ** text. */
1515 if( sType.n>=16
1516 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
1518 sType.n -= 6;
1519 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1520 if( sType.n>=9
1521 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
1523 sType.n -= 9;
1524 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1528 /* Check for standard typenames. For standard typenames we will
1529 ** set the Column.eType field rather than storing the typename after
1530 ** the column name, in order to save space. */
1531 if( sType.n>=3 ){
1532 sqlite3DequoteToken(&sType);
1533 for(i=0; i<SQLITE_N_STDTYPE; i++){
1534 if( sType.n==sqlite3StdTypeLen[i]
1535 && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
1537 sType.n = 0;
1538 eType = i+1;
1539 affinity = sqlite3StdTypeAffinity[i];
1540 if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
1541 break;
1546 z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
1547 if( z==0 ) return;
1548 if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
1549 memcpy(z, sName.z, sName.n);
1550 z[sName.n] = 0;
1551 sqlite3Dequote(z);
1552 hName = sqlite3StrIHash(z);
1553 for(i=0; i<p->nCol; i++){
1554 if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
1555 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1556 sqlite3DbFree(db, z);
1557 return;
1560 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
1561 if( aNew==0 ){
1562 sqlite3DbFree(db, z);
1563 return;
1565 p->aCol = aNew;
1566 pCol = &p->aCol[p->nCol];
1567 memset(pCol, 0, sizeof(p->aCol[0]));
1568 pCol->zCnName = z;
1569 pCol->hName = hName;
1570 sqlite3ColumnPropertiesFromName(p, pCol);
1572 if( sType.n==0 ){
1573 /* If there is no type specified, columns have the default affinity
1574 ** 'BLOB' with a default size of 4 bytes. */
1575 pCol->affinity = affinity;
1576 pCol->eCType = eType;
1577 pCol->szEst = szEst;
1578 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1579 if( affinity==SQLITE_AFF_BLOB ){
1580 if( 4>=sqlite3GlobalConfig.szSorterRef ){
1581 pCol->colFlags |= COLFLAG_SORTERREF;
1584 #endif
1585 }else{
1586 zType = z + sqlite3Strlen30(z) + 1;
1587 memcpy(zType, sType.z, sType.n);
1588 zType[sType.n] = 0;
1589 sqlite3Dequote(zType);
1590 pCol->affinity = sqlite3AffinityType(zType, pCol);
1591 pCol->colFlags |= COLFLAG_HASTYPE;
1593 p->nCol++;
1594 p->nNVCol++;
1595 pParse->constraintName.n = 0;
1599 ** This routine is called by the parser while in the middle of
1600 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1601 ** been seen on a column. This routine sets the notNull flag on
1602 ** the column currently under construction.
1604 void sqlite3AddNotNull(Parse *pParse, int onError){
1605 Table *p;
1606 Column *pCol;
1607 p = pParse->pNewTable;
1608 if( p==0 || NEVER(p->nCol<1) ) return;
1609 pCol = &p->aCol[p->nCol-1];
1610 pCol->notNull = (u8)onError;
1611 p->tabFlags |= TF_HasNotNull;
1613 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1614 ** on this column. */
1615 if( pCol->colFlags & COLFLAG_UNIQUE ){
1616 Index *pIdx;
1617 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1618 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1619 if( pIdx->aiColumn[0]==p->nCol-1 ){
1620 pIdx->uniqNotNull = 1;
1627 ** Scan the column type name zType (length nType) and return the
1628 ** associated affinity type.
1630 ** This routine does a case-independent search of zType for the
1631 ** substrings in the following table. If one of the substrings is
1632 ** found, the corresponding affinity is returned. If zType contains
1633 ** more than one of the substrings, entries toward the top of
1634 ** the table take priority. For example, if zType is 'BLOBINT',
1635 ** SQLITE_AFF_INTEGER is returned.
1637 ** Substring | Affinity
1638 ** --------------------------------
1639 ** 'INT' | SQLITE_AFF_INTEGER
1640 ** 'CHAR' | SQLITE_AFF_TEXT
1641 ** 'CLOB' | SQLITE_AFF_TEXT
1642 ** 'TEXT' | SQLITE_AFF_TEXT
1643 ** 'BLOB' | SQLITE_AFF_BLOB
1644 ** 'REAL' | SQLITE_AFF_REAL
1645 ** 'FLOA' | SQLITE_AFF_REAL
1646 ** 'DOUB' | SQLITE_AFF_REAL
1648 ** If none of the substrings in the above table are found,
1649 ** SQLITE_AFF_NUMERIC is returned.
1651 char sqlite3AffinityType(const char *zIn, Column *pCol){
1652 u32 h = 0;
1653 char aff = SQLITE_AFF_NUMERIC;
1654 const char *zChar = 0;
1656 assert( zIn!=0 );
1657 while( zIn[0] ){
1658 u8 x = *(u8*)zIn;
1659 h = (h<<8) + sqlite3UpperToLower[x];
1660 zIn++;
1661 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1662 aff = SQLITE_AFF_TEXT;
1663 zChar = zIn;
1664 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1665 aff = SQLITE_AFF_TEXT;
1666 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1667 aff = SQLITE_AFF_TEXT;
1668 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1669 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1670 aff = SQLITE_AFF_BLOB;
1671 if( zIn[0]=='(' ) zChar = zIn;
1672 #ifndef SQLITE_OMIT_FLOATING_POINT
1673 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1674 && aff==SQLITE_AFF_NUMERIC ){
1675 aff = SQLITE_AFF_REAL;
1676 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1677 && aff==SQLITE_AFF_NUMERIC ){
1678 aff = SQLITE_AFF_REAL;
1679 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1680 && aff==SQLITE_AFF_NUMERIC ){
1681 aff = SQLITE_AFF_REAL;
1682 #endif
1683 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1684 aff = SQLITE_AFF_INTEGER;
1685 break;
1689 /* If pCol is not NULL, store an estimate of the field size. The
1690 ** estimate is scaled so that the size of an integer is 1. */
1691 if( pCol ){
1692 int v = 0; /* default size is approx 4 bytes */
1693 if( aff<SQLITE_AFF_NUMERIC ){
1694 if( zChar ){
1695 while( zChar[0] ){
1696 if( sqlite3Isdigit(zChar[0]) ){
1697 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1698 sqlite3GetInt32(zChar, &v);
1699 break;
1701 zChar++;
1703 }else{
1704 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1707 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1708 if( v>=sqlite3GlobalConfig.szSorterRef ){
1709 pCol->colFlags |= COLFLAG_SORTERREF;
1711 #endif
1712 v = v/4 + 1;
1713 if( v>255 ) v = 255;
1714 pCol->szEst = v;
1716 return aff;
1720 ** The expression is the default value for the most recently added column
1721 ** of the table currently under construction.
1723 ** Default value expressions must be constant. Raise an exception if this
1724 ** is not the case.
1726 ** This routine is called by the parser while in the middle of
1727 ** parsing a CREATE TABLE statement.
1729 void sqlite3AddDefaultValue(
1730 Parse *pParse, /* Parsing context */
1731 Expr *pExpr, /* The parsed expression of the default value */
1732 const char *zStart, /* Start of the default value text */
1733 const char *zEnd /* First character past end of default value text */
1735 Table *p;
1736 Column *pCol;
1737 sqlite3 *db = pParse->db;
1738 p = pParse->pNewTable;
1739 if( p!=0 ){
1740 int isInit = db->init.busy && db->init.iDb!=1;
1741 pCol = &(p->aCol[p->nCol-1]);
1742 if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
1743 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1744 pCol->zCnName);
1745 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1746 }else if( pCol->colFlags & COLFLAG_GENERATED ){
1747 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1748 testcase( pCol->colFlags & COLFLAG_STORED );
1749 sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
1750 #endif
1751 }else{
1752 /* A copy of pExpr is used instead of the original, as pExpr contains
1753 ** tokens that point to volatile memory.
1755 Expr x, *pDfltExpr;
1756 memset(&x, 0, sizeof(x));
1757 x.op = TK_SPAN;
1758 x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1759 x.pLeft = pExpr;
1760 x.flags = EP_Skip;
1761 pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1762 sqlite3DbFree(db, x.u.zToken);
1763 sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
1766 if( IN_RENAME_OBJECT ){
1767 sqlite3RenameExprUnmap(pParse, pExpr);
1769 sqlite3ExprDelete(db, pExpr);
1773 ** Backwards Compatibility Hack:
1775 ** Historical versions of SQLite accepted strings as column names in
1776 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1778 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1779 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1781 ** This is goofy. But to preserve backwards compatibility we continue to
1782 ** accept it. This routine does the necessary conversion. It converts
1783 ** the expression given in its argument from a TK_STRING into a TK_ID
1784 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1785 ** If the expression is anything other than TK_STRING, the expression is
1786 ** unchanged.
1788 static void sqlite3StringToId(Expr *p){
1789 if( p->op==TK_STRING ){
1790 p->op = TK_ID;
1791 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1792 p->pLeft->op = TK_ID;
1797 ** Tag the given column as being part of the PRIMARY KEY
1799 static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1800 pCol->colFlags |= COLFLAG_PRIMKEY;
1801 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1802 if( pCol->colFlags & COLFLAG_GENERATED ){
1803 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1804 testcase( pCol->colFlags & COLFLAG_STORED );
1805 sqlite3ErrorMsg(pParse,
1806 "generated columns cannot be part of the PRIMARY KEY");
1808 #endif
1812 ** Designate the PRIMARY KEY for the table. pList is a list of names
1813 ** of columns that form the primary key. If pList is NULL, then the
1814 ** most recently added column of the table is the primary key.
1816 ** A table can have at most one primary key. If the table already has
1817 ** a primary key (and this is the second primary key) then create an
1818 ** error.
1820 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1821 ** then we will try to use that column as the rowid. Set the Table.iPKey
1822 ** field of the table under construction to be the index of the
1823 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1824 ** no INTEGER PRIMARY KEY.
1826 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1827 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1829 void sqlite3AddPrimaryKey(
1830 Parse *pParse, /* Parsing context */
1831 ExprList *pList, /* List of field names to be indexed */
1832 int onError, /* What to do with a uniqueness conflict */
1833 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1834 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1836 Table *pTab = pParse->pNewTable;
1837 Column *pCol = 0;
1838 int iCol = -1, i;
1839 int nTerm;
1840 if( pTab==0 ) goto primary_key_exit;
1841 if( pTab->tabFlags & TF_HasPrimaryKey ){
1842 sqlite3ErrorMsg(pParse,
1843 "table \"%s\" has more than one primary key", pTab->zName);
1844 goto primary_key_exit;
1846 pTab->tabFlags |= TF_HasPrimaryKey;
1847 if( pList==0 ){
1848 iCol = pTab->nCol - 1;
1849 pCol = &pTab->aCol[iCol];
1850 makeColumnPartOfPrimaryKey(pParse, pCol);
1851 nTerm = 1;
1852 }else{
1853 nTerm = pList->nExpr;
1854 for(i=0; i<nTerm; i++){
1855 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1856 assert( pCExpr!=0 );
1857 sqlite3StringToId(pCExpr);
1858 if( pCExpr->op==TK_ID ){
1859 const char *zCName;
1860 assert( !ExprHasProperty(pCExpr, EP_IntValue) );
1861 zCName = pCExpr->u.zToken;
1862 for(iCol=0; iCol<pTab->nCol; iCol++){
1863 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
1864 pCol = &pTab->aCol[iCol];
1865 makeColumnPartOfPrimaryKey(pParse, pCol);
1866 break;
1872 if( nTerm==1
1873 && pCol
1874 && pCol->eCType==COLTYPE_INTEGER
1875 && sortOrder!=SQLITE_SO_DESC
1877 if( IN_RENAME_OBJECT && pList ){
1878 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1879 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1881 pTab->iPKey = iCol;
1882 pTab->keyConf = (u8)onError;
1883 assert( autoInc==0 || autoInc==1 );
1884 pTab->tabFlags |= autoInc*TF_Autoincrement;
1885 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
1886 (void)sqlite3HasExplicitNulls(pParse, pList);
1887 }else if( autoInc ){
1888 #ifndef SQLITE_OMIT_AUTOINCREMENT
1889 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1890 "INTEGER PRIMARY KEY");
1891 #endif
1892 }else{
1893 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1894 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1895 pList = 0;
1898 primary_key_exit:
1899 sqlite3ExprListDelete(pParse->db, pList);
1900 return;
1904 ** Add a new CHECK constraint to the table currently under construction.
1906 void sqlite3AddCheckConstraint(
1907 Parse *pParse, /* Parsing context */
1908 Expr *pCheckExpr, /* The check expression */
1909 const char *zStart, /* Opening "(" */
1910 const char *zEnd /* Closing ")" */
1912 #ifndef SQLITE_OMIT_CHECK
1913 Table *pTab = pParse->pNewTable;
1914 sqlite3 *db = pParse->db;
1915 if( pTab && !IN_DECLARE_VTAB
1916 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1918 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1919 if( pParse->constraintName.n ){
1920 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1921 }else{
1922 Token t;
1923 for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
1924 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
1925 t.z = zStart;
1926 t.n = (int)(zEnd - t.z);
1927 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
1929 }else
1930 #endif
1932 sqlite3ExprDelete(pParse->db, pCheckExpr);
1937 ** Set the collation function of the most recently parsed table column
1938 ** to the CollSeq given.
1940 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1941 Table *p;
1942 int i;
1943 char *zColl; /* Dequoted name of collation sequence */
1944 sqlite3 *db;
1946 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
1947 i = p->nCol-1;
1948 db = pParse->db;
1949 zColl = sqlite3NameFromToken(db, pToken);
1950 if( !zColl ) return;
1952 if( sqlite3LocateCollSeq(pParse, zColl) ){
1953 Index *pIdx;
1954 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
1956 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1957 ** then an index may have been created on this column before the
1958 ** collation type was added. Correct this if it is the case.
1960 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1961 assert( pIdx->nKeyCol==1 );
1962 if( pIdx->aiColumn[0]==i ){
1963 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
1967 sqlite3DbFree(db, zColl);
1970 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1971 ** column.
1973 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
1974 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1975 u8 eType = COLFLAG_VIRTUAL;
1976 Table *pTab = pParse->pNewTable;
1977 Column *pCol;
1978 if( pTab==0 ){
1979 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1980 goto generated_done;
1982 pCol = &(pTab->aCol[pTab->nCol-1]);
1983 if( IN_DECLARE_VTAB ){
1984 sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
1985 goto generated_done;
1987 if( pCol->iDflt>0 ) goto generated_error;
1988 if( pType ){
1989 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
1990 /* no-op */
1991 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
1992 eType = COLFLAG_STORED;
1993 }else{
1994 goto generated_error;
1997 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
1998 pCol->colFlags |= eType;
1999 assert( TF_HasVirtual==COLFLAG_VIRTUAL );
2000 assert( TF_HasStored==COLFLAG_STORED );
2001 pTab->tabFlags |= eType;
2002 if( pCol->colFlags & COLFLAG_PRIMKEY ){
2003 makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
2005 if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
2006 /* The value of a generated column needs to be a real expression, not
2007 ** just a reference to another column, in order for covering index
2008 ** optimizations to work correctly. So if the value is not an expression,
2009 ** turn it into one by adding a unary "+" operator. */
2010 pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
2012 if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
2013 sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
2014 pExpr = 0;
2015 goto generated_done;
2017 generated_error:
2018 sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
2019 pCol->zCnName);
2020 generated_done:
2021 sqlite3ExprDelete(pParse->db, pExpr);
2022 #else
2023 /* Throw and error for the GENERATED ALWAYS AS clause if the
2024 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
2025 sqlite3ErrorMsg(pParse, "generated columns not supported");
2026 sqlite3ExprDelete(pParse->db, pExpr);
2027 #endif
2031 ** Generate code that will increment the schema cookie.
2033 ** The schema cookie is used to determine when the schema for the
2034 ** database changes. After each schema change, the cookie value
2035 ** changes. When a process first reads the schema it records the
2036 ** cookie. Thereafter, whenever it goes to access the database,
2037 ** it checks the cookie to make sure the schema has not changed
2038 ** since it was last read.
2040 ** This plan is not completely bullet-proof. It is possible for
2041 ** the schema to change multiple times and for the cookie to be
2042 ** set back to prior value. But schema changes are infrequent
2043 ** and the probability of hitting the same cookie value is only
2044 ** 1 chance in 2^32. So we're safe enough.
2046 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
2047 ** the schema-version whenever the schema changes.
2049 void sqlite3ChangeCookie(Parse *pParse, int iDb){
2050 sqlite3 *db = pParse->db;
2051 Vdbe *v = pParse->pVdbe;
2052 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2053 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
2054 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
2058 ** Measure the number of characters needed to output the given
2059 ** identifier. The number returned includes any quotes used
2060 ** but does not include the null terminator.
2062 ** The estimate is conservative. It might be larger that what is
2063 ** really needed.
2065 static int identLength(const char *z){
2066 int n;
2067 for(n=0; *z; n++, z++){
2068 if( *z=='"' ){ n++; }
2070 return n + 2;
2074 ** The first parameter is a pointer to an output buffer. The second
2075 ** parameter is a pointer to an integer that contains the offset at
2076 ** which to write into the output buffer. This function copies the
2077 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
2078 ** to the specified offset in the buffer and updates *pIdx to refer
2079 ** to the first byte after the last byte written before returning.
2081 ** If the string zSignedIdent consists entirely of alphanumeric
2082 ** characters, does not begin with a digit and is not an SQL keyword,
2083 ** then it is copied to the output buffer exactly as it is. Otherwise,
2084 ** it is quoted using double-quotes.
2086 static void identPut(char *z, int *pIdx, char *zSignedIdent){
2087 unsigned char *zIdent = (unsigned char*)zSignedIdent;
2088 int i, j, needQuote;
2089 i = *pIdx;
2091 for(j=0; zIdent[j]; j++){
2092 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
2094 needQuote = sqlite3Isdigit(zIdent[0])
2095 || sqlite3KeywordCode(zIdent, j)!=TK_ID
2096 || zIdent[j]!=0
2097 || j==0;
2099 if( needQuote ) z[i++] = '"';
2100 for(j=0; zIdent[j]; j++){
2101 z[i++] = zIdent[j];
2102 if( zIdent[j]=='"' ) z[i++] = '"';
2104 if( needQuote ) z[i++] = '"';
2105 z[i] = 0;
2106 *pIdx = i;
2110 ** Generate a CREATE TABLE statement appropriate for the given
2111 ** table. Memory to hold the text of the statement is obtained
2112 ** from sqliteMalloc() and must be freed by the calling function.
2114 static char *createTableStmt(sqlite3 *db, Table *p){
2115 int i, k, n;
2116 char *zStmt;
2117 char *zSep, *zSep2, *zEnd;
2118 Column *pCol;
2119 n = 0;
2120 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
2121 n += identLength(pCol->zCnName) + 5;
2123 n += identLength(p->zName);
2124 if( n<50 ){
2125 zSep = "";
2126 zSep2 = ",";
2127 zEnd = ")";
2128 }else{
2129 zSep = "\n ";
2130 zSep2 = ",\n ";
2131 zEnd = "\n)";
2133 n += 35 + 6*p->nCol;
2134 zStmt = sqlite3DbMallocRaw(0, n);
2135 if( zStmt==0 ){
2136 sqlite3OomFault(db);
2137 return 0;
2139 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
2140 k = sqlite3Strlen30(zStmt);
2141 identPut(zStmt, &k, p->zName);
2142 zStmt[k++] = '(';
2143 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
2144 static const char * const azType[] = {
2145 /* SQLITE_AFF_BLOB */ "",
2146 /* SQLITE_AFF_TEXT */ " TEXT",
2147 /* SQLITE_AFF_NUMERIC */ " NUM",
2148 /* SQLITE_AFF_INTEGER */ " INT",
2149 /* SQLITE_AFF_REAL */ " REAL",
2150 /* SQLITE_AFF_FLEXNUM */ " NUM",
2152 int len;
2153 const char *zType;
2155 sqlite3_snprintf(n-k, &zStmt[k], zSep);
2156 k += sqlite3Strlen30(&zStmt[k]);
2157 zSep = zSep2;
2158 identPut(zStmt, &k, pCol->zCnName);
2159 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
2160 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
2161 testcase( pCol->affinity==SQLITE_AFF_BLOB );
2162 testcase( pCol->affinity==SQLITE_AFF_TEXT );
2163 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
2164 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
2165 testcase( pCol->affinity==SQLITE_AFF_REAL );
2166 testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
2168 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
2169 len = sqlite3Strlen30(zType);
2170 assert( pCol->affinity==SQLITE_AFF_BLOB
2171 || pCol->affinity==SQLITE_AFF_FLEXNUM
2172 || pCol->affinity==sqlite3AffinityType(zType, 0) );
2173 memcpy(&zStmt[k], zType, len);
2174 k += len;
2175 assert( k<=n );
2177 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
2178 return zStmt;
2182 ** Resize an Index object to hold N columns total. Return SQLITE_OK
2183 ** on success and SQLITE_NOMEM on an OOM error.
2185 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
2186 char *zExtra;
2187 int nByte;
2188 if( pIdx->nColumn>=N ) return SQLITE_OK;
2189 assert( pIdx->isResized==0 );
2190 nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
2191 zExtra = sqlite3DbMallocZero(db, nByte);
2192 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
2193 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
2194 pIdx->azColl = (const char**)zExtra;
2195 zExtra += sizeof(char*)*N;
2196 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
2197 pIdx->aiRowLogEst = (LogEst*)zExtra;
2198 zExtra += sizeof(LogEst)*N;
2199 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
2200 pIdx->aiColumn = (i16*)zExtra;
2201 zExtra += sizeof(i16)*N;
2202 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
2203 pIdx->aSortOrder = (u8*)zExtra;
2204 pIdx->nColumn = N;
2205 pIdx->isResized = 1;
2206 return SQLITE_OK;
2210 ** Estimate the total row width for a table.
2212 static void estimateTableWidth(Table *pTab){
2213 unsigned wTable = 0;
2214 const Column *pTabCol;
2215 int i;
2216 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
2217 wTable += pTabCol->szEst;
2219 if( pTab->iPKey<0 ) wTable++;
2220 pTab->szTabRow = sqlite3LogEst(wTable*4);
2224 ** Estimate the average size of a row for an index.
2226 static void estimateIndexWidth(Index *pIdx){
2227 unsigned wIndex = 0;
2228 int i;
2229 const Column *aCol = pIdx->pTable->aCol;
2230 for(i=0; i<pIdx->nColumn; i++){
2231 i16 x = pIdx->aiColumn[i];
2232 assert( x<pIdx->pTable->nCol );
2233 wIndex += x<0 ? 1 : aCol[x].szEst;
2235 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
2238 /* Return true if column number x is any of the first nCol entries of aiCol[].
2239 ** This is used to determine if the column number x appears in any of the
2240 ** first nCol entries of an index.
2242 static int hasColumn(const i16 *aiCol, int nCol, int x){
2243 while( nCol-- > 0 ){
2244 if( x==*(aiCol++) ){
2245 return 1;
2248 return 0;
2252 ** Return true if any of the first nKey entries of index pIdx exactly
2253 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
2254 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
2255 ** or may not be the same index as pPk.
2257 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2258 ** not a rowid or expression.
2260 ** This routine differs from hasColumn() in that both the column and the
2261 ** collating sequence must match for this routine, but for hasColumn() only
2262 ** the column name must match.
2264 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
2265 int i, j;
2266 assert( nKey<=pIdx->nColumn );
2267 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
2268 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
2269 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
2270 assert( pPk->pTable==pIdx->pTable );
2271 testcase( pPk==pIdx );
2272 j = pPk->aiColumn[iCol];
2273 assert( j!=XN_ROWID && j!=XN_EXPR );
2274 for(i=0; i<nKey; i++){
2275 assert( pIdx->aiColumn[i]>=0 || j>=0 );
2276 if( pIdx->aiColumn[i]==j
2277 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
2279 return 1;
2282 return 0;
2285 /* Recompute the colNotIdxed field of the Index.
2287 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2288 ** columns that are within the first 63 columns of the table and a 1 for
2289 ** all other bits (all columns that are not in the index). The
2290 ** high-order bit of colNotIdxed is always 1. All unindexed columns
2291 ** of the table have a 1.
2293 ** 2019-10-24: For the purpose of this computation, virtual columns are
2294 ** not considered to be covered by the index, even if they are in the
2295 ** index, because we do not trust the logic in whereIndexExprTrans() to be
2296 ** able to find all instances of a reference to the indexed table column
2297 ** and convert them into references to the index. Hence we always want
2298 ** the actual table at hand in order to recompute the virtual column, if
2299 ** necessary.
2301 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2302 ** to determine if the index is covering index.
2304 static void recomputeColumnsNotIndexed(Index *pIdx){
2305 Bitmask m = 0;
2306 int j;
2307 Table *pTab = pIdx->pTable;
2308 for(j=pIdx->nColumn-1; j>=0; j--){
2309 int x = pIdx->aiColumn[j];
2310 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
2311 testcase( x==BMS-1 );
2312 testcase( x==BMS-2 );
2313 if( x<BMS-1 ) m |= MASKBIT(x);
2316 pIdx->colNotIdxed = ~m;
2317 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
2321 ** This routine runs at the end of parsing a CREATE TABLE statement that
2322 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
2323 ** internal schema data structures and the generated VDBE code so that they
2324 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2325 ** Changes include:
2327 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2328 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2329 ** into BTREE_BLOBKEY.
2330 ** (3) Bypass the creation of the sqlite_schema table entry
2331 ** for the PRIMARY KEY as the primary key index is now
2332 ** identified by the sqlite_schema table entry of the table itself.
2333 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
2334 ** schema to the rootpage from the main table.
2335 ** (5) Add all table columns to the PRIMARY KEY Index object
2336 ** so that the PRIMARY KEY is a covering index. The surplus
2337 ** columns are part of KeyInfo.nAllField and are not used for
2338 ** sorting or lookup or uniqueness checks.
2339 ** (6) Replace the rowid tail on all automatically generated UNIQUE
2340 ** indices with the PRIMARY KEY columns.
2342 ** For virtual tables, only (1) is performed.
2344 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
2345 Index *pIdx;
2346 Index *pPk;
2347 int nPk;
2348 int nExtra;
2349 int i, j;
2350 sqlite3 *db = pParse->db;
2351 Vdbe *v = pParse->pVdbe;
2353 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2355 if( !db->init.imposterTable ){
2356 for(i=0; i<pTab->nCol; i++){
2357 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
2358 && (pTab->aCol[i].notNull==OE_None)
2360 pTab->aCol[i].notNull = OE_Abort;
2363 pTab->tabFlags |= TF_HasNotNull;
2366 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2367 ** into BTREE_BLOBKEY.
2369 assert( !pParse->bReturning );
2370 if( pParse->u1.addrCrTab ){
2371 assert( v );
2372 sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
2375 /* Locate the PRIMARY KEY index. Or, if this table was originally
2376 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2378 if( pTab->iPKey>=0 ){
2379 ExprList *pList;
2380 Token ipkToken;
2381 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
2382 pList = sqlite3ExprListAppend(pParse, 0,
2383 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
2384 if( pList==0 ){
2385 pTab->tabFlags &= ~TF_WithoutRowid;
2386 return;
2388 if( IN_RENAME_OBJECT ){
2389 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2391 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
2392 assert( pParse->pNewTable==pTab );
2393 pTab->iPKey = -1;
2394 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
2395 SQLITE_IDXTYPE_PRIMARYKEY);
2396 if( pParse->nErr ){
2397 pTab->tabFlags &= ~TF_WithoutRowid;
2398 return;
2400 assert( db->mallocFailed==0 );
2401 pPk = sqlite3PrimaryKeyIndex(pTab);
2402 assert( pPk->nKeyCol==1 );
2403 }else{
2404 pPk = sqlite3PrimaryKeyIndex(pTab);
2405 assert( pPk!=0 );
2408 ** Remove all redundant columns from the PRIMARY KEY. For example, change
2409 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
2410 ** code assumes the PRIMARY KEY contains no repeated columns.
2412 for(i=j=1; i<pPk->nKeyCol; i++){
2413 if( isDupColumn(pPk, j, pPk, i) ){
2414 pPk->nColumn--;
2415 }else{
2416 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
2417 pPk->azColl[j] = pPk->azColl[i];
2418 pPk->aSortOrder[j] = pPk->aSortOrder[i];
2419 pPk->aiColumn[j++] = pPk->aiColumn[i];
2422 pPk->nKeyCol = j;
2424 assert( pPk!=0 );
2425 pPk->isCovering = 1;
2426 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
2427 nPk = pPk->nColumn = pPk->nKeyCol;
2429 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2430 ** table entry. This is only required if currently generating VDBE
2431 ** code for a CREATE TABLE (not when parsing one as part of reading
2432 ** a database schema). */
2433 if( v && pPk->tnum>0 ){
2434 assert( db->init.busy==0 );
2435 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
2438 /* The root page of the PRIMARY KEY is the table root page */
2439 pPk->tnum = pTab->tnum;
2441 /* Update the in-memory representation of all UNIQUE indices by converting
2442 ** the final rowid column into one or more columns of the PRIMARY KEY.
2444 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2445 int n;
2446 if( IsPrimaryKeyIndex(pIdx) ) continue;
2447 for(i=n=0; i<nPk; i++){
2448 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2449 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2450 n++;
2453 if( n==0 ){
2454 /* This index is a superset of the primary key */
2455 pIdx->nColumn = pIdx->nKeyCol;
2456 continue;
2458 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
2459 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2460 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2461 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2462 pIdx->aiColumn[j] = pPk->aiColumn[i];
2463 pIdx->azColl[j] = pPk->azColl[i];
2464 if( pPk->aSortOrder[i] ){
2465 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2466 pIdx->bAscKeyBug = 1;
2468 j++;
2471 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
2472 assert( pIdx->nColumn>=j );
2475 /* Add all table columns to the PRIMARY KEY index
2477 nExtra = 0;
2478 for(i=0; i<pTab->nCol; i++){
2479 if( !hasColumn(pPk->aiColumn, nPk, i)
2480 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
2482 if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
2483 for(i=0, j=nPk; i<pTab->nCol; i++){
2484 if( !hasColumn(pPk->aiColumn, j, i)
2485 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
2487 assert( j<pPk->nColumn );
2488 pPk->aiColumn[j] = i;
2489 pPk->azColl[j] = sqlite3StrBINARY;
2490 j++;
2493 assert( pPk->nColumn==j );
2494 assert( pTab->nNVCol<=j );
2495 recomputeColumnsNotIndexed(pPk);
2499 #ifndef SQLITE_OMIT_VIRTUALTABLE
2501 ** Return true if pTab is a virtual table and zName is a shadow table name
2502 ** for that virtual table.
2504 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
2505 int nName; /* Length of zName */
2506 Module *pMod; /* Module for the virtual table */
2508 if( !IsVirtual(pTab) ) return 0;
2509 nName = sqlite3Strlen30(pTab->zName);
2510 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
2511 if( zName[nName]!='_' ) return 0;
2512 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2513 if( pMod==0 ) return 0;
2514 if( pMod->pModule->iVersion<3 ) return 0;
2515 if( pMod->pModule->xShadowName==0 ) return 0;
2516 return pMod->pModule->xShadowName(zName+nName+1);
2518 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2520 #ifndef SQLITE_OMIT_VIRTUALTABLE
2522 ** Table pTab is a virtual table. If it the virtual table implementation
2523 ** exists and has an xShadowName method, then loop over all other ordinary
2524 ** tables within the same schema looking for shadow tables of pTab, and mark
2525 ** any shadow tables seen using the TF_Shadow flag.
2527 void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
2528 int nName; /* Length of pTab->zName */
2529 Module *pMod; /* Module for the virtual table */
2530 HashElem *k; /* For looping through the symbol table */
2532 assert( IsVirtual(pTab) );
2533 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2534 if( pMod==0 ) return;
2535 if( NEVER(pMod->pModule==0) ) return;
2536 if( pMod->pModule->iVersion<3 ) return;
2537 if( pMod->pModule->xShadowName==0 ) return;
2538 assert( pTab->zName!=0 );
2539 nName = sqlite3Strlen30(pTab->zName);
2540 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
2541 Table *pOther = sqliteHashData(k);
2542 assert( pOther->zName!=0 );
2543 if( !IsOrdinaryTable(pOther) ) continue;
2544 if( pOther->tabFlags & TF_Shadow ) continue;
2545 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
2546 && pOther->zName[nName]=='_'
2547 && pMod->pModule->xShadowName(pOther->zName+nName+1)
2549 pOther->tabFlags |= TF_Shadow;
2553 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2555 #ifndef SQLITE_OMIT_VIRTUALTABLE
2557 ** Return true if zName is a shadow table name in the current database
2558 ** connection.
2560 ** zName is temporarily modified while this routine is running, but is
2561 ** restored to its original value prior to this routine returning.
2563 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
2564 char *zTail; /* Pointer to the last "_" in zName */
2565 Table *pTab; /* Table that zName is a shadow of */
2566 zTail = strrchr(zName, '_');
2567 if( zTail==0 ) return 0;
2568 *zTail = 0;
2569 pTab = sqlite3FindTable(db, zName, 0);
2570 *zTail = '_';
2571 if( pTab==0 ) return 0;
2572 if( !IsVirtual(pTab) ) return 0;
2573 return sqlite3IsShadowTableOf(db, pTab, zName);
2575 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2578 #ifdef SQLITE_DEBUG
2580 ** Mark all nodes of an expression as EP_Immutable, indicating that
2581 ** they should not be changed. Expressions attached to a table or
2582 ** index definition are tagged this way to help ensure that we do
2583 ** not pass them into code generator routines by mistake.
2585 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2586 (void)pWalker;
2587 ExprSetVVAProperty(pExpr, EP_Immutable);
2588 return WRC_Continue;
2590 static void markExprListImmutable(ExprList *pList){
2591 if( pList ){
2592 Walker w;
2593 memset(&w, 0, sizeof(w));
2594 w.xExprCallback = markImmutableExprStep;
2595 w.xSelectCallback = sqlite3SelectWalkNoop;
2596 w.xSelectCallback2 = 0;
2597 sqlite3WalkExprList(&w, pList);
2600 #else
2601 #define markExprListImmutable(X) /* no-op */
2602 #endif /* SQLITE_DEBUG */
2606 ** This routine is called to report the final ")" that terminates
2607 ** a CREATE TABLE statement.
2609 ** The table structure that other action routines have been building
2610 ** is added to the internal hash tables, assuming no errors have
2611 ** occurred.
2613 ** An entry for the table is made in the schema table on disk, unless
2614 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
2615 ** it means we are reading the sqlite_schema table because we just
2616 ** connected to the database or because the sqlite_schema table has
2617 ** recently changed, so the entry for this table already exists in
2618 ** the sqlite_schema table. We do not want to create it again.
2620 ** If the pSelect argument is not NULL, it means that this routine
2621 ** was called to create a table generated from a
2622 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2623 ** the new table will match the result set of the SELECT.
2625 void sqlite3EndTable(
2626 Parse *pParse, /* Parse context */
2627 Token *pCons, /* The ',' token after the last column defn. */
2628 Token *pEnd, /* The ')' before options in the CREATE TABLE */
2629 u32 tabOpts, /* Extra table options. Usually 0. */
2630 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
2632 Table *p; /* The new table */
2633 sqlite3 *db = pParse->db; /* The database connection */
2634 int iDb; /* Database in which the table lives */
2635 Index *pIdx; /* An implied index of the table */
2637 if( pEnd==0 && pSelect==0 ){
2638 return;
2640 p = pParse->pNewTable;
2641 if( p==0 ) return;
2643 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
2644 p->tabFlags |= TF_Shadow;
2647 /* If the db->init.busy is 1 it means we are reading the SQL off the
2648 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2649 ** So do not write to the disk again. Extract the root page number
2650 ** for the table from the db->init.newTnum field. (The page number
2651 ** should have been put there by the sqliteOpenCb routine.)
2653 ** If the root page number is 1, that means this is the sqlite_schema
2654 ** table itself. So mark it read-only.
2656 if( db->init.busy ){
2657 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
2658 sqlite3ErrorMsg(pParse, "");
2659 return;
2661 p->tnum = db->init.newTnum;
2662 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2665 /* Special processing for tables that include the STRICT keyword:
2667 ** * Do not allow custom column datatypes. Every column must have
2668 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
2670 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
2671 ** then all columns of the PRIMARY KEY must have a NOT NULL
2672 ** constraint.
2674 if( tabOpts & TF_Strict ){
2675 int ii;
2676 p->tabFlags |= TF_Strict;
2677 for(ii=0; ii<p->nCol; ii++){
2678 Column *pCol = &p->aCol[ii];
2679 if( pCol->eCType==COLTYPE_CUSTOM ){
2680 if( pCol->colFlags & COLFLAG_HASTYPE ){
2681 sqlite3ErrorMsg(pParse,
2682 "unknown datatype for %s.%s: \"%s\"",
2683 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
2685 }else{
2686 sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
2687 p->zName, pCol->zCnName);
2689 return;
2690 }else if( pCol->eCType==COLTYPE_ANY ){
2691 pCol->affinity = SQLITE_AFF_BLOB;
2693 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
2694 && p->iPKey!=ii
2695 && pCol->notNull == OE_None
2697 pCol->notNull = OE_Abort;
2698 p->tabFlags |= TF_HasNotNull;
2703 assert( (p->tabFlags & TF_HasPrimaryKey)==0
2704 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2705 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2706 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2708 /* Special processing for WITHOUT ROWID Tables */
2709 if( tabOpts & TF_WithoutRowid ){
2710 if( (p->tabFlags & TF_Autoincrement) ){
2711 sqlite3ErrorMsg(pParse,
2712 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2713 return;
2715 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2716 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2717 return;
2719 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2720 convertToWithoutRowidTable(pParse, p);
2722 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2724 #ifndef SQLITE_OMIT_CHECK
2725 /* Resolve names in all CHECK constraint expressions.
2727 if( p->pCheck ){
2728 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2729 if( pParse->nErr ){
2730 /* If errors are seen, delete the CHECK constraints now, else they might
2731 ** actually be used if PRAGMA writable_schema=ON is set. */
2732 sqlite3ExprListDelete(db, p->pCheck);
2733 p->pCheck = 0;
2734 }else{
2735 markExprListImmutable(p->pCheck);
2738 #endif /* !defined(SQLITE_OMIT_CHECK) */
2739 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2740 if( p->tabFlags & TF_HasGenerated ){
2741 int ii, nNG = 0;
2742 testcase( p->tabFlags & TF_HasVirtual );
2743 testcase( p->tabFlags & TF_HasStored );
2744 for(ii=0; ii<p->nCol; ii++){
2745 u32 colFlags = p->aCol[ii].colFlags;
2746 if( (colFlags & COLFLAG_GENERATED)!=0 ){
2747 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
2748 testcase( colFlags & COLFLAG_VIRTUAL );
2749 testcase( colFlags & COLFLAG_STORED );
2750 if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
2751 /* If there are errors in resolving the expression, change the
2752 ** expression to a NULL. This prevents code generators that operate
2753 ** on the expression from inserting extra parts into the expression
2754 ** tree that have been allocated from lookaside memory, which is
2755 ** illegal in a schema and will lead to errors or heap corruption
2756 ** when the database connection closes. */
2757 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
2758 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
2760 }else{
2761 nNG++;
2764 if( nNG==0 ){
2765 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
2766 return;
2769 #endif
2771 /* Estimate the average row size for the table and for all implied indices */
2772 estimateTableWidth(p);
2773 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2774 estimateIndexWidth(pIdx);
2777 /* If not initializing, then create a record for the new table
2778 ** in the schema table of the database.
2780 ** If this is a TEMPORARY table, write the entry into the auxiliary
2781 ** file instead of into the main database file.
2783 if( !db->init.busy ){
2784 int n;
2785 Vdbe *v;
2786 char *zType; /* "view" or "table" */
2787 char *zType2; /* "VIEW" or "TABLE" */
2788 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
2790 v = sqlite3GetVdbe(pParse);
2791 if( NEVER(v==0) ) return;
2793 sqlite3VdbeAddOp1(v, OP_Close, 0);
2796 ** Initialize zType for the new view or table.
2798 if( IsOrdinaryTable(p) ){
2799 /* A regular table */
2800 zType = "table";
2801 zType2 = "TABLE";
2802 #ifndef SQLITE_OMIT_VIEW
2803 }else{
2804 /* A view */
2805 zType = "view";
2806 zType2 = "VIEW";
2807 #endif
2810 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2811 ** statement to populate the new table. The root-page number for the
2812 ** new table is in register pParse->regRoot.
2814 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2815 ** suitable state to query for the column names and types to be used
2816 ** by the new table.
2818 ** A shared-cache write-lock is not required to write to the new table,
2819 ** as a schema-lock must have already been obtained to create it. Since
2820 ** a schema-lock excludes all other database users, the write-lock would
2821 ** be redundant.
2823 if( pSelect ){
2824 SelectDest dest; /* Where the SELECT should store results */
2825 int regYield; /* Register holding co-routine entry-point */
2826 int addrTop; /* Top of the co-routine */
2827 int regRec; /* A record to be insert into the new table */
2828 int regRowid; /* Rowid of the next row to insert */
2829 int addrInsLoop; /* Top of the loop for inserting rows */
2830 Table *pSelTab; /* A table that describes the SELECT results */
2832 if( IN_SPECIAL_PARSE ){
2833 pParse->rc = SQLITE_ERROR;
2834 pParse->nErr++;
2835 return;
2837 regYield = ++pParse->nMem;
2838 regRec = ++pParse->nMem;
2839 regRowid = ++pParse->nMem;
2840 assert(pParse->nTab==1);
2841 sqlite3MayAbort(pParse);
2842 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2843 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2844 pParse->nTab = 2;
2845 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2846 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2847 if( pParse->nErr ) return;
2848 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
2849 if( pSelTab==0 ) return;
2850 assert( p->aCol==0 );
2851 p->nCol = p->nNVCol = pSelTab->nCol;
2852 p->aCol = pSelTab->aCol;
2853 pSelTab->nCol = 0;
2854 pSelTab->aCol = 0;
2855 sqlite3DeleteTable(db, pSelTab);
2856 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2857 sqlite3Select(pParse, pSelect, &dest);
2858 if( pParse->nErr ) return;
2859 sqlite3VdbeEndCoroutine(v, regYield);
2860 sqlite3VdbeJumpHere(v, addrTop - 1);
2861 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2862 VdbeCoverage(v);
2863 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2864 sqlite3TableAffinity(v, p, 0);
2865 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2866 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2867 sqlite3VdbeGoto(v, addrInsLoop);
2868 sqlite3VdbeJumpHere(v, addrInsLoop);
2869 sqlite3VdbeAddOp1(v, OP_Close, 1);
2872 /* Compute the complete text of the CREATE statement */
2873 if( pSelect ){
2874 zStmt = createTableStmt(db, p);
2875 }else{
2876 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2877 n = (int)(pEnd2->z - pParse->sNameToken.z);
2878 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
2879 zStmt = sqlite3MPrintf(db,
2880 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2884 /* A slot for the record has already been allocated in the
2885 ** schema table. We just need to update that slot with all
2886 ** the information we've collected.
2888 sqlite3NestedParse(pParse,
2889 "UPDATE %Q." LEGACY_SCHEMA_TABLE
2890 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2891 " WHERE rowid=#%d",
2892 db->aDb[iDb].zDbSName,
2893 zType,
2894 p->zName,
2895 p->zName,
2896 pParse->regRoot,
2897 zStmt,
2898 pParse->regRowid
2900 sqlite3DbFree(db, zStmt);
2901 sqlite3ChangeCookie(pParse, iDb);
2903 #ifndef SQLITE_OMIT_AUTOINCREMENT
2904 /* Check to see if we need to create an sqlite_sequence table for
2905 ** keeping track of autoincrement keys.
2907 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
2908 Db *pDb = &db->aDb[iDb];
2909 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2910 if( pDb->pSchema->pSeqTab==0 ){
2911 sqlite3NestedParse(pParse,
2912 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2913 pDb->zDbSName
2917 #endif
2919 /* Reparse everything to update our internal data structures */
2920 sqlite3VdbeAddParseSchemaOp(v, iDb,
2921 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
2923 /* Test for cycles in generated columns and illegal expressions
2924 ** in CHECK constraints and in DEFAULT clauses. */
2925 if( p->tabFlags & TF_HasGenerated ){
2926 sqlite3VdbeAddOp4(v, OP_SqlExec, 1, 0, 0,
2927 sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
2928 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
2930 sqlite3VdbeAddOp4(v, OP_SqlExec, 1, 0, 0,
2931 sqlite3MPrintf(db, "PRAGMA \"%w\".integrity_check(%Q)",
2932 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
2935 /* Add the table to the in-memory representation of the database.
2937 if( db->init.busy ){
2938 Table *pOld;
2939 Schema *pSchema = p->pSchema;
2940 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2941 assert( HasRowid(p) || p->iPKey<0 );
2942 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
2943 if( pOld ){
2944 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
2945 sqlite3OomFault(db);
2946 return;
2948 pParse->pNewTable = 0;
2949 db->mDbFlags |= DBFLAG_SchemaChange;
2951 /* If this is the magic sqlite_sequence table used by autoincrement,
2952 ** then record a pointer to this table in the main database structure
2953 ** so that INSERT can find the table easily. */
2954 assert( !pParse->nested );
2955 #ifndef SQLITE_OMIT_AUTOINCREMENT
2956 if( strcmp(p->zName, "sqlite_sequence")==0 ){
2957 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2958 p->pSchema->pSeqTab = p;
2960 #endif
2963 #ifndef SQLITE_OMIT_ALTERTABLE
2964 if( !pSelect && IsOrdinaryTable(p) ){
2965 assert( pCons && pEnd );
2966 if( pCons->z==0 ){
2967 pCons = pEnd;
2969 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
2971 #endif
2974 #ifndef SQLITE_OMIT_VIEW
2976 ** The parser calls this routine in order to create a new VIEW
2978 void sqlite3CreateView(
2979 Parse *pParse, /* The parsing context */
2980 Token *pBegin, /* The CREATE token that begins the statement */
2981 Token *pName1, /* The token that holds the name of the view */
2982 Token *pName2, /* The token that holds the name of the view */
2983 ExprList *pCNames, /* Optional list of view column names */
2984 Select *pSelect, /* A SELECT statement that will become the new view */
2985 int isTemp, /* TRUE for a TEMPORARY view */
2986 int noErr /* Suppress error messages if VIEW already exists */
2988 Table *p;
2989 int n;
2990 const char *z;
2991 Token sEnd;
2992 DbFixer sFix;
2993 Token *pName = 0;
2994 int iDb;
2995 sqlite3 *db = pParse->db;
2997 if( pParse->nVar>0 ){
2998 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2999 goto create_view_fail;
3001 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
3002 p = pParse->pNewTable;
3003 if( p==0 || pParse->nErr ) goto create_view_fail;
3005 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
3006 ** on a view, even though views do not have rowids. The following flag
3007 ** setting fixes this problem. But the fix can be disabled by compiling
3008 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
3009 ** depend upon the old buggy behavior. The ability can also be toggled
3010 ** using sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW,...) */
3011 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
3012 p->tabFlags |= sqlite3Config.mNoVisibleRowid; /* Optional. Allow by default */
3013 #else
3014 p->tabFlags |= TF_NoVisibleRowid; /* Never allow rowid in view */
3015 #endif
3017 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3018 iDb = sqlite3SchemaToIndex(db, p->pSchema);
3019 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
3020 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
3022 /* Make a copy of the entire SELECT statement that defines the view.
3023 ** This will force all the Expr.token.z values to be dynamically
3024 ** allocated rather than point to the input string - which means that
3025 ** they will persist after the current sqlite3_exec() call returns.
3027 pSelect->selFlags |= SF_View;
3028 if( IN_RENAME_OBJECT ){
3029 p->u.view.pSelect = pSelect;
3030 pSelect = 0;
3031 }else{
3032 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
3034 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
3035 p->eTabType = TABTYP_VIEW;
3036 if( db->mallocFailed ) goto create_view_fail;
3038 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
3039 ** the end.
3041 sEnd = pParse->sLastToken;
3042 assert( sEnd.z[0]!=0 || sEnd.n==0 );
3043 if( sEnd.z[0]!=';' ){
3044 sEnd.z += sEnd.n;
3046 sEnd.n = 0;
3047 n = (int)(sEnd.z - pBegin->z);
3048 assert( n>0 );
3049 z = pBegin->z;
3050 while( sqlite3Isspace(z[n-1]) ){ n--; }
3051 sEnd.z = &z[n-1];
3052 sEnd.n = 1;
3054 /* Use sqlite3EndTable() to add the view to the schema table */
3055 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
3057 create_view_fail:
3058 sqlite3SelectDelete(db, pSelect);
3059 if( IN_RENAME_OBJECT ){
3060 sqlite3RenameExprlistUnmap(pParse, pCNames);
3062 sqlite3ExprListDelete(db, pCNames);
3063 return;
3065 #endif /* SQLITE_OMIT_VIEW */
3067 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3069 ** The Table structure pTable is really a VIEW. Fill in the names of
3070 ** the columns of the view in the pTable structure. Return the number
3071 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
3073 static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
3074 Table *pSelTab; /* A fake table from which we get the result set */
3075 Select *pSel; /* Copy of the SELECT that implements the view */
3076 int nErr = 0; /* Number of errors encountered */
3077 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
3078 #ifndef SQLITE_OMIT_VIRTUALTABLE
3079 int rc;
3080 #endif
3081 #ifndef SQLITE_OMIT_AUTHORIZATION
3082 sqlite3_xauth xAuth; /* Saved xAuth pointer */
3083 #endif
3085 assert( pTable );
3087 #ifndef SQLITE_OMIT_VIRTUALTABLE
3088 if( IsVirtual(pTable) ){
3089 db->nSchemaLock++;
3090 rc = sqlite3VtabCallConnect(pParse, pTable);
3091 db->nSchemaLock--;
3092 return rc;
3094 #endif
3096 #ifndef SQLITE_OMIT_VIEW
3097 /* A positive nCol means the columns names for this view are
3098 ** already known. This routine is not called unless either the
3099 ** table is virtual or nCol is zero.
3101 assert( pTable->nCol<=0 );
3103 /* A negative nCol is a special marker meaning that we are currently
3104 ** trying to compute the column names. If we enter this routine with
3105 ** a negative nCol, it means two or more views form a loop, like this:
3107 ** CREATE VIEW one AS SELECT * FROM two;
3108 ** CREATE VIEW two AS SELECT * FROM one;
3110 ** Actually, the error above is now caught prior to reaching this point.
3111 ** But the following test is still important as it does come up
3112 ** in the following:
3114 ** CREATE TABLE main.ex1(a);
3115 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3116 ** SELECT * FROM temp.ex1;
3118 if( pTable->nCol<0 ){
3119 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
3120 return 1;
3122 assert( pTable->nCol>=0 );
3124 /* If we get this far, it means we need to compute the table names.
3125 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
3126 ** "*" elements in the results set of the view and will assign cursors
3127 ** to the elements of the FROM clause. But we do not want these changes
3128 ** to be permanent. So the computation is done on a copy of the SELECT
3129 ** statement that defines the view.
3131 assert( IsView(pTable) );
3132 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
3133 if( pSel ){
3134 u8 eParseMode = pParse->eParseMode;
3135 int nTab = pParse->nTab;
3136 int nSelect = pParse->nSelect;
3137 pParse->eParseMode = PARSE_MODE_NORMAL;
3138 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
3139 pTable->nCol = -1;
3140 DisableLookaside;
3141 #ifndef SQLITE_OMIT_AUTHORIZATION
3142 xAuth = db->xAuth;
3143 db->xAuth = 0;
3144 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3145 db->xAuth = xAuth;
3146 #else
3147 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3148 #endif
3149 pParse->nTab = nTab;
3150 pParse->nSelect = nSelect;
3151 if( pSelTab==0 ){
3152 pTable->nCol = 0;
3153 nErr++;
3154 }else if( pTable->pCheck ){
3155 /* CREATE VIEW name(arglist) AS ...
3156 ** The names of the columns in the table are taken from
3157 ** arglist which is stored in pTable->pCheck. The pCheck field
3158 ** normally holds CHECK constraints on an ordinary table, but for
3159 ** a VIEW it holds the list of column names.
3161 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
3162 &pTable->nCol, &pTable->aCol);
3163 if( pParse->nErr==0
3164 && pTable->nCol==pSel->pEList->nExpr
3166 assert( db->mallocFailed==0 );
3167 sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
3169 }else{
3170 /* CREATE VIEW name AS... without an argument list. Construct
3171 ** the column names from the SELECT statement that defines the view.
3173 assert( pTable->aCol==0 );
3174 pTable->nCol = pSelTab->nCol;
3175 pTable->aCol = pSelTab->aCol;
3176 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
3177 pSelTab->nCol = 0;
3178 pSelTab->aCol = 0;
3179 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
3181 pTable->nNVCol = pTable->nCol;
3182 sqlite3DeleteTable(db, pSelTab);
3183 sqlite3SelectDelete(db, pSel);
3184 EnableLookaside;
3185 pParse->eParseMode = eParseMode;
3186 } else {
3187 nErr++;
3189 pTable->pSchema->schemaFlags |= DB_UnresetViews;
3190 if( db->mallocFailed ){
3191 sqlite3DeleteColumnNames(db, pTable);
3193 #endif /* SQLITE_OMIT_VIEW */
3194 return nErr;
3196 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
3197 assert( pTable!=0 );
3198 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
3199 return viewGetColumnNames(pParse, pTable);
3201 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3203 #ifndef SQLITE_OMIT_VIEW
3205 ** Clear the column names from every VIEW in database idx.
3207 static void sqliteViewResetAll(sqlite3 *db, int idx){
3208 HashElem *i;
3209 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
3210 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
3211 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
3212 Table *pTab = sqliteHashData(i);
3213 if( IsView(pTab) ){
3214 sqlite3DeleteColumnNames(db, pTab);
3217 DbClearProperty(db, idx, DB_UnresetViews);
3219 #else
3220 # define sqliteViewResetAll(A,B)
3221 #endif /* SQLITE_OMIT_VIEW */
3224 ** This function is called by the VDBE to adjust the internal schema
3225 ** used by SQLite when the btree layer moves a table root page. The
3226 ** root-page of a table or index in database iDb has changed from iFrom
3227 ** to iTo.
3229 ** Ticket #1728: The symbol table might still contain information
3230 ** on tables and/or indices that are the process of being deleted.
3231 ** If you are unlucky, one of those deleted indices or tables might
3232 ** have the same rootpage number as the real table or index that is
3233 ** being moved. So we cannot stop searching after the first match
3234 ** because the first match might be for one of the deleted indices
3235 ** or tables and not the table/index that is actually being moved.
3236 ** We must continue looping until all tables and indices with
3237 ** rootpage==iFrom have been converted to have a rootpage of iTo
3238 ** in order to be certain that we got the right one.
3240 #ifndef SQLITE_OMIT_AUTOVACUUM
3241 void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
3242 HashElem *pElem;
3243 Hash *pHash;
3244 Db *pDb;
3246 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3247 pDb = &db->aDb[iDb];
3248 pHash = &pDb->pSchema->tblHash;
3249 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3250 Table *pTab = sqliteHashData(pElem);
3251 if( pTab->tnum==iFrom ){
3252 pTab->tnum = iTo;
3255 pHash = &pDb->pSchema->idxHash;
3256 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3257 Index *pIdx = sqliteHashData(pElem);
3258 if( pIdx->tnum==iFrom ){
3259 pIdx->tnum = iTo;
3263 #endif
3266 ** Write code to erase the table with root-page iTable from database iDb.
3267 ** Also write code to modify the sqlite_schema table and internal schema
3268 ** if a root-page of another table is moved by the btree-layer whilst
3269 ** erasing iTable (this can happen with an auto-vacuum database).
3271 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
3272 Vdbe *v = sqlite3GetVdbe(pParse);
3273 int r1 = sqlite3GetTempReg(pParse);
3274 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
3275 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
3276 sqlite3MayAbort(pParse);
3277 #ifndef SQLITE_OMIT_AUTOVACUUM
3278 /* OP_Destroy stores an in integer r1. If this integer
3279 ** is non-zero, then it is the root page number of a table moved to
3280 ** location iTable. The following code modifies the sqlite_schema table to
3281 ** reflect this.
3283 ** The "#NNN" in the SQL is a special constant that means whatever value
3284 ** is in register NNN. See grammar rules associated with the TK_REGISTER
3285 ** token for additional information.
3287 sqlite3NestedParse(pParse,
3288 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3289 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3290 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
3291 #endif
3292 sqlite3ReleaseTempReg(pParse, r1);
3296 ** Write VDBE code to erase table pTab and all associated indices on disk.
3297 ** Code to update the sqlite_schema tables and internal schema definitions
3298 ** in case a root-page belonging to another table is moved by the btree layer
3299 ** is also added (this can happen with an auto-vacuum database).
3301 static void destroyTable(Parse *pParse, Table *pTab){
3302 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3303 ** is not defined), then it is important to call OP_Destroy on the
3304 ** table and index root-pages in order, starting with the numerically
3305 ** largest root-page number. This guarantees that none of the root-pages
3306 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3307 ** following were coded:
3309 ** OP_Destroy 4 0
3310 ** ...
3311 ** OP_Destroy 5 0
3313 ** and root page 5 happened to be the largest root-page number in the
3314 ** database, then root page 5 would be moved to page 4 by the
3315 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3316 ** a free-list page.
3318 Pgno iTab = pTab->tnum;
3319 Pgno iDestroyed = 0;
3321 while( 1 ){
3322 Index *pIdx;
3323 Pgno iLargest = 0;
3325 if( iDestroyed==0 || iTab<iDestroyed ){
3326 iLargest = iTab;
3328 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3329 Pgno iIdx = pIdx->tnum;
3330 assert( pIdx->pSchema==pTab->pSchema );
3331 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
3332 iLargest = iIdx;
3335 if( iLargest==0 ){
3336 return;
3337 }else{
3338 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3339 assert( iDb>=0 && iDb<pParse->db->nDb );
3340 destroyRootPage(pParse, iLargest, iDb);
3341 iDestroyed = iLargest;
3347 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3348 ** after a DROP INDEX or DROP TABLE command.
3350 static void sqlite3ClearStatTables(
3351 Parse *pParse, /* The parsing context */
3352 int iDb, /* The database number */
3353 const char *zType, /* "idx" or "tbl" */
3354 const char *zName /* Name of index or table */
3356 int i;
3357 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
3358 for(i=1; i<=4; i++){
3359 char zTab[24];
3360 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
3361 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
3362 sqlite3NestedParse(pParse,
3363 "DELETE FROM %Q.%s WHERE %s=%Q",
3364 zDbName, zTab, zType, zName
3371 ** Generate code to drop a table.
3373 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
3374 Vdbe *v;
3375 sqlite3 *db = pParse->db;
3376 Trigger *pTrigger;
3377 Db *pDb = &db->aDb[iDb];
3379 v = sqlite3GetVdbe(pParse);
3380 assert( v!=0 );
3381 sqlite3BeginWriteOperation(pParse, 1, iDb);
3383 #ifndef SQLITE_OMIT_VIRTUALTABLE
3384 if( IsVirtual(pTab) ){
3385 sqlite3VdbeAddOp0(v, OP_VBegin);
3387 #endif
3389 /* Drop all triggers associated with the table being dropped. Code
3390 ** is generated to remove entries from sqlite_schema and/or
3391 ** sqlite_temp_schema if required.
3393 pTrigger = sqlite3TriggerList(pParse, pTab);
3394 while( pTrigger ){
3395 assert( pTrigger->pSchema==pTab->pSchema ||
3396 pTrigger->pSchema==db->aDb[1].pSchema );
3397 sqlite3DropTriggerPtr(pParse, pTrigger);
3398 pTrigger = pTrigger->pNext;
3401 #ifndef SQLITE_OMIT_AUTOINCREMENT
3402 /* Remove any entries of the sqlite_sequence table associated with
3403 ** the table being dropped. This is done before the table is dropped
3404 ** at the btree level, in case the sqlite_sequence table needs to
3405 ** move as a result of the drop (can happen in auto-vacuum mode).
3407 if( pTab->tabFlags & TF_Autoincrement ){
3408 sqlite3NestedParse(pParse,
3409 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3410 pDb->zDbSName, pTab->zName
3413 #endif
3415 /* Drop all entries in the schema table that refer to the
3416 ** table. The program name loops through the schema table and deletes
3417 ** every row that refers to a table of the same name as the one being
3418 ** dropped. Triggers are handled separately because a trigger can be
3419 ** created in the temp database that refers to a table in another
3420 ** database.
3422 sqlite3NestedParse(pParse,
3423 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3424 " WHERE tbl_name=%Q and type!='trigger'",
3425 pDb->zDbSName, pTab->zName);
3426 if( !isView && !IsVirtual(pTab) ){
3427 destroyTable(pParse, pTab);
3430 /* Remove the table entry from SQLite's internal schema and modify
3431 ** the schema cookie.
3433 if( IsVirtual(pTab) ){
3434 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
3435 sqlite3MayAbort(pParse);
3437 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
3438 sqlite3ChangeCookie(pParse, iDb);
3439 sqliteViewResetAll(db, iDb);
3443 ** Return TRUE if shadow tables should be read-only in the current
3444 ** context.
3446 int sqlite3ReadOnlyShadowTables(sqlite3 *db){
3447 #ifndef SQLITE_OMIT_VIRTUALTABLE
3448 if( (db->flags & SQLITE_Defensive)!=0
3449 && db->pVtabCtx==0
3450 && db->nVdbeExec==0
3451 && !sqlite3VtabInSync(db)
3453 return 1;
3455 #endif
3456 return 0;
3460 ** Return true if it is not allowed to drop the given table
3462 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
3463 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
3464 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
3465 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
3466 return 1;
3468 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
3469 return 1;
3471 if( pTab->tabFlags & TF_Eponymous ){
3472 return 1;
3474 return 0;
3478 ** This routine is called to do the work of a DROP TABLE statement.
3479 ** pName is the name of the table to be dropped.
3481 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3482 Table *pTab;
3483 Vdbe *v;
3484 sqlite3 *db = pParse->db;
3485 int iDb;
3487 if( db->mallocFailed ){
3488 goto exit_drop_table;
3490 assert( pParse->nErr==0 );
3491 assert( pName->nSrc==1 );
3492 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3493 if( noErr ) db->suppressErr++;
3494 assert( isView==0 || isView==LOCATE_VIEW );
3495 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3496 if( noErr ) db->suppressErr--;
3498 if( pTab==0 ){
3499 if( noErr ){
3500 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3501 sqlite3ForceNotReadOnly(pParse);
3503 goto exit_drop_table;
3505 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3506 assert( iDb>=0 && iDb<db->nDb );
3508 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3509 ** it is initialized.
3511 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3512 goto exit_drop_table;
3514 #ifndef SQLITE_OMIT_AUTHORIZATION
3516 int code;
3517 const char *zTab = SCHEMA_TABLE(iDb);
3518 const char *zDb = db->aDb[iDb].zDbSName;
3519 const char *zArg2 = 0;
3520 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3521 goto exit_drop_table;
3523 if( isView ){
3524 if( !OMIT_TEMPDB && iDb==1 ){
3525 code = SQLITE_DROP_TEMP_VIEW;
3526 }else{
3527 code = SQLITE_DROP_VIEW;
3529 #ifndef SQLITE_OMIT_VIRTUALTABLE
3530 }else if( IsVirtual(pTab) ){
3531 code = SQLITE_DROP_VTABLE;
3532 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
3533 #endif
3534 }else{
3535 if( !OMIT_TEMPDB && iDb==1 ){
3536 code = SQLITE_DROP_TEMP_TABLE;
3537 }else{
3538 code = SQLITE_DROP_TABLE;
3541 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3542 goto exit_drop_table;
3544 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3545 goto exit_drop_table;
3548 #endif
3549 if( tableMayNotBeDropped(db, pTab) ){
3550 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3551 goto exit_drop_table;
3554 #ifndef SQLITE_OMIT_VIEW
3555 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3556 ** on a table.
3558 if( isView && !IsView(pTab) ){
3559 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3560 goto exit_drop_table;
3562 if( !isView && IsView(pTab) ){
3563 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3564 goto exit_drop_table;
3566 #endif
3568 /* Generate code to remove the table from the schema table
3569 ** on disk.
3571 v = sqlite3GetVdbe(pParse);
3572 if( v ){
3573 sqlite3BeginWriteOperation(pParse, 1, iDb);
3574 if( !isView ){
3575 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3576 sqlite3FkDropTable(pParse, pName, pTab);
3578 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
3581 exit_drop_table:
3582 sqlite3SrcListDelete(db, pName);
3586 ** This routine is called to create a new foreign key on the table
3587 ** currently under construction. pFromCol determines which columns
3588 ** in the current table point to the foreign key. If pFromCol==0 then
3589 ** connect the key to the last column inserted. pTo is the name of
3590 ** the table referred to (a.k.a the "parent" table). pToCol is a list
3591 ** of tables in the parent pTo table. flags contains all
3592 ** information about the conflict resolution algorithms specified
3593 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3595 ** An FKey structure is created and added to the table currently
3596 ** under construction in the pParse->pNewTable field.
3598 ** The foreign key is set for IMMEDIATE processing. A subsequent call
3599 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3601 void sqlite3CreateForeignKey(
3602 Parse *pParse, /* Parsing context */
3603 ExprList *pFromCol, /* Columns in this table that point to other table */
3604 Token *pTo, /* Name of the other table */
3605 ExprList *pToCol, /* Columns in the other table */
3606 int flags /* Conflict resolution algorithms. */
3608 sqlite3 *db = pParse->db;
3609 #ifndef SQLITE_OMIT_FOREIGN_KEY
3610 FKey *pFKey = 0;
3611 FKey *pNextTo;
3612 Table *p = pParse->pNewTable;
3613 i64 nByte;
3614 int i;
3615 int nCol;
3616 char *z;
3618 assert( pTo!=0 );
3619 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3620 if( pFromCol==0 ){
3621 int iCol = p->nCol-1;
3622 if( NEVER(iCol<0) ) goto fk_end;
3623 if( pToCol && pToCol->nExpr!=1 ){
3624 sqlite3ErrorMsg(pParse, "foreign key on %s"
3625 " should reference only one column of table %T",
3626 p->aCol[iCol].zCnName, pTo);
3627 goto fk_end;
3629 nCol = 1;
3630 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
3631 sqlite3ErrorMsg(pParse,
3632 "number of columns in foreign key does not match the number of "
3633 "columns in the referenced table");
3634 goto fk_end;
3635 }else{
3636 nCol = pFromCol->nExpr;
3638 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
3639 if( pToCol ){
3640 for(i=0; i<pToCol->nExpr; i++){
3641 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3644 pFKey = sqlite3DbMallocZero(db, nByte );
3645 if( pFKey==0 ){
3646 goto fk_end;
3648 pFKey->pFrom = p;
3649 assert( IsOrdinaryTable(p) );
3650 pFKey->pNextFrom = p->u.tab.pFKey;
3651 z = (char*)&pFKey->aCol[nCol];
3652 pFKey->zTo = z;
3653 if( IN_RENAME_OBJECT ){
3654 sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3656 memcpy(z, pTo->z, pTo->n);
3657 z[pTo->n] = 0;
3658 sqlite3Dequote(z);
3659 z += pTo->n+1;
3660 pFKey->nCol = nCol;
3661 if( pFromCol==0 ){
3662 pFKey->aCol[0].iFrom = p->nCol-1;
3663 }else{
3664 for(i=0; i<nCol; i++){
3665 int j;
3666 for(j=0; j<p->nCol; j++){
3667 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
3668 pFKey->aCol[i].iFrom = j;
3669 break;
3672 if( j>=p->nCol ){
3673 sqlite3ErrorMsg(pParse,
3674 "unknown column \"%s\" in foreign key definition",
3675 pFromCol->a[i].zEName);
3676 goto fk_end;
3678 if( IN_RENAME_OBJECT ){
3679 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3683 if( pToCol ){
3684 for(i=0; i<nCol; i++){
3685 int n = sqlite3Strlen30(pToCol->a[i].zEName);
3686 pFKey->aCol[i].zCol = z;
3687 if( IN_RENAME_OBJECT ){
3688 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
3690 memcpy(z, pToCol->a[i].zEName, n);
3691 z[n] = 0;
3692 z += n+1;
3695 pFKey->isDeferred = 0;
3696 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
3697 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
3699 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
3700 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3701 pFKey->zTo, (void *)pFKey
3703 if( pNextTo==pFKey ){
3704 sqlite3OomFault(db);
3705 goto fk_end;
3707 if( pNextTo ){
3708 assert( pNextTo->pPrevTo==0 );
3709 pFKey->pNextTo = pNextTo;
3710 pNextTo->pPrevTo = pFKey;
3713 /* Link the foreign key to the table as the last step.
3715 assert( IsOrdinaryTable(p) );
3716 p->u.tab.pFKey = pFKey;
3717 pFKey = 0;
3719 fk_end:
3720 sqlite3DbFree(db, pFKey);
3721 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3722 sqlite3ExprListDelete(db, pFromCol);
3723 sqlite3ExprListDelete(db, pToCol);
3727 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3728 ** clause is seen as part of a foreign key definition. The isDeferred
3729 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3730 ** The behavior of the most recently created foreign key is adjusted
3731 ** accordingly.
3733 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3734 #ifndef SQLITE_OMIT_FOREIGN_KEY
3735 Table *pTab;
3736 FKey *pFKey;
3737 if( (pTab = pParse->pNewTable)==0 ) return;
3738 if( NEVER(!IsOrdinaryTable(pTab)) ) return;
3739 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
3740 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3741 pFKey->isDeferred = (u8)isDeferred;
3742 #endif
3746 ** Generate code that will erase and refill index *pIdx. This is
3747 ** used to initialize a newly created index or to recompute the
3748 ** content of an index in response to a REINDEX command.
3750 ** if memRootPage is not negative, it means that the index is newly
3751 ** created. The register specified by memRootPage contains the
3752 ** root page number of the index. If memRootPage is negative, then
3753 ** the index already exists and must be cleared before being refilled and
3754 ** the root page number of the index is taken from pIndex->tnum.
3756 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3757 Table *pTab = pIndex->pTable; /* The table that is indexed */
3758 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
3759 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
3760 int iSorter; /* Cursor opened by OpenSorter (if in use) */
3761 int addr1; /* Address of top of loop */
3762 int addr2; /* Address to jump to for next iteration */
3763 Pgno tnum; /* Root page of index */
3764 int iPartIdxLabel; /* Jump to this label to skip a row */
3765 Vdbe *v; /* Generate code into this virtual machine */
3766 KeyInfo *pKey; /* KeyInfo for index */
3767 int regRecord; /* Register holding assembled index record */
3768 sqlite3 *db = pParse->db; /* The database connection */
3769 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3771 #ifndef SQLITE_OMIT_AUTHORIZATION
3772 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3773 db->aDb[iDb].zDbSName ) ){
3774 return;
3776 #endif
3778 /* Require a write-lock on the table to perform this operation */
3779 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3781 v = sqlite3GetVdbe(pParse);
3782 if( v==0 ) return;
3783 if( memRootPage>=0 ){
3784 tnum = (Pgno)memRootPage;
3785 }else{
3786 tnum = pIndex->tnum;
3788 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3789 assert( pKey!=0 || pParse->nErr );
3791 /* Open the sorter cursor if we are to use one. */
3792 iSorter = pParse->nTab++;
3793 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3794 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3796 /* Open the table. Loop through all rows of the table, inserting index
3797 ** records into the sorter. */
3798 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3799 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3800 regRecord = sqlite3GetTempReg(pParse);
3801 sqlite3MultiWrite(pParse);
3803 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3804 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3805 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3806 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3807 sqlite3VdbeJumpHere(v, addr1);
3808 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3809 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
3810 (char *)pKey, P4_KEYINFO);
3811 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3813 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3814 if( IsUniqueIndex(pIndex) ){
3815 int j2 = sqlite3VdbeGoto(v, 1);
3816 addr2 = sqlite3VdbeCurrentAddr(v);
3817 sqlite3VdbeVerifyAbortable(v, OE_Abort);
3818 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3819 pIndex->nKeyCol); VdbeCoverage(v);
3820 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3821 sqlite3VdbeJumpHere(v, j2);
3822 }else{
3823 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3824 ** abort. The exception is if one of the indexed expressions contains a
3825 ** user function that throws an exception when it is evaluated. But the
3826 ** overhead of adding a statement journal to a CREATE INDEX statement is
3827 ** very small (since most of the pages written do not contain content that
3828 ** needs to be restored if the statement aborts), so we call
3829 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3830 sqlite3MayAbort(pParse);
3831 addr2 = sqlite3VdbeCurrentAddr(v);
3833 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3834 if( !pIndex->bAscKeyBug ){
3835 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3836 ** faster by avoiding unnecessary seeks. But the optimization does
3837 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3838 ** with DESC primary keys, since those indexes have there keys in
3839 ** a different order from the main table.
3840 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3842 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3844 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3845 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3846 sqlite3ReleaseTempReg(pParse, regRecord);
3847 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3848 sqlite3VdbeJumpHere(v, addr1);
3850 sqlite3VdbeAddOp1(v, OP_Close, iTab);
3851 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3852 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3856 ** Allocate heap space to hold an Index object with nCol columns.
3858 ** Increase the allocation size to provide an extra nExtra bytes
3859 ** of 8-byte aligned space after the Index object and return a
3860 ** pointer to this extra space in *ppExtra.
3862 Index *sqlite3AllocateIndexObject(
3863 sqlite3 *db, /* Database connection */
3864 i16 nCol, /* Total number of columns in the index */
3865 int nExtra, /* Number of bytes of extra space to alloc */
3866 char **ppExtra /* Pointer to the "extra" space */
3868 Index *p; /* Allocated index object */
3869 int nByte; /* Bytes of space for Index object + arrays */
3871 nByte = ROUND8(sizeof(Index)) + /* Index structure */
3872 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
3873 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
3874 sizeof(i16)*nCol + /* Index.aiColumn */
3875 sizeof(u8)*nCol); /* Index.aSortOrder */
3876 p = sqlite3DbMallocZero(db, nByte + nExtra);
3877 if( p ){
3878 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3879 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3880 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3881 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
3882 p->aSortOrder = (u8*)pExtra;
3883 p->nColumn = nCol;
3884 p->nKeyCol = nCol - 1;
3885 *ppExtra = ((char*)p) + nByte;
3887 return p;
3891 ** If expression list pList contains an expression that was parsed with
3892 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3893 ** pParse and return non-zero. Otherwise, return zero.
3895 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
3896 if( pList ){
3897 int i;
3898 for(i=0; i<pList->nExpr; i++){
3899 if( pList->a[i].fg.bNulls ){
3900 u8 sf = pList->a[i].fg.sortFlags;
3901 sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
3902 (sf==0 || sf==3) ? "FIRST" : "LAST"
3904 return 1;
3908 return 0;
3912 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
3913 ** and pTblList is the name of the table that is to be indexed. Both will
3914 ** be NULL for a primary key or an index that is created to satisfy a
3915 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
3916 ** as the table to be indexed. pParse->pNewTable is a table that is
3917 ** currently being constructed by a CREATE TABLE statement.
3919 ** pList is a list of columns to be indexed. pList will be NULL if this
3920 ** is a primary key or unique-constraint on the most recent column added
3921 ** to the table currently under construction.
3923 void sqlite3CreateIndex(
3924 Parse *pParse, /* All information about this parse */
3925 Token *pName1, /* First part of index name. May be NULL */
3926 Token *pName2, /* Second part of index name. May be NULL */
3927 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3928 ExprList *pList, /* A list of columns to be indexed */
3929 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3930 Token *pStart, /* The CREATE token that begins this statement */
3931 Expr *pPIWhere, /* WHERE clause for partial indices */
3932 int sortOrder, /* Sort order of primary key when pList==NULL */
3933 int ifNotExist, /* Omit error if index already exists */
3934 u8 idxType /* The index type */
3936 Table *pTab = 0; /* Table to be indexed */
3937 Index *pIndex = 0; /* The index to be created */
3938 char *zName = 0; /* Name of the index */
3939 int nName; /* Number of characters in zName */
3940 int i, j;
3941 DbFixer sFix; /* For assigning database names to pTable */
3942 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
3943 sqlite3 *db = pParse->db;
3944 Db *pDb; /* The specific table containing the indexed database */
3945 int iDb; /* Index of the database that is being written */
3946 Token *pName = 0; /* Unqualified name of the index to create */
3947 struct ExprList_item *pListItem; /* For looping over pList */
3948 int nExtra = 0; /* Space allocated for zExtra[] */
3949 int nExtraCol; /* Number of extra columns needed */
3950 char *zExtra = 0; /* Extra space after the Index object */
3951 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
3953 assert( db->pParse==pParse );
3954 if( pParse->nErr ){
3955 goto exit_create_index;
3957 assert( db->mallocFailed==0 );
3958 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3959 goto exit_create_index;
3961 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3962 goto exit_create_index;
3964 if( sqlite3HasExplicitNulls(pParse, pList) ){
3965 goto exit_create_index;
3969 ** Find the table that is to be indexed. Return early if not found.
3971 if( pTblName!=0 ){
3973 /* Use the two-part index name to determine the database
3974 ** to search for the table. 'Fix' the table name to this db
3975 ** before looking up the table.
3977 assert( pName1 && pName2 );
3978 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3979 if( iDb<0 ) goto exit_create_index;
3980 assert( pName && pName->z );
3982 #ifndef SQLITE_OMIT_TEMPDB
3983 /* If the index name was unqualified, check if the table
3984 ** is a temp table. If so, set the database to 1. Do not do this
3985 ** if initializing a database schema.
3987 if( !db->init.busy ){
3988 pTab = sqlite3SrcListLookup(pParse, pTblName);
3989 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3990 iDb = 1;
3993 #endif
3995 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3996 if( sqlite3FixSrcList(&sFix, pTblName) ){
3997 /* Because the parser constructs pTblName from a single identifier,
3998 ** sqlite3FixSrcList can never fail. */
3999 assert(0);
4001 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
4002 assert( db->mallocFailed==0 || pTab==0 );
4003 if( pTab==0 ) goto exit_create_index;
4004 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
4005 sqlite3ErrorMsg(pParse,
4006 "cannot create a TEMP index on non-TEMP table \"%s\"",
4007 pTab->zName);
4008 goto exit_create_index;
4010 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
4011 }else{
4012 assert( pName==0 );
4013 assert( pStart==0 );
4014 pTab = pParse->pNewTable;
4015 if( !pTab ) goto exit_create_index;
4016 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4018 pDb = &db->aDb[iDb];
4020 assert( pTab!=0 );
4021 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
4022 && db->init.busy==0
4023 && pTblName!=0
4024 #if SQLITE_USER_AUTHENTICATION
4025 && sqlite3UserAuthTable(pTab->zName)==0
4026 #endif
4028 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
4029 goto exit_create_index;
4031 #ifndef SQLITE_OMIT_VIEW
4032 if( IsView(pTab) ){
4033 sqlite3ErrorMsg(pParse, "views may not be indexed");
4034 goto exit_create_index;
4036 #endif
4037 #ifndef SQLITE_OMIT_VIRTUALTABLE
4038 if( IsVirtual(pTab) ){
4039 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
4040 goto exit_create_index;
4042 #endif
4045 ** Find the name of the index. Make sure there is not already another
4046 ** index or table with the same name.
4048 ** Exception: If we are reading the names of permanent indices from the
4049 ** sqlite_schema table (because some other process changed the schema) and
4050 ** one of the index names collides with the name of a temporary table or
4051 ** index, then we will continue to process this index.
4053 ** If pName==0 it means that we are
4054 ** dealing with a primary key or UNIQUE constraint. We have to invent our
4055 ** own name.
4057 if( pName ){
4058 zName = sqlite3NameFromToken(db, pName);
4059 if( zName==0 ) goto exit_create_index;
4060 assert( pName->z!=0 );
4061 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
4062 goto exit_create_index;
4064 if( !IN_RENAME_OBJECT ){
4065 if( !db->init.busy ){
4066 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
4067 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
4068 goto exit_create_index;
4071 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
4072 if( !ifNotExist ){
4073 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
4074 }else{
4075 assert( !db->init.busy );
4076 sqlite3CodeVerifySchema(pParse, iDb);
4077 sqlite3ForceNotReadOnly(pParse);
4079 goto exit_create_index;
4082 }else{
4083 int n;
4084 Index *pLoop;
4085 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
4086 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
4087 if( zName==0 ){
4088 goto exit_create_index;
4091 /* Automatic index names generated from within sqlite3_declare_vtab()
4092 ** must have names that are distinct from normal automatic index names.
4093 ** The following statement converts "sqlite3_autoindex..." into
4094 ** "sqlite3_butoindex..." in order to make the names distinct.
4095 ** The "vtab_err.test" test demonstrates the need of this statement. */
4096 if( IN_SPECIAL_PARSE ) zName[7]++;
4099 /* Check for authorization to create an index.
4101 #ifndef SQLITE_OMIT_AUTHORIZATION
4102 if( !IN_RENAME_OBJECT ){
4103 const char *zDb = pDb->zDbSName;
4104 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
4105 goto exit_create_index;
4107 i = SQLITE_CREATE_INDEX;
4108 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
4109 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
4110 goto exit_create_index;
4113 #endif
4115 /* If pList==0, it means this routine was called to make a primary
4116 ** key out of the last column added to the table under construction.
4117 ** So create a fake list to simulate this.
4119 if( pList==0 ){
4120 Token prevCol;
4121 Column *pCol = &pTab->aCol[pTab->nCol-1];
4122 pCol->colFlags |= COLFLAG_UNIQUE;
4123 sqlite3TokenInit(&prevCol, pCol->zCnName);
4124 pList = sqlite3ExprListAppend(pParse, 0,
4125 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
4126 if( pList==0 ) goto exit_create_index;
4127 assert( pList->nExpr==1 );
4128 sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
4129 }else{
4130 sqlite3ExprListCheckLength(pParse, pList, "index");
4131 if( pParse->nErr ) goto exit_create_index;
4134 /* Figure out how many bytes of space are required to store explicitly
4135 ** specified collation sequence names.
4137 for(i=0; i<pList->nExpr; i++){
4138 Expr *pExpr = pList->a[i].pExpr;
4139 assert( pExpr!=0 );
4140 if( pExpr->op==TK_COLLATE ){
4141 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4142 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
4147 ** Allocate the index structure.
4149 nName = sqlite3Strlen30(zName);
4150 nExtraCol = pPk ? pPk->nKeyCol : 1;
4151 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
4152 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
4153 nName + nExtra + 1, &zExtra);
4154 if( db->mallocFailed ){
4155 goto exit_create_index;
4157 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
4158 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
4159 pIndex->zName = zExtra;
4160 zExtra += nName + 1;
4161 memcpy(pIndex->zName, zName, nName+1);
4162 pIndex->pTable = pTab;
4163 pIndex->onError = (u8)onError;
4164 pIndex->uniqNotNull = onError!=OE_None;
4165 pIndex->idxType = idxType;
4166 pIndex->pSchema = db->aDb[iDb].pSchema;
4167 pIndex->nKeyCol = pList->nExpr;
4168 if( pPIWhere ){
4169 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
4170 pIndex->pPartIdxWhere = pPIWhere;
4171 pPIWhere = 0;
4173 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4175 /* Check to see if we should honor DESC requests on index columns
4177 if( pDb->pSchema->file_format>=4 ){
4178 sortOrderMask = -1; /* Honor DESC */
4179 }else{
4180 sortOrderMask = 0; /* Ignore DESC */
4183 /* Analyze the list of expressions that form the terms of the index and
4184 ** report any errors. In the common case where the expression is exactly
4185 ** a table column, store that column in aiColumn[]. For general expressions,
4186 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4188 ** TODO: Issue a warning if two or more columns of the index are identical.
4189 ** TODO: Issue a warning if the table primary key is used as part of the
4190 ** index key.
4192 pListItem = pList->a;
4193 if( IN_RENAME_OBJECT ){
4194 pIndex->aColExpr = pList;
4195 pList = 0;
4197 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
4198 Expr *pCExpr; /* The i-th index expression */
4199 int requestedSortOrder; /* ASC or DESC on the i-th expression */
4200 const char *zColl; /* Collation sequence name */
4202 sqlite3StringToId(pListItem->pExpr);
4203 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
4204 if( pParse->nErr ) goto exit_create_index;
4205 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
4206 if( pCExpr->op!=TK_COLUMN ){
4207 if( pTab==pParse->pNewTable ){
4208 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
4209 "UNIQUE constraints");
4210 goto exit_create_index;
4212 if( pIndex->aColExpr==0 ){
4213 pIndex->aColExpr = pList;
4214 pList = 0;
4216 j = XN_EXPR;
4217 pIndex->aiColumn[i] = XN_EXPR;
4218 pIndex->uniqNotNull = 0;
4219 pIndex->bHasExpr = 1;
4220 }else{
4221 j = pCExpr->iColumn;
4222 assert( j<=0x7fff );
4223 if( j<0 ){
4224 j = pTab->iPKey;
4225 }else{
4226 if( pTab->aCol[j].notNull==0 ){
4227 pIndex->uniqNotNull = 0;
4229 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
4230 pIndex->bHasVCol = 1;
4231 pIndex->bHasExpr = 1;
4234 pIndex->aiColumn[i] = (i16)j;
4236 zColl = 0;
4237 if( pListItem->pExpr->op==TK_COLLATE ){
4238 int nColl;
4239 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
4240 zColl = pListItem->pExpr->u.zToken;
4241 nColl = sqlite3Strlen30(zColl) + 1;
4242 assert( nExtra>=nColl );
4243 memcpy(zExtra, zColl, nColl);
4244 zColl = zExtra;
4245 zExtra += nColl;
4246 nExtra -= nColl;
4247 }else if( j>=0 ){
4248 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
4250 if( !zColl ) zColl = sqlite3StrBINARY;
4251 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
4252 goto exit_create_index;
4254 pIndex->azColl[i] = zColl;
4255 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
4256 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
4259 /* Append the table key to the end of the index. For WITHOUT ROWID
4260 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
4261 ** normal tables (when pPk==0) this will be the rowid.
4263 if( pPk ){
4264 for(j=0; j<pPk->nKeyCol; j++){
4265 int x = pPk->aiColumn[j];
4266 assert( x>=0 );
4267 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
4268 pIndex->nColumn--;
4269 }else{
4270 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
4271 pIndex->aiColumn[i] = x;
4272 pIndex->azColl[i] = pPk->azColl[j];
4273 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
4274 i++;
4277 assert( i==pIndex->nColumn );
4278 }else{
4279 pIndex->aiColumn[i] = XN_ROWID;
4280 pIndex->azColl[i] = sqlite3StrBINARY;
4282 sqlite3DefaultRowEst(pIndex);
4283 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
4285 /* If this index contains every column of its table, then mark
4286 ** it as a covering index */
4287 assert( HasRowid(pTab)
4288 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
4289 recomputeColumnsNotIndexed(pIndex);
4290 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
4291 pIndex->isCovering = 1;
4292 for(j=0; j<pTab->nCol; j++){
4293 if( j==pTab->iPKey ) continue;
4294 if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
4295 pIndex->isCovering = 0;
4296 break;
4300 if( pTab==pParse->pNewTable ){
4301 /* This routine has been called to create an automatic index as a
4302 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4303 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4304 ** i.e. one of:
4306 ** CREATE TABLE t(x PRIMARY KEY, y);
4307 ** CREATE TABLE t(x, y, UNIQUE(x, y));
4309 ** Either way, check to see if the table already has such an index. If
4310 ** so, don't bother creating this one. This only applies to
4311 ** automatically created indices. Users can do as they wish with
4312 ** explicit indices.
4314 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4315 ** (and thus suppressing the second one) even if they have different
4316 ** sort orders.
4318 ** If there are different collating sequences or if the columns of
4319 ** the constraint occur in different orders, then the constraints are
4320 ** considered distinct and both result in separate indices.
4322 Index *pIdx;
4323 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4324 int k;
4325 assert( IsUniqueIndex(pIdx) );
4326 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
4327 assert( IsUniqueIndex(pIndex) );
4329 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
4330 for(k=0; k<pIdx->nKeyCol; k++){
4331 const char *z1;
4332 const char *z2;
4333 assert( pIdx->aiColumn[k]>=0 );
4334 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
4335 z1 = pIdx->azColl[k];
4336 z2 = pIndex->azColl[k];
4337 if( sqlite3StrICmp(z1, z2) ) break;
4339 if( k==pIdx->nKeyCol ){
4340 if( pIdx->onError!=pIndex->onError ){
4341 /* This constraint creates the same index as a previous
4342 ** constraint specified somewhere in the CREATE TABLE statement.
4343 ** However the ON CONFLICT clauses are different. If both this
4344 ** constraint and the previous equivalent constraint have explicit
4345 ** ON CONFLICT clauses this is an error. Otherwise, use the
4346 ** explicitly specified behavior for the index.
4348 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
4349 sqlite3ErrorMsg(pParse,
4350 "conflicting ON CONFLICT clauses specified", 0);
4352 if( pIdx->onError==OE_Default ){
4353 pIdx->onError = pIndex->onError;
4356 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
4357 if( IN_RENAME_OBJECT ){
4358 pIndex->pNext = pParse->pNewIndex;
4359 pParse->pNewIndex = pIndex;
4360 pIndex = 0;
4362 goto exit_create_index;
4367 if( !IN_RENAME_OBJECT ){
4369 /* Link the new Index structure to its table and to the other
4370 ** in-memory database structures.
4372 assert( pParse->nErr==0 );
4373 if( db->init.busy ){
4374 Index *p;
4375 assert( !IN_SPECIAL_PARSE );
4376 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
4377 if( pTblName!=0 ){
4378 pIndex->tnum = db->init.newTnum;
4379 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
4380 sqlite3ErrorMsg(pParse, "invalid rootpage");
4381 pParse->rc = SQLITE_CORRUPT_BKPT;
4382 goto exit_create_index;
4385 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
4386 pIndex->zName, pIndex);
4387 if( p ){
4388 assert( p==pIndex ); /* Malloc must have failed */
4389 sqlite3OomFault(db);
4390 goto exit_create_index;
4392 db->mDbFlags |= DBFLAG_SchemaChange;
4395 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4396 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4397 ** emit code to allocate the index rootpage on disk and make an entry for
4398 ** the index in the sqlite_schema table and populate the index with
4399 ** content. But, do not do this if we are simply reading the sqlite_schema
4400 ** table to parse the schema, or if this index is the PRIMARY KEY index
4401 ** of a WITHOUT ROWID table.
4403 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4404 ** or UNIQUE index in a CREATE TABLE statement. Since the table
4405 ** has just been created, it contains no data and the index initialization
4406 ** step can be skipped.
4408 else if( HasRowid(pTab) || pTblName!=0 ){
4409 Vdbe *v;
4410 char *zStmt;
4411 int iMem = ++pParse->nMem;
4413 v = sqlite3GetVdbe(pParse);
4414 if( v==0 ) goto exit_create_index;
4416 sqlite3BeginWriteOperation(pParse, 1, iDb);
4418 /* Create the rootpage for the index using CreateIndex. But before
4419 ** doing so, code a Noop instruction and store its address in
4420 ** Index.tnum. This is required in case this index is actually a
4421 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4422 ** that case the convertToWithoutRowidTable() routine will replace
4423 ** the Noop with a Goto to jump over the VDBE code generated below. */
4424 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
4425 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
4427 /* Gather the complete text of the CREATE INDEX statement into
4428 ** the zStmt variable
4430 assert( pName!=0 || pStart==0 );
4431 if( pStart ){
4432 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
4433 if( pName->z[n-1]==';' ) n--;
4434 /* A named index with an explicit CREATE INDEX statement */
4435 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
4436 onError==OE_None ? "" : " UNIQUE", n, pName->z);
4437 }else{
4438 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4439 /* zStmt = sqlite3MPrintf(""); */
4440 zStmt = 0;
4443 /* Add an entry in sqlite_schema for this index
4445 sqlite3NestedParse(pParse,
4446 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
4447 db->aDb[iDb].zDbSName,
4448 pIndex->zName,
4449 pTab->zName,
4450 iMem,
4451 zStmt
4453 sqlite3DbFree(db, zStmt);
4455 /* Fill the index with data and reparse the schema. Code an OP_Expire
4456 ** to invalidate all pre-compiled statements.
4458 if( pTblName ){
4459 sqlite3RefillIndex(pParse, pIndex, iMem);
4460 sqlite3ChangeCookie(pParse, iDb);
4461 sqlite3VdbeAddParseSchemaOp(v, iDb,
4462 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
4463 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
4466 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
4469 if( db->init.busy || pTblName==0 ){
4470 pIndex->pNext = pTab->pIndex;
4471 pTab->pIndex = pIndex;
4472 pIndex = 0;
4474 else if( IN_RENAME_OBJECT ){
4475 assert( pParse->pNewIndex==0 );
4476 pParse->pNewIndex = pIndex;
4477 pIndex = 0;
4480 /* Clean up before exiting */
4481 exit_create_index:
4482 if( pIndex ) sqlite3FreeIndex(db, pIndex);
4483 if( pTab ){
4484 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
4485 ** The list was already ordered when this routine was entered, so at this
4486 ** point at most a single index (the newly added index) will be out of
4487 ** order. So we have to reorder at most one index. */
4488 Index **ppFrom;
4489 Index *pThis;
4490 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
4491 Index *pNext;
4492 if( pThis->onError!=OE_Replace ) continue;
4493 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4494 *ppFrom = pNext;
4495 pThis->pNext = pNext->pNext;
4496 pNext->pNext = pThis;
4497 ppFrom = &pNext->pNext;
4499 break;
4501 #ifdef SQLITE_DEBUG
4502 /* Verify that all REPLACE indexes really are now at the end
4503 ** of the index list. In other words, no other index type ever
4504 ** comes after a REPLACE index on the list. */
4505 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
4506 assert( pThis->onError!=OE_Replace
4507 || pThis->pNext==0
4508 || pThis->pNext->onError==OE_Replace );
4510 #endif
4512 sqlite3ExprDelete(db, pPIWhere);
4513 sqlite3ExprListDelete(db, pList);
4514 sqlite3SrcListDelete(db, pTblName);
4515 sqlite3DbFree(db, zName);
4519 ** Fill the Index.aiRowEst[] array with default information - information
4520 ** to be used when we have not run the ANALYZE command.
4522 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4523 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
4524 ** number of rows in the table that match any particular value of the
4525 ** first column of the index. aiRowEst[2] is an estimate of the number
4526 ** of rows that match any particular combination of the first 2 columns
4527 ** of the index. And so forth. It must always be the case that
4529 ** aiRowEst[N]<=aiRowEst[N-1]
4530 ** aiRowEst[N]>=1
4532 ** Apart from that, we have little to go on besides intuition as to
4533 ** how aiRowEst[] should be initialized. The numbers generated here
4534 ** are based on typical values found in actual indices.
4536 void sqlite3DefaultRowEst(Index *pIdx){
4537 /* 10, 9, 8, 7, 6 */
4538 static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
4539 LogEst *a = pIdx->aiRowLogEst;
4540 LogEst x;
4541 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
4542 int i;
4544 /* Indexes with default row estimates should not have stat1 data */
4545 assert( !pIdx->hasStat1 );
4547 /* Set the first entry (number of rows in the index) to the estimated
4548 ** number of rows in the table, or half the number of rows in the table
4549 ** for a partial index.
4551 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
4552 ** table but other parts we are having to guess at, then do not let the
4553 ** estimated number of rows in the table be less than 1000 (LogEst 99).
4554 ** Failure to do this can cause the indexes for which we do not have
4555 ** stat1 data to be ignored by the query planner.
4557 x = pIdx->pTable->nRowLogEst;
4558 assert( 99==sqlite3LogEst(1000) );
4559 if( x<99 ){
4560 pIdx->pTable->nRowLogEst = x = 99;
4562 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
4563 a[0] = x;
4565 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4566 ** 6 and each subsequent value (if any) is 5. */
4567 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4568 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4569 a[i] = 23; assert( 23==sqlite3LogEst(5) );
4572 assert( 0==sqlite3LogEst(1) );
4573 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
4577 ** This routine will drop an existing named index. This routine
4578 ** implements the DROP INDEX statement.
4580 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
4581 Index *pIndex;
4582 Vdbe *v;
4583 sqlite3 *db = pParse->db;
4584 int iDb;
4586 if( db->mallocFailed ){
4587 goto exit_drop_index;
4589 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
4590 assert( pName->nSrc==1 );
4591 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4592 goto exit_drop_index;
4594 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
4595 if( pIndex==0 ){
4596 if( !ifExists ){
4597 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
4598 }else{
4599 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
4600 sqlite3ForceNotReadOnly(pParse);
4602 pParse->checkSchema = 1;
4603 goto exit_drop_index;
4605 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
4606 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4607 "or PRIMARY KEY constraint cannot be dropped", 0);
4608 goto exit_drop_index;
4610 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4611 #ifndef SQLITE_OMIT_AUTHORIZATION
4613 int code = SQLITE_DROP_INDEX;
4614 Table *pTab = pIndex->pTable;
4615 const char *zDb = db->aDb[iDb].zDbSName;
4616 const char *zTab = SCHEMA_TABLE(iDb);
4617 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4618 goto exit_drop_index;
4620 if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
4621 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4622 goto exit_drop_index;
4625 #endif
4627 /* Generate code to remove the index and from the schema table */
4628 v = sqlite3GetVdbe(pParse);
4629 if( v ){
4630 sqlite3BeginWriteOperation(pParse, 1, iDb);
4631 sqlite3NestedParse(pParse,
4632 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
4633 db->aDb[iDb].zDbSName, pIndex->zName
4635 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
4636 sqlite3ChangeCookie(pParse, iDb);
4637 destroyRootPage(pParse, pIndex->tnum, iDb);
4638 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
4641 exit_drop_index:
4642 sqlite3SrcListDelete(db, pName);
4646 ** pArray is a pointer to an array of objects. Each object in the
4647 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4648 ** to extend the array so that there is space for a new object at the end.
4650 ** When this function is called, *pnEntry contains the current size of
4651 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4652 ** in total).
4654 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4655 ** space allocated for the new object is zeroed, *pnEntry updated to
4656 ** reflect the new size of the array and a pointer to the new allocation
4657 ** returned. *pIdx is set to the index of the new array entry in this case.
4659 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4660 ** unchanged and a copy of pArray returned.
4662 void *sqlite3ArrayAllocate(
4663 sqlite3 *db, /* Connection to notify of malloc failures */
4664 void *pArray, /* Array of objects. Might be reallocated */
4665 int szEntry, /* Size of each object in the array */
4666 int *pnEntry, /* Number of objects currently in use */
4667 int *pIdx /* Write the index of a new slot here */
4669 char *z;
4670 sqlite3_int64 n = *pIdx = *pnEntry;
4671 if( (n & (n-1))==0 ){
4672 sqlite3_int64 sz = (n==0) ? 1 : 2*n;
4673 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
4674 if( pNew==0 ){
4675 *pIdx = -1;
4676 return pArray;
4678 pArray = pNew;
4680 z = (char*)pArray;
4681 memset(&z[n * szEntry], 0, szEntry);
4682 ++*pnEntry;
4683 return pArray;
4687 ** Append a new element to the given IdList. Create a new IdList if
4688 ** need be.
4690 ** A new IdList is returned, or NULL if malloc() fails.
4692 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
4693 sqlite3 *db = pParse->db;
4694 int i;
4695 if( pList==0 ){
4696 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
4697 if( pList==0 ) return 0;
4698 }else{
4699 IdList *pNew;
4700 pNew = sqlite3DbRealloc(db, pList,
4701 sizeof(IdList) + pList->nId*sizeof(pList->a));
4702 if( pNew==0 ){
4703 sqlite3IdListDelete(db, pList);
4704 return 0;
4706 pList = pNew;
4708 i = pList->nId++;
4709 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4710 if( IN_RENAME_OBJECT && pList->a[i].zName ){
4711 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
4713 return pList;
4717 ** Delete an IdList.
4719 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4720 int i;
4721 assert( db!=0 );
4722 if( pList==0 ) return;
4723 assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */
4724 for(i=0; i<pList->nId; i++){
4725 sqlite3DbFree(db, pList->a[i].zName);
4727 sqlite3DbNNFreeNN(db, pList);
4731 ** Return the index in pList of the identifier named zId. Return -1
4732 ** if not found.
4734 int sqlite3IdListIndex(IdList *pList, const char *zName){
4735 int i;
4736 assert( pList!=0 );
4737 for(i=0; i<pList->nId; i++){
4738 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4740 return -1;
4744 ** Maximum size of a SrcList object.
4745 ** The SrcList object is used to represent the FROM clause of a
4746 ** SELECT statement, and the query planner cannot deal with more
4747 ** than 64 tables in a join. So any value larger than 64 here
4748 ** is sufficient for most uses. Smaller values, like say 10, are
4749 ** appropriate for small and memory-limited applications.
4751 #ifndef SQLITE_MAX_SRCLIST
4752 # define SQLITE_MAX_SRCLIST 200
4753 #endif
4756 ** Expand the space allocated for the given SrcList object by
4757 ** creating nExtra new slots beginning at iStart. iStart is zero based.
4758 ** New slots are zeroed.
4760 ** For example, suppose a SrcList initially contains two entries: A,B.
4761 ** To append 3 new entries onto the end, do this:
4763 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4765 ** After the call above it would contain: A, B, nil, nil, nil.
4766 ** If the iStart argument had been 1 instead of 2, then the result
4767 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
4768 ** the iStart value would be 0. The result then would
4769 ** be: nil, nil, nil, A, B.
4771 ** If a memory allocation fails or the SrcList becomes too large, leave
4772 ** the original SrcList unchanged, return NULL, and leave an error message
4773 ** in pParse.
4775 SrcList *sqlite3SrcListEnlarge(
4776 Parse *pParse, /* Parsing context into which errors are reported */
4777 SrcList *pSrc, /* The SrcList to be enlarged */
4778 int nExtra, /* Number of new slots to add to pSrc->a[] */
4779 int iStart /* Index in pSrc->a[] of first new slot */
4781 int i;
4783 /* Sanity checking on calling parameters */
4784 assert( iStart>=0 );
4785 assert( nExtra>=1 );
4786 assert( pSrc!=0 );
4787 assert( iStart<=pSrc->nSrc );
4789 /* Allocate additional space if needed */
4790 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4791 SrcList *pNew;
4792 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4793 sqlite3 *db = pParse->db;
4795 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4796 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4797 SQLITE_MAX_SRCLIST);
4798 return 0;
4800 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4801 pNew = sqlite3DbRealloc(db, pSrc,
4802 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4803 if( pNew==0 ){
4804 assert( db->mallocFailed );
4805 return 0;
4807 pSrc = pNew;
4808 pSrc->nAlloc = nAlloc;
4811 /* Move existing slots that come after the newly inserted slots
4812 ** out of the way */
4813 for(i=pSrc->nSrc-1; i>=iStart; i--){
4814 pSrc->a[i+nExtra] = pSrc->a[i];
4816 pSrc->nSrc += nExtra;
4818 /* Zero the newly allocated slots */
4819 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4820 for(i=iStart; i<iStart+nExtra; i++){
4821 pSrc->a[i].iCursor = -1;
4824 /* Return a pointer to the enlarged SrcList */
4825 return pSrc;
4830 ** Append a new table name to the given SrcList. Create a new SrcList if
4831 ** need be. A new entry is created in the SrcList even if pTable is NULL.
4833 ** A SrcList is returned, or NULL if there is an OOM error or if the
4834 ** SrcList grows to large. The returned
4835 ** SrcList might be the same as the SrcList that was input or it might be
4836 ** a new one. If an OOM error does occurs, then the prior value of pList
4837 ** that is input to this routine is automatically freed.
4839 ** If pDatabase is not null, it means that the table has an optional
4840 ** database name prefix. Like this: "database.table". The pDatabase
4841 ** points to the table name and the pTable points to the database name.
4842 ** The SrcList.a[].zName field is filled with the table name which might
4843 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4844 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4845 ** or with NULL if no database is specified.
4847 ** In other words, if call like this:
4849 ** sqlite3SrcListAppend(D,A,B,0);
4851 ** Then B is a table name and the database name is unspecified. If called
4852 ** like this:
4854 ** sqlite3SrcListAppend(D,A,B,C);
4856 ** Then C is the table name and B is the database name. If C is defined
4857 ** then so is B. In other words, we never have a case where:
4859 ** sqlite3SrcListAppend(D,A,0,C);
4861 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
4862 ** before being added to the SrcList.
4864 SrcList *sqlite3SrcListAppend(
4865 Parse *pParse, /* Parsing context, in which errors are reported */
4866 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
4867 Token *pTable, /* Table to append */
4868 Token *pDatabase /* Database of the table */
4870 SrcItem *pItem;
4871 sqlite3 *db;
4872 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
4873 assert( pParse!=0 );
4874 assert( pParse->db!=0 );
4875 db = pParse->db;
4876 if( pList==0 ){
4877 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4878 if( pList==0 ) return 0;
4879 pList->nAlloc = 1;
4880 pList->nSrc = 1;
4881 memset(&pList->a[0], 0, sizeof(pList->a[0]));
4882 pList->a[0].iCursor = -1;
4883 }else{
4884 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4885 if( pNew==0 ){
4886 sqlite3SrcListDelete(db, pList);
4887 return 0;
4888 }else{
4889 pList = pNew;
4892 pItem = &pList->a[pList->nSrc-1];
4893 if( pDatabase && pDatabase->z==0 ){
4894 pDatabase = 0;
4896 if( pDatabase ){
4897 pItem->zName = sqlite3NameFromToken(db, pDatabase);
4898 pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4899 }else{
4900 pItem->zName = sqlite3NameFromToken(db, pTable);
4901 pItem->zDatabase = 0;
4903 return pList;
4907 ** Assign VdbeCursor index numbers to all tables in a SrcList
4909 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4910 int i;
4911 SrcItem *pItem;
4912 assert( pList || pParse->db->mallocFailed );
4913 if( ALWAYS(pList) ){
4914 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4915 if( pItem->iCursor>=0 ) continue;
4916 pItem->iCursor = pParse->nTab++;
4917 if( pItem->pSelect ){
4918 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4925 ** Delete an entire SrcList including all its substructure.
4927 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4928 int i;
4929 SrcItem *pItem;
4930 assert( db!=0 );
4931 if( pList==0 ) return;
4932 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4933 if( pItem->zDatabase ) sqlite3DbNNFreeNN(db, pItem->zDatabase);
4934 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
4935 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
4936 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4937 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4938 sqlite3DeleteTable(db, pItem->pTab);
4939 if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
4940 if( pItem->fg.isUsing ){
4941 sqlite3IdListDelete(db, pItem->u3.pUsing);
4942 }else if( pItem->u3.pOn ){
4943 sqlite3ExprDelete(db, pItem->u3.pOn);
4946 sqlite3DbNNFreeNN(db, pList);
4950 ** This routine is called by the parser to add a new term to the
4951 ** end of a growing FROM clause. The "p" parameter is the part of
4952 ** the FROM clause that has already been constructed. "p" is NULL
4953 ** if this is the first term of the FROM clause. pTable and pDatabase
4954 ** are the name of the table and database named in the FROM clause term.
4955 ** pDatabase is NULL if the database name qualifier is missing - the
4956 ** usual case. If the term has an alias, then pAlias points to the
4957 ** alias token. If the term is a subquery, then pSubquery is the
4958 ** SELECT statement that the subquery encodes. The pTable and
4959 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
4960 ** parameters are the content of the ON and USING clauses.
4962 ** Return a new SrcList which encodes is the FROM with the new
4963 ** term added.
4965 SrcList *sqlite3SrcListAppendFromTerm(
4966 Parse *pParse, /* Parsing context */
4967 SrcList *p, /* The left part of the FROM clause already seen */
4968 Token *pTable, /* Name of the table to add to the FROM clause */
4969 Token *pDatabase, /* Name of the database containing pTable */
4970 Token *pAlias, /* The right-hand side of the AS subexpression */
4971 Select *pSubquery, /* A subquery used in place of a table name */
4972 OnOrUsing *pOnUsing /* Either the ON clause or the USING clause */
4974 SrcItem *pItem;
4975 sqlite3 *db = pParse->db;
4976 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
4977 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4978 (pOnUsing->pOn ? "ON" : "USING")
4980 goto append_from_error;
4982 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4983 if( p==0 ){
4984 goto append_from_error;
4986 assert( p->nSrc>0 );
4987 pItem = &p->a[p->nSrc-1];
4988 assert( (pTable==0)==(pDatabase==0) );
4989 assert( pItem->zName==0 || pDatabase!=0 );
4990 if( IN_RENAME_OBJECT && pItem->zName ){
4991 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4992 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4994 assert( pAlias!=0 );
4995 if( pAlias->n ){
4996 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4998 if( pSubquery ){
4999 pItem->pSelect = pSubquery;
5000 if( pSubquery->selFlags & SF_NestedFrom ){
5001 pItem->fg.isNestedFrom = 1;
5004 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
5005 assert( pItem->fg.isUsing==0 );
5006 if( pOnUsing==0 ){
5007 pItem->u3.pOn = 0;
5008 }else if( pOnUsing->pUsing ){
5009 pItem->fg.isUsing = 1;
5010 pItem->u3.pUsing = pOnUsing->pUsing;
5011 }else{
5012 pItem->u3.pOn = pOnUsing->pOn;
5014 return p;
5016 append_from_error:
5017 assert( p==0 );
5018 sqlite3ClearOnOrUsing(db, pOnUsing);
5019 sqlite3SelectDelete(db, pSubquery);
5020 return 0;
5024 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5025 ** element of the source-list passed as the second argument.
5027 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
5028 assert( pIndexedBy!=0 );
5029 if( p && pIndexedBy->n>0 ){
5030 SrcItem *pItem;
5031 assert( p->nSrc>0 );
5032 pItem = &p->a[p->nSrc-1];
5033 assert( pItem->fg.notIndexed==0 );
5034 assert( pItem->fg.isIndexedBy==0 );
5035 assert( pItem->fg.isTabFunc==0 );
5036 if( pIndexedBy->n==1 && !pIndexedBy->z ){
5037 /* A "NOT INDEXED" clause was supplied. See parse.y
5038 ** construct "indexed_opt" for details. */
5039 pItem->fg.notIndexed = 1;
5040 }else{
5041 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
5042 pItem->fg.isIndexedBy = 1;
5043 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
5049 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
5050 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
5051 ** are deleted by this function.
5053 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
5054 assert( p1 && p1->nSrc==1 );
5055 if( p2 ){
5056 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
5057 if( pNew==0 ){
5058 sqlite3SrcListDelete(pParse->db, p2);
5059 }else{
5060 p1 = pNew;
5061 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
5062 sqlite3DbFree(pParse->db, p2);
5063 p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
5066 return p1;
5070 ** Add the list of function arguments to the SrcList entry for a
5071 ** table-valued-function.
5073 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
5074 if( p ){
5075 SrcItem *pItem = &p->a[p->nSrc-1];
5076 assert( pItem->fg.notIndexed==0 );
5077 assert( pItem->fg.isIndexedBy==0 );
5078 assert( pItem->fg.isTabFunc==0 );
5079 pItem->u1.pFuncArg = pList;
5080 pItem->fg.isTabFunc = 1;
5081 }else{
5082 sqlite3ExprListDelete(pParse->db, pList);
5087 ** When building up a FROM clause in the parser, the join operator
5088 ** is initially attached to the left operand. But the code generator
5089 ** expects the join operator to be on the right operand. This routine
5090 ** Shifts all join operators from left to right for an entire FROM
5091 ** clause.
5093 ** Example: Suppose the join is like this:
5095 ** A natural cross join B
5097 ** The operator is "natural cross join". The A and B operands are stored
5098 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
5099 ** operator with A. This routine shifts that operator over to B.
5101 ** Additional changes:
5103 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
5104 ** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
5105 ** code generator can easily tell that the table is part of
5106 ** the left operand of at least one RIGHT JOIN.
5108 void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
5109 (void)pParse;
5110 if( p && p->nSrc>1 ){
5111 int i = p->nSrc-1;
5112 u8 allFlags = 0;
5114 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
5115 }while( (--i)>0 );
5116 p->a[0].fg.jointype = 0;
5118 /* All terms to the left of a RIGHT JOIN should be tagged with the
5119 ** JT_LTORJ flags */
5120 if( allFlags & JT_RIGHT ){
5121 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
5122 i--;
5123 assert( i>=0 );
5125 p->a[i].fg.jointype |= JT_LTORJ;
5126 }while( (--i)>=0 );
5132 ** Generate VDBE code for a BEGIN statement.
5134 void sqlite3BeginTransaction(Parse *pParse, int type){
5135 sqlite3 *db;
5136 Vdbe *v;
5137 int i;
5139 assert( pParse!=0 );
5140 db = pParse->db;
5141 assert( db!=0 );
5142 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
5143 return;
5145 v = sqlite3GetVdbe(pParse);
5146 if( !v ) return;
5147 if( type!=TK_DEFERRED ){
5148 for(i=0; i<db->nDb; i++){
5149 int eTxnType;
5150 Btree *pBt = db->aDb[i].pBt;
5151 if( pBt && sqlite3BtreeIsReadonly(pBt) ){
5152 eTxnType = 0; /* Read txn */
5153 }else if( type==TK_EXCLUSIVE ){
5154 eTxnType = 2; /* Exclusive txn */
5155 }else{
5156 eTxnType = 1; /* Write txn */
5158 sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
5159 sqlite3VdbeUsesBtree(v, i);
5162 sqlite3VdbeAddOp0(v, OP_AutoCommit);
5166 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
5167 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
5168 ** code is generated for a COMMIT.
5170 void sqlite3EndTransaction(Parse *pParse, int eType){
5171 Vdbe *v;
5172 int isRollback;
5174 assert( pParse!=0 );
5175 assert( pParse->db!=0 );
5176 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
5177 isRollback = eType==TK_ROLLBACK;
5178 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
5179 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
5180 return;
5182 v = sqlite3GetVdbe(pParse);
5183 if( v ){
5184 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
5189 ** This function is called by the parser when it parses a command to create,
5190 ** release or rollback an SQL savepoint.
5192 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
5193 char *zName = sqlite3NameFromToken(pParse->db, pName);
5194 if( zName ){
5195 Vdbe *v = sqlite3GetVdbe(pParse);
5196 #ifndef SQLITE_OMIT_AUTHORIZATION
5197 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5198 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
5199 #endif
5200 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
5201 sqlite3DbFree(pParse->db, zName);
5202 return;
5204 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
5209 ** Make sure the TEMP database is open and available for use. Return
5210 ** the number of errors. Leave any error messages in the pParse structure.
5212 int sqlite3OpenTempDatabase(Parse *pParse){
5213 sqlite3 *db = pParse->db;
5214 if( db->aDb[1].pBt==0 && !pParse->explain ){
5215 int rc;
5216 Btree *pBt;
5217 static const int flags =
5218 SQLITE_OPEN_READWRITE |
5219 SQLITE_OPEN_CREATE |
5220 SQLITE_OPEN_EXCLUSIVE |
5221 SQLITE_OPEN_DELETEONCLOSE |
5222 SQLITE_OPEN_TEMP_DB;
5224 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
5225 if( rc!=SQLITE_OK ){
5226 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
5227 "file for storing temporary tables");
5228 pParse->rc = rc;
5229 return 1;
5231 db->aDb[1].pBt = pBt;
5232 assert( db->aDb[1].pSchema );
5233 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
5234 sqlite3OomFault(db);
5235 return 1;
5238 return 0;
5242 ** Record the fact that the schema cookie will need to be verified
5243 ** for database iDb. The code to actually verify the schema cookie
5244 ** will occur at the end of the top-level VDBE and will be generated
5245 ** later, by sqlite3FinishCoding().
5247 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
5248 assert( iDb>=0 && iDb<pToplevel->db->nDb );
5249 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
5250 assert( iDb<SQLITE_MAX_DB );
5251 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
5252 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
5253 DbMaskSet(pToplevel->cookieMask, iDb);
5254 if( !OMIT_TEMPDB && iDb==1 ){
5255 sqlite3OpenTempDatabase(pToplevel);
5259 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
5260 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
5265 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
5266 ** attached database. Otherwise, invoke it for the database named zDb only.
5268 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
5269 sqlite3 *db = pParse->db;
5270 int i;
5271 for(i=0; i<db->nDb; i++){
5272 Db *pDb = &db->aDb[i];
5273 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
5274 sqlite3CodeVerifySchema(pParse, i);
5280 ** Generate VDBE code that prepares for doing an operation that
5281 ** might change the database.
5283 ** This routine starts a new transaction if we are not already within
5284 ** a transaction. If we are already within a transaction, then a checkpoint
5285 ** is set if the setStatement parameter is true. A checkpoint should
5286 ** be set for operations that might fail (due to a constraint) part of
5287 ** the way through and which will need to undo some writes without having to
5288 ** rollback the whole transaction. For operations where all constraints
5289 ** can be checked before any changes are made to the database, it is never
5290 ** necessary to undo a write and the checkpoint should not be set.
5292 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
5293 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5294 sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
5295 DbMaskSet(pToplevel->writeMask, iDb);
5296 pToplevel->isMultiWrite |= setStatement;
5300 ** Indicate that the statement currently under construction might write
5301 ** more than one entry (example: deleting one row then inserting another,
5302 ** inserting multiple rows in a table, or inserting a row and index entries.)
5303 ** If an abort occurs after some of these writes have completed, then it will
5304 ** be necessary to undo the completed writes.
5306 void sqlite3MultiWrite(Parse *pParse){
5307 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5308 pToplevel->isMultiWrite = 1;
5312 ** The code generator calls this routine if is discovers that it is
5313 ** possible to abort a statement prior to completion. In order to
5314 ** perform this abort without corrupting the database, we need to make
5315 ** sure that the statement is protected by a statement transaction.
5317 ** Technically, we only need to set the mayAbort flag if the
5318 ** isMultiWrite flag was previously set. There is a time dependency
5319 ** such that the abort must occur after the multiwrite. This makes
5320 ** some statements involving the REPLACE conflict resolution algorithm
5321 ** go a little faster. But taking advantage of this time dependency
5322 ** makes it more difficult to prove that the code is correct (in
5323 ** particular, it prevents us from writing an effective
5324 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
5325 ** to take the safe route and skip the optimization.
5327 void sqlite3MayAbort(Parse *pParse){
5328 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5329 pToplevel->mayAbort = 1;
5333 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5334 ** error. The onError parameter determines which (if any) of the statement
5335 ** and/or current transaction is rolled back.
5337 void sqlite3HaltConstraint(
5338 Parse *pParse, /* Parsing context */
5339 int errCode, /* extended error code */
5340 int onError, /* Constraint type */
5341 char *p4, /* Error message */
5342 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
5343 u8 p5Errmsg /* P5_ErrMsg type */
5345 Vdbe *v;
5346 assert( pParse->pVdbe!=0 );
5347 v = sqlite3GetVdbe(pParse);
5348 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
5349 if( onError==OE_Abort ){
5350 sqlite3MayAbort(pParse);
5352 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
5353 sqlite3VdbeChangeP5(v, p5Errmsg);
5357 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5359 void sqlite3UniqueConstraint(
5360 Parse *pParse, /* Parsing context */
5361 int onError, /* Constraint type */
5362 Index *pIdx /* The index that triggers the constraint */
5364 char *zErr;
5365 int j;
5366 StrAccum errMsg;
5367 Table *pTab = pIdx->pTable;
5369 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
5370 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
5371 if( pIdx->aColExpr ){
5372 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
5373 }else{
5374 for(j=0; j<pIdx->nKeyCol; j++){
5375 char *zCol;
5376 assert( pIdx->aiColumn[j]>=0 );
5377 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
5378 if( j ) sqlite3_str_append(&errMsg, ", ", 2);
5379 sqlite3_str_appendall(&errMsg, pTab->zName);
5380 sqlite3_str_append(&errMsg, ".", 1);
5381 sqlite3_str_appendall(&errMsg, zCol);
5384 zErr = sqlite3StrAccumFinish(&errMsg);
5385 sqlite3HaltConstraint(pParse,
5386 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
5387 : SQLITE_CONSTRAINT_UNIQUE,
5388 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
5393 ** Code an OP_Halt due to non-unique rowid.
5395 void sqlite3RowidConstraint(
5396 Parse *pParse, /* Parsing context */
5397 int onError, /* Conflict resolution algorithm */
5398 Table *pTab /* The table with the non-unique rowid */
5400 char *zMsg;
5401 int rc;
5402 if( pTab->iPKey>=0 ){
5403 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
5404 pTab->aCol[pTab->iPKey].zCnName);
5405 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
5406 }else{
5407 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
5408 rc = SQLITE_CONSTRAINT_ROWID;
5410 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
5411 P5_ConstraintUnique);
5415 ** Check to see if pIndex uses the collating sequence pColl. Return
5416 ** true if it does and false if it does not.
5418 #ifndef SQLITE_OMIT_REINDEX
5419 static int collationMatch(const char *zColl, Index *pIndex){
5420 int i;
5421 assert( zColl!=0 );
5422 for(i=0; i<pIndex->nColumn; i++){
5423 const char *z = pIndex->azColl[i];
5424 assert( z!=0 || pIndex->aiColumn[i]<0 );
5425 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
5426 return 1;
5429 return 0;
5431 #endif
5434 ** Recompute all indices of pTab that use the collating sequence pColl.
5435 ** If pColl==0 then recompute all indices of pTab.
5437 #ifndef SQLITE_OMIT_REINDEX
5438 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
5439 if( !IsVirtual(pTab) ){
5440 Index *pIndex; /* An index associated with pTab */
5442 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
5443 if( zColl==0 || collationMatch(zColl, pIndex) ){
5444 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5445 sqlite3BeginWriteOperation(pParse, 0, iDb);
5446 sqlite3RefillIndex(pParse, pIndex, -1);
5451 #endif
5454 ** Recompute all indices of all tables in all databases where the
5455 ** indices use the collating sequence pColl. If pColl==0 then recompute
5456 ** all indices everywhere.
5458 #ifndef SQLITE_OMIT_REINDEX
5459 static void reindexDatabases(Parse *pParse, char const *zColl){
5460 Db *pDb; /* A single database */
5461 int iDb; /* The database index number */
5462 sqlite3 *db = pParse->db; /* The database connection */
5463 HashElem *k; /* For looping over tables in pDb */
5464 Table *pTab; /* A table in the database */
5466 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
5467 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
5468 assert( pDb!=0 );
5469 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
5470 pTab = (Table*)sqliteHashData(k);
5471 reindexTable(pParse, pTab, zColl);
5475 #endif
5478 ** Generate code for the REINDEX command.
5480 ** REINDEX -- 1
5481 ** REINDEX <collation> -- 2
5482 ** REINDEX ?<database>.?<tablename> -- 3
5483 ** REINDEX ?<database>.?<indexname> -- 4
5485 ** Form 1 causes all indices in all attached databases to be rebuilt.
5486 ** Form 2 rebuilds all indices in all databases that use the named
5487 ** collating function. Forms 3 and 4 rebuild the named index or all
5488 ** indices associated with the named table.
5490 #ifndef SQLITE_OMIT_REINDEX
5491 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
5492 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
5493 char *z; /* Name of a table or index */
5494 const char *zDb; /* Name of the database */
5495 Table *pTab; /* A table in the database */
5496 Index *pIndex; /* An index associated with pTab */
5497 int iDb; /* The database index number */
5498 sqlite3 *db = pParse->db; /* The database connection */
5499 Token *pObjName; /* Name of the table or index to be reindexed */
5501 /* Read the database schema. If an error occurs, leave an error message
5502 ** and code in pParse and return NULL. */
5503 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
5504 return;
5507 if( pName1==0 ){
5508 reindexDatabases(pParse, 0);
5509 return;
5510 }else if( NEVER(pName2==0) || pName2->z==0 ){
5511 char *zColl;
5512 assert( pName1->z );
5513 zColl = sqlite3NameFromToken(pParse->db, pName1);
5514 if( !zColl ) return;
5515 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
5516 if( pColl ){
5517 reindexDatabases(pParse, zColl);
5518 sqlite3DbFree(db, zColl);
5519 return;
5521 sqlite3DbFree(db, zColl);
5523 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
5524 if( iDb<0 ) return;
5525 z = sqlite3NameFromToken(db, pObjName);
5526 if( z==0 ) return;
5527 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
5528 pTab = sqlite3FindTable(db, z, zDb);
5529 if( pTab ){
5530 reindexTable(pParse, pTab, 0);
5531 sqlite3DbFree(db, z);
5532 return;
5534 pIndex = sqlite3FindIndex(db, z, zDb);
5535 sqlite3DbFree(db, z);
5536 if( pIndex ){
5537 iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema);
5538 sqlite3BeginWriteOperation(pParse, 0, iDb);
5539 sqlite3RefillIndex(pParse, pIndex, -1);
5540 return;
5542 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
5544 #endif
5547 ** Return a KeyInfo structure that is appropriate for the given Index.
5549 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5550 ** when it has finished using it.
5552 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
5553 int i;
5554 int nCol = pIdx->nColumn;
5555 int nKey = pIdx->nKeyCol;
5556 KeyInfo *pKey;
5557 if( pParse->nErr ) return 0;
5558 if( pIdx->uniqNotNull ){
5559 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
5560 }else{
5561 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
5563 if( pKey ){
5564 assert( sqlite3KeyInfoIsWriteable(pKey) );
5565 for(i=0; i<nCol; i++){
5566 const char *zColl = pIdx->azColl[i];
5567 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
5568 sqlite3LocateCollSeq(pParse, zColl);
5569 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
5570 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
5572 if( pParse->nErr ){
5573 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
5574 if( pIdx->bNoQuery==0 ){
5575 /* Deactivate the index because it contains an unknown collating
5576 ** sequence. The only way to reactive the index is to reload the
5577 ** schema. Adding the missing collating sequence later does not
5578 ** reactive the index. The application had the chance to register
5579 ** the missing index using the collation-needed callback. For
5580 ** simplicity, SQLite will not give the application a second chance.
5582 pIdx->bNoQuery = 1;
5583 pParse->rc = SQLITE_ERROR_RETRY;
5585 sqlite3KeyInfoUnref(pKey);
5586 pKey = 0;
5589 return pKey;
5592 #ifndef SQLITE_OMIT_CTE
5594 ** Create a new CTE object
5596 Cte *sqlite3CteNew(
5597 Parse *pParse, /* Parsing context */
5598 Token *pName, /* Name of the common-table */
5599 ExprList *pArglist, /* Optional column name list for the table */
5600 Select *pQuery, /* Query used to initialize the table */
5601 u8 eM10d /* The MATERIALIZED flag */
5603 Cte *pNew;
5604 sqlite3 *db = pParse->db;
5606 pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
5607 assert( pNew!=0 || db->mallocFailed );
5609 if( db->mallocFailed ){
5610 sqlite3ExprListDelete(db, pArglist);
5611 sqlite3SelectDelete(db, pQuery);
5612 }else{
5613 pNew->pSelect = pQuery;
5614 pNew->pCols = pArglist;
5615 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
5616 pNew->eM10d = eM10d;
5618 return pNew;
5622 ** Clear information from a Cte object, but do not deallocate storage
5623 ** for the object itself.
5625 static void cteClear(sqlite3 *db, Cte *pCte){
5626 assert( pCte!=0 );
5627 sqlite3ExprListDelete(db, pCte->pCols);
5628 sqlite3SelectDelete(db, pCte->pSelect);
5629 sqlite3DbFree(db, pCte->zName);
5633 ** Free the contents of the CTE object passed as the second argument.
5635 void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
5636 assert( pCte!=0 );
5637 cteClear(db, pCte);
5638 sqlite3DbFree(db, pCte);
5642 ** This routine is invoked once per CTE by the parser while parsing a
5643 ** WITH clause. The CTE described by the third argument is added to
5644 ** the WITH clause of the second argument. If the second argument is
5645 ** NULL, then a new WITH argument is created.
5647 With *sqlite3WithAdd(
5648 Parse *pParse, /* Parsing context */
5649 With *pWith, /* Existing WITH clause, or NULL */
5650 Cte *pCte /* CTE to add to the WITH clause */
5652 sqlite3 *db = pParse->db;
5653 With *pNew;
5654 char *zName;
5656 if( pCte==0 ){
5657 return pWith;
5660 /* Check that the CTE name is unique within this WITH clause. If
5661 ** not, store an error in the Parse structure. */
5662 zName = pCte->zName;
5663 if( zName && pWith ){
5664 int i;
5665 for(i=0; i<pWith->nCte; i++){
5666 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5667 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
5672 if( pWith ){
5673 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
5674 pNew = sqlite3DbRealloc(db, pWith, nByte);
5675 }else{
5676 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
5678 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
5680 if( db->mallocFailed ){
5681 sqlite3CteDelete(db, pCte);
5682 pNew = pWith;
5683 }else{
5684 pNew->a[pNew->nCte++] = *pCte;
5685 sqlite3DbFree(db, pCte);
5688 return pNew;
5692 ** Free the contents of the With object passed as the second argument.
5694 void sqlite3WithDelete(sqlite3 *db, With *pWith){
5695 if( pWith ){
5696 int i;
5697 for(i=0; i<pWith->nCte; i++){
5698 cteClear(db, &pWith->a[i]);
5700 sqlite3DbFree(db, pWith);
5703 void sqlite3WithDeleteGeneric(sqlite3 *db, void *pWith){
5704 sqlite3WithDelete(db, (With*)pWith);
5706 #endif /* !defined(SQLITE_OMIT_CTE) */