Merge sqlite-release(3.42.0) into prerelease-integration
[sqlcipher.git] / src / build.c
blob9be444c3c36d457ad58b489b043c672074121db2
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 /* Once all the cookies have been verified and transactions opened,
238 ** obtain the required table-locks. This is a no-op unless the
239 ** shared-cache feature is enabled.
241 codeTableLocks(pParse);
243 /* Initialize any AUTOINCREMENT data structures required.
245 sqlite3AutoincrementBegin(pParse);
247 /* Code constant expressions that where factored out of inner loops.
249 ** The pConstExpr list might also contain expressions that we simply
250 ** want to keep around until the Parse object is deleted. Such
251 ** expressions have iConstExprReg==0. Do not generate code for
252 ** those expressions, of course.
254 if( pParse->pConstExpr ){
255 ExprList *pEL = pParse->pConstExpr;
256 pParse->okConstFactor = 0;
257 for(i=0; i<pEL->nExpr; i++){
258 int iReg = pEL->a[i].u.iConstExprReg;
259 sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);
263 if( pParse->bReturning ){
264 Returning *pRet = pParse->u1.pReturning;
265 if( pRet->nRetCol ){
266 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
270 /* Finally, jump back to the beginning of the executable code. */
271 sqlite3VdbeGoto(v, 1);
274 /* Get the VDBE program ready for execution
276 assert( v!=0 || pParse->nErr );
277 assert( db->mallocFailed==0 || pParse->nErr );
278 if( pParse->nErr==0 ){
279 /* A minimum of one cursor is required if autoincrement is used
280 * See ticket [a696379c1f08866] */
281 assert( pParse->pAinc==0 || pParse->nTab>0 );
282 sqlite3VdbeMakeReady(v, pParse);
283 pParse->rc = SQLITE_DONE;
284 }else{
285 pParse->rc = SQLITE_ERROR;
290 ** Run the parser and code generator recursively in order to generate
291 ** code for the SQL statement given onto the end of the pParse context
292 ** currently under construction. Notes:
294 ** * The final OP_Halt is not appended and other initialization
295 ** and finalization steps are omitted because those are handling by the
296 ** outermost parser.
298 ** * Built-in SQL functions always take precedence over application-defined
299 ** SQL functions. In other words, it is not possible to override a
300 ** built-in function.
302 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
303 va_list ap;
304 char *zSql;
305 sqlite3 *db = pParse->db;
306 u32 savedDbFlags = db->mDbFlags;
307 char saveBuf[PARSE_TAIL_SZ];
309 if( pParse->nErr ) return;
310 if( pParse->eParseMode ) return;
311 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
312 va_start(ap, zFormat);
313 zSql = sqlite3VMPrintf(db, zFormat, ap);
314 va_end(ap);
315 if( zSql==0 ){
316 /* This can result either from an OOM or because the formatted string
317 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
318 ** an error */
319 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
320 pParse->nErr++;
321 return;
323 pParse->nested++;
324 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
325 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
326 db->mDbFlags |= DBFLAG_PreferBuiltin;
327 sqlite3RunParser(pParse, zSql);
328 db->mDbFlags = savedDbFlags;
329 sqlite3DbFree(db, zSql);
330 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
331 pParse->nested--;
334 #if SQLITE_USER_AUTHENTICATION
336 ** Return TRUE if zTable is the name of the system table that stores the
337 ** list of users and their access credentials.
339 int sqlite3UserAuthTable(const char *zTable){
340 return sqlite3_stricmp(zTable, "sqlite_user")==0;
342 #endif
345 ** Locate the in-memory structure that describes a particular database
346 ** table given the name of that table and (optionally) the name of the
347 ** database containing the table. Return NULL if not found.
349 ** If zDatabase is 0, all databases are searched for the table and the
350 ** first matching table is returned. (No checking for duplicate table
351 ** names is done.) The search order is TEMP first, then MAIN, then any
352 ** auxiliary databases added using the ATTACH command.
354 ** See also sqlite3LocateTable().
356 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
357 Table *p = 0;
358 int i;
360 /* All mutexes are required for schema access. Make sure we hold them. */
361 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
362 #if SQLITE_USER_AUTHENTICATION
363 /* Only the admin user is allowed to know that the sqlite_user table
364 ** exists */
365 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
366 return 0;
368 #endif
369 if( zDatabase ){
370 for(i=0; i<db->nDb; i++){
371 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
373 if( i>=db->nDb ){
374 /* No match against the official names. But always match "main"
375 ** to schema 0 as a legacy fallback. */
376 if( sqlite3StrICmp(zDatabase,"main")==0 ){
377 i = 0;
378 }else{
379 return 0;
382 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
383 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
384 if( i==1 ){
385 if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
386 || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
387 || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
389 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
390 LEGACY_TEMP_SCHEMA_TABLE);
392 }else{
393 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
394 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
395 LEGACY_SCHEMA_TABLE);
399 }else{
400 /* Match against TEMP first */
401 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
402 if( p ) return p;
403 /* The main database is second */
404 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
405 if( p ) return p;
406 /* Attached databases are in order of attachment */
407 for(i=2; i<db->nDb; i++){
408 assert( sqlite3SchemaMutexHeld(db, i, 0) );
409 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
410 if( p ) break;
412 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
413 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
414 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
415 }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
416 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
417 LEGACY_TEMP_SCHEMA_TABLE);
421 return p;
425 ** Locate the in-memory structure that describes a particular database
426 ** table given the name of that table and (optionally) the name of the
427 ** database containing the table. Return NULL if not found. Also leave an
428 ** error message in pParse->zErrMsg.
430 ** The difference between this routine and sqlite3FindTable() is that this
431 ** routine leaves an error message in pParse->zErrMsg where
432 ** sqlite3FindTable() does not.
434 Table *sqlite3LocateTable(
435 Parse *pParse, /* context in which to report errors */
436 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
437 const char *zName, /* Name of the table we are looking for */
438 const char *zDbase /* Name of the database. Might be NULL */
440 Table *p;
441 sqlite3 *db = pParse->db;
443 /* Read the database schema. If an error occurs, leave an error message
444 ** and code in pParse and return NULL. */
445 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
446 && SQLITE_OK!=sqlite3ReadSchema(pParse)
448 return 0;
451 p = sqlite3FindTable(db, zName, zDbase);
452 if( p==0 ){
453 #ifndef SQLITE_OMIT_VIRTUALTABLE
454 /* If zName is the not the name of a table in the schema created using
455 ** CREATE, then check to see if it is the name of an virtual table that
456 ** can be an eponymous virtual table. */
457 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
458 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
459 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
460 pMod = sqlite3PragmaVtabRegister(db, zName);
462 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
463 testcase( pMod->pEpoTab==0 );
464 return pMod->pEpoTab;
467 #endif
468 if( flags & LOCATE_NOERR ) return 0;
469 pParse->checkSchema = 1;
470 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
471 p = 0;
474 if( p==0 ){
475 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
476 if( zDbase ){
477 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
478 }else{
479 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
481 }else{
482 assert( HasRowid(p) || p->iPKey<0 );
485 return p;
489 ** Locate the table identified by *p.
491 ** This is a wrapper around sqlite3LocateTable(). The difference between
492 ** sqlite3LocateTable() and this function is that this function restricts
493 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
494 ** non-NULL if it is part of a view or trigger program definition. See
495 ** sqlite3FixSrcList() for details.
497 Table *sqlite3LocateTableItem(
498 Parse *pParse,
499 u32 flags,
500 SrcItem *p
502 const char *zDb;
503 assert( p->pSchema==0 || p->zDatabase==0 );
504 if( p->pSchema ){
505 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
506 zDb = pParse->db->aDb[iDb].zDbSName;
507 }else{
508 zDb = p->zDatabase;
510 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
514 ** Return the preferred table name for system tables. Translate legacy
515 ** names into the new preferred names, as appropriate.
517 const char *sqlite3PreferredTableName(const char *zName){
518 if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
519 if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
520 return PREFERRED_SCHEMA_TABLE;
522 if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
523 return PREFERRED_TEMP_SCHEMA_TABLE;
526 return zName;
530 ** Locate the in-memory structure that describes
531 ** a particular index given the name of that index
532 ** and the name of the database that contains the index.
533 ** Return NULL if not found.
535 ** If zDatabase is 0, all databases are searched for the
536 ** table and the first matching index is returned. (No checking
537 ** for duplicate index names is done.) The search order is
538 ** TEMP first, then MAIN, then any auxiliary databases added
539 ** using the ATTACH command.
541 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
542 Index *p = 0;
543 int i;
544 /* All mutexes are required for schema access. Make sure we hold them. */
545 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
546 for(i=OMIT_TEMPDB; i<db->nDb; i++){
547 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
548 Schema *pSchema = db->aDb[j].pSchema;
549 assert( pSchema );
550 if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
551 assert( sqlite3SchemaMutexHeld(db, j, 0) );
552 p = sqlite3HashFind(&pSchema->idxHash, zName);
553 if( p ) break;
555 return p;
559 ** Reclaim the memory used by an index
561 void sqlite3FreeIndex(sqlite3 *db, Index *p){
562 #ifndef SQLITE_OMIT_ANALYZE
563 sqlite3DeleteIndexSamples(db, p);
564 #endif
565 sqlite3ExprDelete(db, p->pPartIdxWhere);
566 sqlite3ExprListDelete(db, p->aColExpr);
567 sqlite3DbFree(db, p->zColAff);
568 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
569 #ifdef SQLITE_ENABLE_STAT4
570 sqlite3_free(p->aiRowEst);
571 #endif
572 sqlite3DbFree(db, p);
576 ** For the index called zIdxName which is found in the database iDb,
577 ** unlike that index from its Table then remove the index from
578 ** the index hash table and free all memory structures associated
579 ** with the index.
581 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
582 Index *pIndex;
583 Hash *pHash;
585 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
586 pHash = &db->aDb[iDb].pSchema->idxHash;
587 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
588 if( ALWAYS(pIndex) ){
589 if( pIndex->pTable->pIndex==pIndex ){
590 pIndex->pTable->pIndex = pIndex->pNext;
591 }else{
592 Index *p;
593 /* Justification of ALWAYS(); The index must be on the list of
594 ** indices. */
595 p = pIndex->pTable->pIndex;
596 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
597 if( ALWAYS(p && p->pNext==pIndex) ){
598 p->pNext = pIndex->pNext;
601 sqlite3FreeIndex(db, pIndex);
603 db->mDbFlags |= DBFLAG_SchemaChange;
607 ** Look through the list of open database files in db->aDb[] and if
608 ** any have been closed, remove them from the list. Reallocate the
609 ** db->aDb[] structure to a smaller size, if possible.
611 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
612 ** are never candidates for being collapsed.
614 void sqlite3CollapseDatabaseArray(sqlite3 *db){
615 int i, j;
616 for(i=j=2; i<db->nDb; i++){
617 struct Db *pDb = &db->aDb[i];
618 if( pDb->pBt==0 ){
619 sqlite3DbFree(db, pDb->zDbSName);
620 pDb->zDbSName = 0;
621 continue;
623 if( j<i ){
624 db->aDb[j] = db->aDb[i];
626 j++;
628 db->nDb = j;
629 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
630 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
631 sqlite3DbFree(db, db->aDb);
632 db->aDb = db->aDbStatic;
637 ** Reset the schema for the database at index iDb. Also reset the
638 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
639 ** Deferred resets may be run by calling with iDb<0.
641 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
642 int i;
643 assert( iDb<db->nDb );
645 if( iDb>=0 ){
646 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
647 DbSetProperty(db, iDb, DB_ResetWanted);
648 DbSetProperty(db, 1, DB_ResetWanted);
649 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
652 if( db->nSchemaLock==0 ){
653 for(i=0; i<db->nDb; i++){
654 if( DbHasProperty(db, i, DB_ResetWanted) ){
655 sqlite3SchemaClear(db->aDb[i].pSchema);
662 ** Erase all schema information from all attached databases (including
663 ** "main" and "temp") for a single database connection.
665 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
666 int i;
667 sqlite3BtreeEnterAll(db);
668 for(i=0; i<db->nDb; i++){
669 Db *pDb = &db->aDb[i];
670 if( pDb->pSchema ){
671 if( db->nSchemaLock==0 ){
672 sqlite3SchemaClear(pDb->pSchema);
673 }else{
674 DbSetProperty(db, i, DB_ResetWanted);
678 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
679 sqlite3VtabUnlockList(db);
680 sqlite3BtreeLeaveAll(db);
681 if( db->nSchemaLock==0 ){
682 sqlite3CollapseDatabaseArray(db);
687 ** This routine is called when a commit occurs.
689 void sqlite3CommitInternalChanges(sqlite3 *db){
690 db->mDbFlags &= ~DBFLAG_SchemaChange;
694 ** Set the expression associated with a column. This is usually
695 ** the DEFAULT value, but might also be the expression that computes
696 ** the value for a generated column.
698 void sqlite3ColumnSetExpr(
699 Parse *pParse, /* Parsing context */
700 Table *pTab, /* The table containing the column */
701 Column *pCol, /* The column to receive the new DEFAULT expression */
702 Expr *pExpr /* The new default expression */
704 ExprList *pList;
705 assert( IsOrdinaryTable(pTab) );
706 pList = pTab->u.tab.pDfltList;
707 if( pCol->iDflt==0
708 || NEVER(pList==0)
709 || NEVER(pList->nExpr<pCol->iDflt)
711 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
712 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
713 }else{
714 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
715 pList->a[pCol->iDflt-1].pExpr = pExpr;
720 ** Return the expression associated with a column. The expression might be
721 ** the DEFAULT clause or the AS clause of a generated column.
722 ** Return NULL if the column has no associated expression.
724 Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
725 if( pCol->iDflt==0 ) return 0;
726 if( NEVER(!IsOrdinaryTable(pTab)) ) return 0;
727 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
728 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
729 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
733 ** Set the collating sequence name for a column.
735 void sqlite3ColumnSetColl(
736 sqlite3 *db,
737 Column *pCol,
738 const char *zColl
740 i64 nColl;
741 i64 n;
742 char *zNew;
743 assert( zColl!=0 );
744 n = sqlite3Strlen30(pCol->zCnName) + 1;
745 if( pCol->colFlags & COLFLAG_HASTYPE ){
746 n += sqlite3Strlen30(pCol->zCnName+n) + 1;
748 nColl = sqlite3Strlen30(zColl) + 1;
749 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
750 if( zNew ){
751 pCol->zCnName = zNew;
752 memcpy(pCol->zCnName + n, zColl, nColl);
753 pCol->colFlags |= COLFLAG_HASCOLL;
758 ** Return the collating squence name for a column
760 const char *sqlite3ColumnColl(Column *pCol){
761 const char *z;
762 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
763 z = pCol->zCnName;
764 while( *z ){ z++; }
765 if( pCol->colFlags & COLFLAG_HASTYPE ){
766 do{ z++; }while( *z );
768 return z+1;
772 ** Delete memory allocated for the column names of a table or view (the
773 ** Table.aCol[] array).
775 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
776 int i;
777 Column *pCol;
778 assert( pTable!=0 );
779 assert( db!=0 );
780 if( (pCol = pTable->aCol)!=0 ){
781 for(i=0; i<pTable->nCol; i++, pCol++){
782 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
783 sqlite3DbFree(db, pCol->zCnName);
785 sqlite3DbNNFreeNN(db, pTable->aCol);
786 if( IsOrdinaryTable(pTable) ){
787 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
789 if( db->pnBytesFreed==0 ){
790 pTable->aCol = 0;
791 pTable->nCol = 0;
792 if( IsOrdinaryTable(pTable) ){
793 pTable->u.tab.pDfltList = 0;
800 ** Remove the memory data structures associated with the given
801 ** Table. No changes are made to disk by this routine.
803 ** This routine just deletes the data structure. It does not unlink
804 ** the table data structure from the hash table. But it does destroy
805 ** memory structures of the indices and foreign keys associated with
806 ** the table.
808 ** The db parameter is optional. It is needed if the Table object
809 ** contains lookaside memory. (Table objects in the schema do not use
810 ** lookaside memory, but some ephemeral Table objects do.) Or the
811 ** db parameter can be used with db->pnBytesFreed to measure the memory
812 ** used by the Table object.
814 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
815 Index *pIndex, *pNext;
817 #ifdef SQLITE_DEBUG
818 /* Record the number of outstanding lookaside allocations in schema Tables
819 ** prior to doing any free() operations. Since schema Tables do not use
820 ** lookaside, this number should not change.
822 ** If malloc has already failed, it may be that it failed while allocating
823 ** a Table object that was going to be marked ephemeral. So do not check
824 ** that no lookaside memory is used in this case either. */
825 int nLookaside = 0;
826 assert( db!=0 );
827 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
828 nLookaside = sqlite3LookasideUsed(db, 0);
830 #endif
832 /* Delete all indices associated with this table. */
833 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
834 pNext = pIndex->pNext;
835 assert( pIndex->pSchema==pTable->pSchema
836 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
837 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
838 char *zName = pIndex->zName;
839 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
840 &pIndex->pSchema->idxHash, zName, 0
842 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
843 assert( pOld==pIndex || pOld==0 );
845 sqlite3FreeIndex(db, pIndex);
848 if( IsOrdinaryTable(pTable) ){
849 sqlite3FkDelete(db, pTable);
851 #ifndef SQLITE_OMIT_VIRTUALTABLE
852 else if( IsVirtual(pTable) ){
853 sqlite3VtabClear(db, pTable);
855 #endif
856 else{
857 assert( IsView(pTable) );
858 sqlite3SelectDelete(db, pTable->u.view.pSelect);
861 /* Delete the Table structure itself.
863 sqlite3DeleteColumnNames(db, pTable);
864 sqlite3DbFree(db, pTable->zName);
865 sqlite3DbFree(db, pTable->zColAff);
866 sqlite3ExprListDelete(db, pTable->pCheck);
867 sqlite3DbFree(db, pTable);
869 /* Verify that no lookaside memory was used by schema tables */
870 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
872 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
873 /* Do not delete the table until the reference count reaches zero. */
874 assert( db!=0 );
875 if( !pTable ) return;
876 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
877 deleteTable(db, 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 ** Name of the special TEMP trigger used to implement RETURNING. The
1415 ** name begins with "sqlite_" so that it is guaranteed not to collide
1416 ** with any application-generated triggers.
1418 #define RETURNING_TRIGGER_NAME "sqlite_returning"
1421 ** Clean up the data structures associated with the RETURNING clause.
1423 static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){
1424 Hash *pHash;
1425 pHash = &(db->aDb[1].pSchema->trigHash);
1426 sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, 0);
1427 sqlite3ExprListDelete(db, pRet->pReturnEL);
1428 sqlite3DbFree(db, pRet);
1432 ** Add the RETURNING clause to the parse currently underway.
1434 ** This routine creates a special TEMP trigger that will fire for each row
1435 ** of the DML statement. That TEMP trigger contains a single SELECT
1436 ** statement with a result set that is the argument of the RETURNING clause.
1437 ** The trigger has the Trigger.bReturning flag and an opcode of
1438 ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
1439 ** knows to handle it specially. The TEMP trigger is automatically
1440 ** removed at the end of the parse.
1442 ** When this routine is called, we do not yet know if the RETURNING clause
1443 ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
1444 ** RETURNING trigger instead. It will then be converted into the appropriate
1445 ** type on the first call to sqlite3TriggersExist().
1447 void sqlite3AddReturning(Parse *pParse, ExprList *pList){
1448 Returning *pRet;
1449 Hash *pHash;
1450 sqlite3 *db = pParse->db;
1451 if( pParse->pNewTrigger ){
1452 sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
1453 }else{
1454 assert( pParse->bReturning==0 || pParse->ifNotExists );
1456 pParse->bReturning = 1;
1457 pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
1458 if( pRet==0 ){
1459 sqlite3ExprListDelete(db, pList);
1460 return;
1462 pParse->u1.pReturning = pRet;
1463 pRet->pParse = pParse;
1464 pRet->pReturnEL = pList;
1465 sqlite3ParserAddCleanup(pParse,
1466 (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet);
1467 testcase( pParse->earlyCleanup );
1468 if( db->mallocFailed ) return;
1469 pRet->retTrig.zName = RETURNING_TRIGGER_NAME;
1470 pRet->retTrig.op = TK_RETURNING;
1471 pRet->retTrig.tr_tm = TRIGGER_AFTER;
1472 pRet->retTrig.bReturning = 1;
1473 pRet->retTrig.pSchema = db->aDb[1].pSchema;
1474 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
1475 pRet->retTrig.step_list = &pRet->retTStep;
1476 pRet->retTStep.op = TK_RETURNING;
1477 pRet->retTStep.pTrig = &pRet->retTrig;
1478 pRet->retTStep.pExprList = pList;
1479 pHash = &(db->aDb[1].pSchema->trigHash);
1480 assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0
1481 || pParse->nErr || pParse->ifNotExists );
1482 if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
1483 ==&pRet->retTrig ){
1484 sqlite3OomFault(db);
1489 ** Add a new column to the table currently being constructed.
1491 ** The parser calls this routine once for each column declaration
1492 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1493 ** first to get things going. Then this routine is called for each
1494 ** column.
1496 void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
1497 Table *p;
1498 int i;
1499 char *z;
1500 char *zType;
1501 Column *pCol;
1502 sqlite3 *db = pParse->db;
1503 u8 hName;
1504 Column *aNew;
1505 u8 eType = COLTYPE_CUSTOM;
1506 u8 szEst = 1;
1507 char affinity = SQLITE_AFF_BLOB;
1509 if( (p = pParse->pNewTable)==0 ) return;
1510 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1511 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1512 return;
1514 if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
1516 /* Because keywords GENERATE ALWAYS can be converted into indentifiers
1517 ** by the parser, we can sometimes end up with a typename that ends
1518 ** with "generated always". Check for this case and omit the surplus
1519 ** text. */
1520 if( sType.n>=16
1521 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
1523 sType.n -= 6;
1524 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1525 if( sType.n>=9
1526 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
1528 sType.n -= 9;
1529 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1533 /* Check for standard typenames. For standard typenames we will
1534 ** set the Column.eType field rather than storing the typename after
1535 ** the column name, in order to save space. */
1536 if( sType.n>=3 ){
1537 sqlite3DequoteToken(&sType);
1538 for(i=0; i<SQLITE_N_STDTYPE; i++){
1539 if( sType.n==sqlite3StdTypeLen[i]
1540 && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
1542 sType.n = 0;
1543 eType = i+1;
1544 affinity = sqlite3StdTypeAffinity[i];
1545 if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
1546 break;
1551 z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
1552 if( z==0 ) return;
1553 if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
1554 memcpy(z, sName.z, sName.n);
1555 z[sName.n] = 0;
1556 sqlite3Dequote(z);
1557 hName = sqlite3StrIHash(z);
1558 for(i=0; i<p->nCol; i++){
1559 if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
1560 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1561 sqlite3DbFree(db, z);
1562 return;
1565 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
1566 if( aNew==0 ){
1567 sqlite3DbFree(db, z);
1568 return;
1570 p->aCol = aNew;
1571 pCol = &p->aCol[p->nCol];
1572 memset(pCol, 0, sizeof(p->aCol[0]));
1573 pCol->zCnName = z;
1574 pCol->hName = hName;
1575 sqlite3ColumnPropertiesFromName(p, pCol);
1577 if( sType.n==0 ){
1578 /* If there is no type specified, columns have the default affinity
1579 ** 'BLOB' with a default size of 4 bytes. */
1580 pCol->affinity = affinity;
1581 pCol->eCType = eType;
1582 pCol->szEst = szEst;
1583 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1584 if( affinity==SQLITE_AFF_BLOB ){
1585 if( 4>=sqlite3GlobalConfig.szSorterRef ){
1586 pCol->colFlags |= COLFLAG_SORTERREF;
1589 #endif
1590 }else{
1591 zType = z + sqlite3Strlen30(z) + 1;
1592 memcpy(zType, sType.z, sType.n);
1593 zType[sType.n] = 0;
1594 sqlite3Dequote(zType);
1595 pCol->affinity = sqlite3AffinityType(zType, pCol);
1596 pCol->colFlags |= COLFLAG_HASTYPE;
1598 p->nCol++;
1599 p->nNVCol++;
1600 pParse->constraintName.n = 0;
1604 ** This routine is called by the parser while in the middle of
1605 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1606 ** been seen on a column. This routine sets the notNull flag on
1607 ** the column currently under construction.
1609 void sqlite3AddNotNull(Parse *pParse, int onError){
1610 Table *p;
1611 Column *pCol;
1612 p = pParse->pNewTable;
1613 if( p==0 || NEVER(p->nCol<1) ) return;
1614 pCol = &p->aCol[p->nCol-1];
1615 pCol->notNull = (u8)onError;
1616 p->tabFlags |= TF_HasNotNull;
1618 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1619 ** on this column. */
1620 if( pCol->colFlags & COLFLAG_UNIQUE ){
1621 Index *pIdx;
1622 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1623 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1624 if( pIdx->aiColumn[0]==p->nCol-1 ){
1625 pIdx->uniqNotNull = 1;
1632 ** Scan the column type name zType (length nType) and return the
1633 ** associated affinity type.
1635 ** This routine does a case-independent search of zType for the
1636 ** substrings in the following table. If one of the substrings is
1637 ** found, the corresponding affinity is returned. If zType contains
1638 ** more than one of the substrings, entries toward the top of
1639 ** the table take priority. For example, if zType is 'BLOBINT',
1640 ** SQLITE_AFF_INTEGER is returned.
1642 ** Substring | Affinity
1643 ** --------------------------------
1644 ** 'INT' | SQLITE_AFF_INTEGER
1645 ** 'CHAR' | SQLITE_AFF_TEXT
1646 ** 'CLOB' | SQLITE_AFF_TEXT
1647 ** 'TEXT' | SQLITE_AFF_TEXT
1648 ** 'BLOB' | SQLITE_AFF_BLOB
1649 ** 'REAL' | SQLITE_AFF_REAL
1650 ** 'FLOA' | SQLITE_AFF_REAL
1651 ** 'DOUB' | SQLITE_AFF_REAL
1653 ** If none of the substrings in the above table are found,
1654 ** SQLITE_AFF_NUMERIC is returned.
1656 char sqlite3AffinityType(const char *zIn, Column *pCol){
1657 u32 h = 0;
1658 char aff = SQLITE_AFF_NUMERIC;
1659 const char *zChar = 0;
1661 assert( zIn!=0 );
1662 while( zIn[0] ){
1663 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1664 zIn++;
1665 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1666 aff = SQLITE_AFF_TEXT;
1667 zChar = zIn;
1668 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1669 aff = SQLITE_AFF_TEXT;
1670 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1671 aff = SQLITE_AFF_TEXT;
1672 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1673 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1674 aff = SQLITE_AFF_BLOB;
1675 if( zIn[0]=='(' ) zChar = zIn;
1676 #ifndef SQLITE_OMIT_FLOATING_POINT
1677 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1678 && aff==SQLITE_AFF_NUMERIC ){
1679 aff = SQLITE_AFF_REAL;
1680 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1681 && aff==SQLITE_AFF_NUMERIC ){
1682 aff = SQLITE_AFF_REAL;
1683 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1684 && aff==SQLITE_AFF_NUMERIC ){
1685 aff = SQLITE_AFF_REAL;
1686 #endif
1687 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1688 aff = SQLITE_AFF_INTEGER;
1689 break;
1693 /* If pCol is not NULL, store an estimate of the field size. The
1694 ** estimate is scaled so that the size of an integer is 1. */
1695 if( pCol ){
1696 int v = 0; /* default size is approx 4 bytes */
1697 if( aff<SQLITE_AFF_NUMERIC ){
1698 if( zChar ){
1699 while( zChar[0] ){
1700 if( sqlite3Isdigit(zChar[0]) ){
1701 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1702 sqlite3GetInt32(zChar, &v);
1703 break;
1705 zChar++;
1707 }else{
1708 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1711 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1712 if( v>=sqlite3GlobalConfig.szSorterRef ){
1713 pCol->colFlags |= COLFLAG_SORTERREF;
1715 #endif
1716 v = v/4 + 1;
1717 if( v>255 ) v = 255;
1718 pCol->szEst = v;
1720 return aff;
1724 ** The expression is the default value for the most recently added column
1725 ** of the table currently under construction.
1727 ** Default value expressions must be constant. Raise an exception if this
1728 ** is not the case.
1730 ** This routine is called by the parser while in the middle of
1731 ** parsing a CREATE TABLE statement.
1733 void sqlite3AddDefaultValue(
1734 Parse *pParse, /* Parsing context */
1735 Expr *pExpr, /* The parsed expression of the default value */
1736 const char *zStart, /* Start of the default value text */
1737 const char *zEnd /* First character past end of defaut value text */
1739 Table *p;
1740 Column *pCol;
1741 sqlite3 *db = pParse->db;
1742 p = pParse->pNewTable;
1743 if( p!=0 ){
1744 int isInit = db->init.busy && db->init.iDb!=1;
1745 pCol = &(p->aCol[p->nCol-1]);
1746 if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
1747 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1748 pCol->zCnName);
1749 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1750 }else if( pCol->colFlags & COLFLAG_GENERATED ){
1751 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1752 testcase( pCol->colFlags & COLFLAG_STORED );
1753 sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
1754 #endif
1755 }else{
1756 /* A copy of pExpr is used instead of the original, as pExpr contains
1757 ** tokens that point to volatile memory.
1759 Expr x, *pDfltExpr;
1760 memset(&x, 0, sizeof(x));
1761 x.op = TK_SPAN;
1762 x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1763 x.pLeft = pExpr;
1764 x.flags = EP_Skip;
1765 pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1766 sqlite3DbFree(db, x.u.zToken);
1767 sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
1770 if( IN_RENAME_OBJECT ){
1771 sqlite3RenameExprUnmap(pParse, pExpr);
1773 sqlite3ExprDelete(db, pExpr);
1777 ** Backwards Compatibility Hack:
1779 ** Historical versions of SQLite accepted strings as column names in
1780 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1782 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1783 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1785 ** This is goofy. But to preserve backwards compatibility we continue to
1786 ** accept it. This routine does the necessary conversion. It converts
1787 ** the expression given in its argument from a TK_STRING into a TK_ID
1788 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1789 ** If the expression is anything other than TK_STRING, the expression is
1790 ** unchanged.
1792 static void sqlite3StringToId(Expr *p){
1793 if( p->op==TK_STRING ){
1794 p->op = TK_ID;
1795 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1796 p->pLeft->op = TK_ID;
1801 ** Tag the given column as being part of the PRIMARY KEY
1803 static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1804 pCol->colFlags |= COLFLAG_PRIMKEY;
1805 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1806 if( pCol->colFlags & COLFLAG_GENERATED ){
1807 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1808 testcase( pCol->colFlags & COLFLAG_STORED );
1809 sqlite3ErrorMsg(pParse,
1810 "generated columns cannot be part of the PRIMARY KEY");
1812 #endif
1816 ** Designate the PRIMARY KEY for the table. pList is a list of names
1817 ** of columns that form the primary key. If pList is NULL, then the
1818 ** most recently added column of the table is the primary key.
1820 ** A table can have at most one primary key. If the table already has
1821 ** a primary key (and this is the second primary key) then create an
1822 ** error.
1824 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1825 ** then we will try to use that column as the rowid. Set the Table.iPKey
1826 ** field of the table under construction to be the index of the
1827 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1828 ** no INTEGER PRIMARY KEY.
1830 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1831 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1833 void sqlite3AddPrimaryKey(
1834 Parse *pParse, /* Parsing context */
1835 ExprList *pList, /* List of field names to be indexed */
1836 int onError, /* What to do with a uniqueness conflict */
1837 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1838 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1840 Table *pTab = pParse->pNewTable;
1841 Column *pCol = 0;
1842 int iCol = -1, i;
1843 int nTerm;
1844 if( pTab==0 ) goto primary_key_exit;
1845 if( pTab->tabFlags & TF_HasPrimaryKey ){
1846 sqlite3ErrorMsg(pParse,
1847 "table \"%s\" has more than one primary key", pTab->zName);
1848 goto primary_key_exit;
1850 pTab->tabFlags |= TF_HasPrimaryKey;
1851 if( pList==0 ){
1852 iCol = pTab->nCol - 1;
1853 pCol = &pTab->aCol[iCol];
1854 makeColumnPartOfPrimaryKey(pParse, pCol);
1855 nTerm = 1;
1856 }else{
1857 nTerm = pList->nExpr;
1858 for(i=0; i<nTerm; i++){
1859 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1860 assert( pCExpr!=0 );
1861 sqlite3StringToId(pCExpr);
1862 if( pCExpr->op==TK_ID ){
1863 const char *zCName;
1864 assert( !ExprHasProperty(pCExpr, EP_IntValue) );
1865 zCName = pCExpr->u.zToken;
1866 for(iCol=0; iCol<pTab->nCol; iCol++){
1867 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
1868 pCol = &pTab->aCol[iCol];
1869 makeColumnPartOfPrimaryKey(pParse, pCol);
1870 break;
1876 if( nTerm==1
1877 && pCol
1878 && pCol->eCType==COLTYPE_INTEGER
1879 && sortOrder!=SQLITE_SO_DESC
1881 if( IN_RENAME_OBJECT && pList ){
1882 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1883 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1885 pTab->iPKey = iCol;
1886 pTab->keyConf = (u8)onError;
1887 assert( autoInc==0 || autoInc==1 );
1888 pTab->tabFlags |= autoInc*TF_Autoincrement;
1889 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
1890 (void)sqlite3HasExplicitNulls(pParse, pList);
1891 }else if( autoInc ){
1892 #ifndef SQLITE_OMIT_AUTOINCREMENT
1893 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1894 "INTEGER PRIMARY KEY");
1895 #endif
1896 }else{
1897 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1898 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1899 pList = 0;
1902 primary_key_exit:
1903 sqlite3ExprListDelete(pParse->db, pList);
1904 return;
1908 ** Add a new CHECK constraint to the table currently under construction.
1910 void sqlite3AddCheckConstraint(
1911 Parse *pParse, /* Parsing context */
1912 Expr *pCheckExpr, /* The check expression */
1913 const char *zStart, /* Opening "(" */
1914 const char *zEnd /* Closing ")" */
1916 #ifndef SQLITE_OMIT_CHECK
1917 Table *pTab = pParse->pNewTable;
1918 sqlite3 *db = pParse->db;
1919 if( pTab && !IN_DECLARE_VTAB
1920 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1922 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1923 if( pParse->constraintName.n ){
1924 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1925 }else{
1926 Token t;
1927 for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
1928 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
1929 t.z = zStart;
1930 t.n = (int)(zEnd - t.z);
1931 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
1933 }else
1934 #endif
1936 sqlite3ExprDelete(pParse->db, pCheckExpr);
1941 ** Set the collation function of the most recently parsed table column
1942 ** to the CollSeq given.
1944 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1945 Table *p;
1946 int i;
1947 char *zColl; /* Dequoted name of collation sequence */
1948 sqlite3 *db;
1950 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
1951 i = p->nCol-1;
1952 db = pParse->db;
1953 zColl = sqlite3NameFromToken(db, pToken);
1954 if( !zColl ) return;
1956 if( sqlite3LocateCollSeq(pParse, zColl) ){
1957 Index *pIdx;
1958 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
1960 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1961 ** then an index may have been created on this column before the
1962 ** collation type was added. Correct this if it is the case.
1964 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1965 assert( pIdx->nKeyCol==1 );
1966 if( pIdx->aiColumn[0]==i ){
1967 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
1971 sqlite3DbFree(db, zColl);
1974 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1975 ** column.
1977 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
1978 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1979 u8 eType = COLFLAG_VIRTUAL;
1980 Table *pTab = pParse->pNewTable;
1981 Column *pCol;
1982 if( pTab==0 ){
1983 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1984 goto generated_done;
1986 pCol = &(pTab->aCol[pTab->nCol-1]);
1987 if( IN_DECLARE_VTAB ){
1988 sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
1989 goto generated_done;
1991 if( pCol->iDflt>0 ) goto generated_error;
1992 if( pType ){
1993 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
1994 /* no-op */
1995 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
1996 eType = COLFLAG_STORED;
1997 }else{
1998 goto generated_error;
2001 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
2002 pCol->colFlags |= eType;
2003 assert( TF_HasVirtual==COLFLAG_VIRTUAL );
2004 assert( TF_HasStored==COLFLAG_STORED );
2005 pTab->tabFlags |= eType;
2006 if( pCol->colFlags & COLFLAG_PRIMKEY ){
2007 makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
2009 if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
2010 /* The value of a generated column needs to be a real expression, not
2011 ** just a reference to another column, in order for covering index
2012 ** optimizations to work correctly. So if the value is not an expression,
2013 ** turn it into one by adding a unary "+" operator. */
2014 pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
2016 if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
2017 sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
2018 pExpr = 0;
2019 goto generated_done;
2021 generated_error:
2022 sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
2023 pCol->zCnName);
2024 generated_done:
2025 sqlite3ExprDelete(pParse->db, pExpr);
2026 #else
2027 /* Throw and error for the GENERATED ALWAYS AS clause if the
2028 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
2029 sqlite3ErrorMsg(pParse, "generated columns not supported");
2030 sqlite3ExprDelete(pParse->db, pExpr);
2031 #endif
2035 ** Generate code that will increment the schema cookie.
2037 ** The schema cookie is used to determine when the schema for the
2038 ** database changes. After each schema change, the cookie value
2039 ** changes. When a process first reads the schema it records the
2040 ** cookie. Thereafter, whenever it goes to access the database,
2041 ** it checks the cookie to make sure the schema has not changed
2042 ** since it was last read.
2044 ** This plan is not completely bullet-proof. It is possible for
2045 ** the schema to change multiple times and for the cookie to be
2046 ** set back to prior value. But schema changes are infrequent
2047 ** and the probability of hitting the same cookie value is only
2048 ** 1 chance in 2^32. So we're safe enough.
2050 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
2051 ** the schema-version whenever the schema changes.
2053 void sqlite3ChangeCookie(Parse *pParse, int iDb){
2054 sqlite3 *db = pParse->db;
2055 Vdbe *v = pParse->pVdbe;
2056 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2057 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
2058 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
2062 ** Measure the number of characters needed to output the given
2063 ** identifier. The number returned includes any quotes used
2064 ** but does not include the null terminator.
2066 ** The estimate is conservative. It might be larger that what is
2067 ** really needed.
2069 static int identLength(const char *z){
2070 int n;
2071 for(n=0; *z; n++, z++){
2072 if( *z=='"' ){ n++; }
2074 return n + 2;
2078 ** The first parameter is a pointer to an output buffer. The second
2079 ** parameter is a pointer to an integer that contains the offset at
2080 ** which to write into the output buffer. This function copies the
2081 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
2082 ** to the specified offset in the buffer and updates *pIdx to refer
2083 ** to the first byte after the last byte written before returning.
2085 ** If the string zSignedIdent consists entirely of alpha-numeric
2086 ** characters, does not begin with a digit and is not an SQL keyword,
2087 ** then it is copied to the output buffer exactly as it is. Otherwise,
2088 ** it is quoted using double-quotes.
2090 static void identPut(char *z, int *pIdx, char *zSignedIdent){
2091 unsigned char *zIdent = (unsigned char*)zSignedIdent;
2092 int i, j, needQuote;
2093 i = *pIdx;
2095 for(j=0; zIdent[j]; j++){
2096 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
2098 needQuote = sqlite3Isdigit(zIdent[0])
2099 || sqlite3KeywordCode(zIdent, j)!=TK_ID
2100 || zIdent[j]!=0
2101 || j==0;
2103 if( needQuote ) z[i++] = '"';
2104 for(j=0; zIdent[j]; j++){
2105 z[i++] = zIdent[j];
2106 if( zIdent[j]=='"' ) z[i++] = '"';
2108 if( needQuote ) z[i++] = '"';
2109 z[i] = 0;
2110 *pIdx = i;
2114 ** Generate a CREATE TABLE statement appropriate for the given
2115 ** table. Memory to hold the text of the statement is obtained
2116 ** from sqliteMalloc() and must be freed by the calling function.
2118 static char *createTableStmt(sqlite3 *db, Table *p){
2119 int i, k, n;
2120 char *zStmt;
2121 char *zSep, *zSep2, *zEnd;
2122 Column *pCol;
2123 n = 0;
2124 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
2125 n += identLength(pCol->zCnName) + 5;
2127 n += identLength(p->zName);
2128 if( n<50 ){
2129 zSep = "";
2130 zSep2 = ",";
2131 zEnd = ")";
2132 }else{
2133 zSep = "\n ";
2134 zSep2 = ",\n ";
2135 zEnd = "\n)";
2137 n += 35 + 6*p->nCol;
2138 zStmt = sqlite3DbMallocRaw(0, n);
2139 if( zStmt==0 ){
2140 sqlite3OomFault(db);
2141 return 0;
2143 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
2144 k = sqlite3Strlen30(zStmt);
2145 identPut(zStmt, &k, p->zName);
2146 zStmt[k++] = '(';
2147 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
2148 static const char * const azType[] = {
2149 /* SQLITE_AFF_BLOB */ "",
2150 /* SQLITE_AFF_TEXT */ " TEXT",
2151 /* SQLITE_AFF_NUMERIC */ " NUM",
2152 /* SQLITE_AFF_INTEGER */ " INT",
2153 /* SQLITE_AFF_REAL */ " REAL",
2154 /* SQLITE_AFF_FLEXNUM */ " NUM",
2156 int len;
2157 const char *zType;
2159 sqlite3_snprintf(n-k, &zStmt[k], zSep);
2160 k += sqlite3Strlen30(&zStmt[k]);
2161 zSep = zSep2;
2162 identPut(zStmt, &k, pCol->zCnName);
2163 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
2164 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
2165 testcase( pCol->affinity==SQLITE_AFF_BLOB );
2166 testcase( pCol->affinity==SQLITE_AFF_TEXT );
2167 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
2168 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
2169 testcase( pCol->affinity==SQLITE_AFF_REAL );
2170 testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
2172 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
2173 len = sqlite3Strlen30(zType);
2174 assert( pCol->affinity==SQLITE_AFF_BLOB
2175 || pCol->affinity==SQLITE_AFF_FLEXNUM
2176 || pCol->affinity==sqlite3AffinityType(zType, 0) );
2177 memcpy(&zStmt[k], zType, len);
2178 k += len;
2179 assert( k<=n );
2181 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
2182 return zStmt;
2186 ** Resize an Index object to hold N columns total. Return SQLITE_OK
2187 ** on success and SQLITE_NOMEM on an OOM error.
2189 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
2190 char *zExtra;
2191 int nByte;
2192 if( pIdx->nColumn>=N ) return SQLITE_OK;
2193 assert( pIdx->isResized==0 );
2194 nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
2195 zExtra = sqlite3DbMallocZero(db, nByte);
2196 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
2197 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
2198 pIdx->azColl = (const char**)zExtra;
2199 zExtra += sizeof(char*)*N;
2200 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
2201 pIdx->aiRowLogEst = (LogEst*)zExtra;
2202 zExtra += sizeof(LogEst)*N;
2203 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
2204 pIdx->aiColumn = (i16*)zExtra;
2205 zExtra += sizeof(i16)*N;
2206 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
2207 pIdx->aSortOrder = (u8*)zExtra;
2208 pIdx->nColumn = N;
2209 pIdx->isResized = 1;
2210 return SQLITE_OK;
2214 ** Estimate the total row width for a table.
2216 static void estimateTableWidth(Table *pTab){
2217 unsigned wTable = 0;
2218 const Column *pTabCol;
2219 int i;
2220 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
2221 wTable += pTabCol->szEst;
2223 if( pTab->iPKey<0 ) wTable++;
2224 pTab->szTabRow = sqlite3LogEst(wTable*4);
2228 ** Estimate the average size of a row for an index.
2230 static void estimateIndexWidth(Index *pIdx){
2231 unsigned wIndex = 0;
2232 int i;
2233 const Column *aCol = pIdx->pTable->aCol;
2234 for(i=0; i<pIdx->nColumn; i++){
2235 i16 x = pIdx->aiColumn[i];
2236 assert( x<pIdx->pTable->nCol );
2237 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
2239 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
2242 /* Return true if column number x is any of the first nCol entries of aiCol[].
2243 ** This is used to determine if the column number x appears in any of the
2244 ** first nCol entries of an index.
2246 static int hasColumn(const i16 *aiCol, int nCol, int x){
2247 while( nCol-- > 0 ){
2248 if( x==*(aiCol++) ){
2249 return 1;
2252 return 0;
2256 ** Return true if any of the first nKey entries of index pIdx exactly
2257 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
2258 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
2259 ** or may not be the same index as pPk.
2261 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2262 ** not a rowid or expression.
2264 ** This routine differs from hasColumn() in that both the column and the
2265 ** collating sequence must match for this routine, but for hasColumn() only
2266 ** the column name must match.
2268 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
2269 int i, j;
2270 assert( nKey<=pIdx->nColumn );
2271 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
2272 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
2273 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
2274 assert( pPk->pTable==pIdx->pTable );
2275 testcase( pPk==pIdx );
2276 j = pPk->aiColumn[iCol];
2277 assert( j!=XN_ROWID && j!=XN_EXPR );
2278 for(i=0; i<nKey; i++){
2279 assert( pIdx->aiColumn[i]>=0 || j>=0 );
2280 if( pIdx->aiColumn[i]==j
2281 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
2283 return 1;
2286 return 0;
2289 /* Recompute the colNotIdxed field of the Index.
2291 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2292 ** columns that are within the first 63 columns of the table and a 1 for
2293 ** all other bits (all columns that are not in the index). The
2294 ** high-order bit of colNotIdxed is always 1. All unindexed columns
2295 ** of the table have a 1.
2297 ** 2019-10-24: For the purpose of this computation, virtual columns are
2298 ** not considered to be covered by the index, even if they are in the
2299 ** index, because we do not trust the logic in whereIndexExprTrans() to be
2300 ** able to find all instances of a reference to the indexed table column
2301 ** and convert them into references to the index. Hence we always want
2302 ** the actual table at hand in order to recompute the virtual column, if
2303 ** necessary.
2305 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2306 ** to determine if the index is covering index.
2308 static void recomputeColumnsNotIndexed(Index *pIdx){
2309 Bitmask m = 0;
2310 int j;
2311 Table *pTab = pIdx->pTable;
2312 for(j=pIdx->nColumn-1; j>=0; j--){
2313 int x = pIdx->aiColumn[j];
2314 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
2315 testcase( x==BMS-1 );
2316 testcase( x==BMS-2 );
2317 if( x<BMS-1 ) m |= MASKBIT(x);
2320 pIdx->colNotIdxed = ~m;
2321 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
2325 ** This routine runs at the end of parsing a CREATE TABLE statement that
2326 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
2327 ** internal schema data structures and the generated VDBE code so that they
2328 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2329 ** Changes include:
2331 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2332 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2333 ** into BTREE_BLOBKEY.
2334 ** (3) Bypass the creation of the sqlite_schema table entry
2335 ** for the PRIMARY KEY as the primary key index is now
2336 ** identified by the sqlite_schema table entry of the table itself.
2337 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
2338 ** schema to the rootpage from the main table.
2339 ** (5) Add all table columns to the PRIMARY KEY Index object
2340 ** so that the PRIMARY KEY is a covering index. The surplus
2341 ** columns are part of KeyInfo.nAllField and are not used for
2342 ** sorting or lookup or uniqueness checks.
2343 ** (6) Replace the rowid tail on all automatically generated UNIQUE
2344 ** indices with the PRIMARY KEY columns.
2346 ** For virtual tables, only (1) is performed.
2348 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
2349 Index *pIdx;
2350 Index *pPk;
2351 int nPk;
2352 int nExtra;
2353 int i, j;
2354 sqlite3 *db = pParse->db;
2355 Vdbe *v = pParse->pVdbe;
2357 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2359 if( !db->init.imposterTable ){
2360 for(i=0; i<pTab->nCol; i++){
2361 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
2362 && (pTab->aCol[i].notNull==OE_None)
2364 pTab->aCol[i].notNull = OE_Abort;
2367 pTab->tabFlags |= TF_HasNotNull;
2370 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2371 ** into BTREE_BLOBKEY.
2373 assert( !pParse->bReturning );
2374 if( pParse->u1.addrCrTab ){
2375 assert( v );
2376 sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
2379 /* Locate the PRIMARY KEY index. Or, if this table was originally
2380 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2382 if( pTab->iPKey>=0 ){
2383 ExprList *pList;
2384 Token ipkToken;
2385 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
2386 pList = sqlite3ExprListAppend(pParse, 0,
2387 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
2388 if( pList==0 ){
2389 pTab->tabFlags &= ~TF_WithoutRowid;
2390 return;
2392 if( IN_RENAME_OBJECT ){
2393 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2395 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
2396 assert( pParse->pNewTable==pTab );
2397 pTab->iPKey = -1;
2398 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
2399 SQLITE_IDXTYPE_PRIMARYKEY);
2400 if( pParse->nErr ){
2401 pTab->tabFlags &= ~TF_WithoutRowid;
2402 return;
2404 assert( db->mallocFailed==0 );
2405 pPk = sqlite3PrimaryKeyIndex(pTab);
2406 assert( pPk->nKeyCol==1 );
2407 }else{
2408 pPk = sqlite3PrimaryKeyIndex(pTab);
2409 assert( pPk!=0 );
2412 ** Remove all redundant columns from the PRIMARY KEY. For example, change
2413 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
2414 ** code assumes the PRIMARY KEY contains no repeated columns.
2416 for(i=j=1; i<pPk->nKeyCol; i++){
2417 if( isDupColumn(pPk, j, pPk, i) ){
2418 pPk->nColumn--;
2419 }else{
2420 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
2421 pPk->azColl[j] = pPk->azColl[i];
2422 pPk->aSortOrder[j] = pPk->aSortOrder[i];
2423 pPk->aiColumn[j++] = pPk->aiColumn[i];
2426 pPk->nKeyCol = j;
2428 assert( pPk!=0 );
2429 pPk->isCovering = 1;
2430 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
2431 nPk = pPk->nColumn = pPk->nKeyCol;
2433 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2434 ** table entry. This is only required if currently generating VDBE
2435 ** code for a CREATE TABLE (not when parsing one as part of reading
2436 ** a database schema). */
2437 if( v && pPk->tnum>0 ){
2438 assert( db->init.busy==0 );
2439 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
2442 /* The root page of the PRIMARY KEY is the table root page */
2443 pPk->tnum = pTab->tnum;
2445 /* Update the in-memory representation of all UNIQUE indices by converting
2446 ** the final rowid column into one or more columns of the PRIMARY KEY.
2448 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2449 int n;
2450 if( IsPrimaryKeyIndex(pIdx) ) continue;
2451 for(i=n=0; i<nPk; i++){
2452 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2453 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2454 n++;
2457 if( n==0 ){
2458 /* This index is a superset of the primary key */
2459 pIdx->nColumn = pIdx->nKeyCol;
2460 continue;
2462 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
2463 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2464 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2465 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2466 pIdx->aiColumn[j] = pPk->aiColumn[i];
2467 pIdx->azColl[j] = pPk->azColl[i];
2468 if( pPk->aSortOrder[i] ){
2469 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2470 pIdx->bAscKeyBug = 1;
2472 j++;
2475 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
2476 assert( pIdx->nColumn>=j );
2479 /* Add all table columns to the PRIMARY KEY index
2481 nExtra = 0;
2482 for(i=0; i<pTab->nCol; i++){
2483 if( !hasColumn(pPk->aiColumn, nPk, i)
2484 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
2486 if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
2487 for(i=0, j=nPk; i<pTab->nCol; i++){
2488 if( !hasColumn(pPk->aiColumn, j, i)
2489 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
2491 assert( j<pPk->nColumn );
2492 pPk->aiColumn[j] = i;
2493 pPk->azColl[j] = sqlite3StrBINARY;
2494 j++;
2497 assert( pPk->nColumn==j );
2498 assert( pTab->nNVCol<=j );
2499 recomputeColumnsNotIndexed(pPk);
2503 #ifndef SQLITE_OMIT_VIRTUALTABLE
2505 ** Return true if pTab is a virtual table and zName is a shadow table name
2506 ** for that virtual table.
2508 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
2509 int nName; /* Length of zName */
2510 Module *pMod; /* Module for the virtual table */
2512 if( !IsVirtual(pTab) ) return 0;
2513 nName = sqlite3Strlen30(pTab->zName);
2514 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
2515 if( zName[nName]!='_' ) return 0;
2516 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2517 if( pMod==0 ) return 0;
2518 if( pMod->pModule->iVersion<3 ) return 0;
2519 if( pMod->pModule->xShadowName==0 ) return 0;
2520 return pMod->pModule->xShadowName(zName+nName+1);
2522 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2524 #ifndef SQLITE_OMIT_VIRTUALTABLE
2526 ** Table pTab is a virtual table. If it the virtual table implementation
2527 ** exists and has an xShadowName method, then loop over all other ordinary
2528 ** tables within the same schema looking for shadow tables of pTab, and mark
2529 ** any shadow tables seen using the TF_Shadow flag.
2531 void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
2532 int nName; /* Length of pTab->zName */
2533 Module *pMod; /* Module for the virtual table */
2534 HashElem *k; /* For looping through the symbol table */
2536 assert( IsVirtual(pTab) );
2537 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2538 if( pMod==0 ) return;
2539 if( NEVER(pMod->pModule==0) ) return;
2540 if( pMod->pModule->iVersion<3 ) return;
2541 if( pMod->pModule->xShadowName==0 ) return;
2542 assert( pTab->zName!=0 );
2543 nName = sqlite3Strlen30(pTab->zName);
2544 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
2545 Table *pOther = sqliteHashData(k);
2546 assert( pOther->zName!=0 );
2547 if( !IsOrdinaryTable(pOther) ) continue;
2548 if( pOther->tabFlags & TF_Shadow ) continue;
2549 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
2550 && pOther->zName[nName]=='_'
2551 && pMod->pModule->xShadowName(pOther->zName+nName+1)
2553 pOther->tabFlags |= TF_Shadow;
2557 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2559 #ifndef SQLITE_OMIT_VIRTUALTABLE
2561 ** Return true if zName is a shadow table name in the current database
2562 ** connection.
2564 ** zName is temporarily modified while this routine is running, but is
2565 ** restored to its original value prior to this routine returning.
2567 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
2568 char *zTail; /* Pointer to the last "_" in zName */
2569 Table *pTab; /* Table that zName is a shadow of */
2570 zTail = strrchr(zName, '_');
2571 if( zTail==0 ) return 0;
2572 *zTail = 0;
2573 pTab = sqlite3FindTable(db, zName, 0);
2574 *zTail = '_';
2575 if( pTab==0 ) return 0;
2576 if( !IsVirtual(pTab) ) return 0;
2577 return sqlite3IsShadowTableOf(db, pTab, zName);
2579 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2582 #ifdef SQLITE_DEBUG
2584 ** Mark all nodes of an expression as EP_Immutable, indicating that
2585 ** they should not be changed. Expressions attached to a table or
2586 ** index definition are tagged this way to help ensure that we do
2587 ** not pass them into code generator routines by mistake.
2589 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2590 (void)pWalker;
2591 ExprSetVVAProperty(pExpr, EP_Immutable);
2592 return WRC_Continue;
2594 static void markExprListImmutable(ExprList *pList){
2595 if( pList ){
2596 Walker w;
2597 memset(&w, 0, sizeof(w));
2598 w.xExprCallback = markImmutableExprStep;
2599 w.xSelectCallback = sqlite3SelectWalkNoop;
2600 w.xSelectCallback2 = 0;
2601 sqlite3WalkExprList(&w, pList);
2604 #else
2605 #define markExprListImmutable(X) /* no-op */
2606 #endif /* SQLITE_DEBUG */
2610 ** This routine is called to report the final ")" that terminates
2611 ** a CREATE TABLE statement.
2613 ** The table structure that other action routines have been building
2614 ** is added to the internal hash tables, assuming no errors have
2615 ** occurred.
2617 ** An entry for the table is made in the schema table on disk, unless
2618 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
2619 ** it means we are reading the sqlite_schema table because we just
2620 ** connected to the database or because the sqlite_schema table has
2621 ** recently changed, so the entry for this table already exists in
2622 ** the sqlite_schema table. We do not want to create it again.
2624 ** If the pSelect argument is not NULL, it means that this routine
2625 ** was called to create a table generated from a
2626 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2627 ** the new table will match the result set of the SELECT.
2629 void sqlite3EndTable(
2630 Parse *pParse, /* Parse context */
2631 Token *pCons, /* The ',' token after the last column defn. */
2632 Token *pEnd, /* The ')' before options in the CREATE TABLE */
2633 u32 tabOpts, /* Extra table options. Usually 0. */
2634 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
2636 Table *p; /* The new table */
2637 sqlite3 *db = pParse->db; /* The database connection */
2638 int iDb; /* Database in which the table lives */
2639 Index *pIdx; /* An implied index of the table */
2641 if( pEnd==0 && pSelect==0 ){
2642 return;
2644 p = pParse->pNewTable;
2645 if( p==0 ) return;
2647 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
2648 p->tabFlags |= TF_Shadow;
2651 /* If the db->init.busy is 1 it means we are reading the SQL off the
2652 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2653 ** So do not write to the disk again. Extract the root page number
2654 ** for the table from the db->init.newTnum field. (The page number
2655 ** should have been put there by the sqliteOpenCb routine.)
2657 ** If the root page number is 1, that means this is the sqlite_schema
2658 ** table itself. So mark it read-only.
2660 if( db->init.busy ){
2661 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
2662 sqlite3ErrorMsg(pParse, "");
2663 return;
2665 p->tnum = db->init.newTnum;
2666 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2669 /* Special processing for tables that include the STRICT keyword:
2671 ** * Do not allow custom column datatypes. Every column must have
2672 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
2674 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
2675 ** then all columns of the PRIMARY KEY must have a NOT NULL
2676 ** constraint.
2678 if( tabOpts & TF_Strict ){
2679 int ii;
2680 p->tabFlags |= TF_Strict;
2681 for(ii=0; ii<p->nCol; ii++){
2682 Column *pCol = &p->aCol[ii];
2683 if( pCol->eCType==COLTYPE_CUSTOM ){
2684 if( pCol->colFlags & COLFLAG_HASTYPE ){
2685 sqlite3ErrorMsg(pParse,
2686 "unknown datatype for %s.%s: \"%s\"",
2687 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
2689 }else{
2690 sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
2691 p->zName, pCol->zCnName);
2693 return;
2694 }else if( pCol->eCType==COLTYPE_ANY ){
2695 pCol->affinity = SQLITE_AFF_BLOB;
2697 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
2698 && p->iPKey!=ii
2699 && pCol->notNull == OE_None
2701 pCol->notNull = OE_Abort;
2702 p->tabFlags |= TF_HasNotNull;
2707 assert( (p->tabFlags & TF_HasPrimaryKey)==0
2708 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2709 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2710 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2712 /* Special processing for WITHOUT ROWID Tables */
2713 if( tabOpts & TF_WithoutRowid ){
2714 if( (p->tabFlags & TF_Autoincrement) ){
2715 sqlite3ErrorMsg(pParse,
2716 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2717 return;
2719 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2720 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2721 return;
2723 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2724 convertToWithoutRowidTable(pParse, p);
2726 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2728 #ifndef SQLITE_OMIT_CHECK
2729 /* Resolve names in all CHECK constraint expressions.
2731 if( p->pCheck ){
2732 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2733 if( pParse->nErr ){
2734 /* If errors are seen, delete the CHECK constraints now, else they might
2735 ** actually be used if PRAGMA writable_schema=ON is set. */
2736 sqlite3ExprListDelete(db, p->pCheck);
2737 p->pCheck = 0;
2738 }else{
2739 markExprListImmutable(p->pCheck);
2742 #endif /* !defined(SQLITE_OMIT_CHECK) */
2743 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2744 if( p->tabFlags & TF_HasGenerated ){
2745 int ii, nNG = 0;
2746 testcase( p->tabFlags & TF_HasVirtual );
2747 testcase( p->tabFlags & TF_HasStored );
2748 for(ii=0; ii<p->nCol; ii++){
2749 u32 colFlags = p->aCol[ii].colFlags;
2750 if( (colFlags & COLFLAG_GENERATED)!=0 ){
2751 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
2752 testcase( colFlags & COLFLAG_VIRTUAL );
2753 testcase( colFlags & COLFLAG_STORED );
2754 if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
2755 /* If there are errors in resolving the expression, change the
2756 ** expression to a NULL. This prevents code generators that operate
2757 ** on the expression from inserting extra parts into the expression
2758 ** tree that have been allocated from lookaside memory, which is
2759 ** illegal in a schema and will lead to errors or heap corruption
2760 ** when the database connection closes. */
2761 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
2762 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
2764 }else{
2765 nNG++;
2768 if( nNG==0 ){
2769 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
2770 return;
2773 #endif
2775 /* Estimate the average row size for the table and for all implied indices */
2776 estimateTableWidth(p);
2777 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2778 estimateIndexWidth(pIdx);
2781 /* If not initializing, then create a record for the new table
2782 ** in the schema table of the database.
2784 ** If this is a TEMPORARY table, write the entry into the auxiliary
2785 ** file instead of into the main database file.
2787 if( !db->init.busy ){
2788 int n;
2789 Vdbe *v;
2790 char *zType; /* "view" or "table" */
2791 char *zType2; /* "VIEW" or "TABLE" */
2792 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
2794 v = sqlite3GetVdbe(pParse);
2795 if( NEVER(v==0) ) return;
2797 sqlite3VdbeAddOp1(v, OP_Close, 0);
2800 ** Initialize zType for the new view or table.
2802 if( IsOrdinaryTable(p) ){
2803 /* A regular table */
2804 zType = "table";
2805 zType2 = "TABLE";
2806 #ifndef SQLITE_OMIT_VIEW
2807 }else{
2808 /* A view */
2809 zType = "view";
2810 zType2 = "VIEW";
2811 #endif
2814 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2815 ** statement to populate the new table. The root-page number for the
2816 ** new table is in register pParse->regRoot.
2818 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2819 ** suitable state to query for the column names and types to be used
2820 ** by the new table.
2822 ** A shared-cache write-lock is not required to write to the new table,
2823 ** as a schema-lock must have already been obtained to create it. Since
2824 ** a schema-lock excludes all other database users, the write-lock would
2825 ** be redundant.
2827 if( pSelect ){
2828 SelectDest dest; /* Where the SELECT should store results */
2829 int regYield; /* Register holding co-routine entry-point */
2830 int addrTop; /* Top of the co-routine */
2831 int regRec; /* A record to be insert into the new table */
2832 int regRowid; /* Rowid of the next row to insert */
2833 int addrInsLoop; /* Top of the loop for inserting rows */
2834 Table *pSelTab; /* A table that describes the SELECT results */
2836 if( IN_SPECIAL_PARSE ){
2837 pParse->rc = SQLITE_ERROR;
2838 pParse->nErr++;
2839 return;
2841 regYield = ++pParse->nMem;
2842 regRec = ++pParse->nMem;
2843 regRowid = ++pParse->nMem;
2844 assert(pParse->nTab==1);
2845 sqlite3MayAbort(pParse);
2846 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
2847 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2848 pParse->nTab = 2;
2849 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2850 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2851 if( pParse->nErr ) return;
2852 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
2853 if( pSelTab==0 ) return;
2854 assert( p->aCol==0 );
2855 p->nCol = p->nNVCol = pSelTab->nCol;
2856 p->aCol = pSelTab->aCol;
2857 pSelTab->nCol = 0;
2858 pSelTab->aCol = 0;
2859 sqlite3DeleteTable(db, pSelTab);
2860 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2861 sqlite3Select(pParse, pSelect, &dest);
2862 if( pParse->nErr ) return;
2863 sqlite3VdbeEndCoroutine(v, regYield);
2864 sqlite3VdbeJumpHere(v, addrTop - 1);
2865 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2866 VdbeCoverage(v);
2867 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2868 sqlite3TableAffinity(v, p, 0);
2869 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2870 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
2871 sqlite3VdbeGoto(v, addrInsLoop);
2872 sqlite3VdbeJumpHere(v, addrInsLoop);
2873 sqlite3VdbeAddOp1(v, OP_Close, 1);
2876 /* Compute the complete text of the CREATE statement */
2877 if( pSelect ){
2878 zStmt = createTableStmt(db, p);
2879 }else{
2880 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2881 n = (int)(pEnd2->z - pParse->sNameToken.z);
2882 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
2883 zStmt = sqlite3MPrintf(db,
2884 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2888 /* A slot for the record has already been allocated in the
2889 ** schema table. We just need to update that slot with all
2890 ** the information we've collected.
2892 sqlite3NestedParse(pParse,
2893 "UPDATE %Q." LEGACY_SCHEMA_TABLE
2894 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2895 " WHERE rowid=#%d",
2896 db->aDb[iDb].zDbSName,
2897 zType,
2898 p->zName,
2899 p->zName,
2900 pParse->regRoot,
2901 zStmt,
2902 pParse->regRowid
2904 sqlite3DbFree(db, zStmt);
2905 sqlite3ChangeCookie(pParse, iDb);
2907 #ifndef SQLITE_OMIT_AUTOINCREMENT
2908 /* Check to see if we need to create an sqlite_sequence table for
2909 ** keeping track of autoincrement keys.
2911 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
2912 Db *pDb = &db->aDb[iDb];
2913 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2914 if( pDb->pSchema->pSeqTab==0 ){
2915 sqlite3NestedParse(pParse,
2916 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2917 pDb->zDbSName
2921 #endif
2923 /* Reparse everything to update our internal data structures */
2924 sqlite3VdbeAddParseSchemaOp(v, iDb,
2925 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
2928 /* Add the table to the in-memory representation of the database.
2930 if( db->init.busy ){
2931 Table *pOld;
2932 Schema *pSchema = p->pSchema;
2933 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2934 assert( HasRowid(p) || p->iPKey<0 );
2935 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
2936 if( pOld ){
2937 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
2938 sqlite3OomFault(db);
2939 return;
2941 pParse->pNewTable = 0;
2942 db->mDbFlags |= DBFLAG_SchemaChange;
2944 /* If this is the magic sqlite_sequence table used by autoincrement,
2945 ** then record a pointer to this table in the main database structure
2946 ** so that INSERT can find the table easily. */
2947 assert( !pParse->nested );
2948 #ifndef SQLITE_OMIT_AUTOINCREMENT
2949 if( strcmp(p->zName, "sqlite_sequence")==0 ){
2950 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2951 p->pSchema->pSeqTab = p;
2953 #endif
2956 #ifndef SQLITE_OMIT_ALTERTABLE
2957 if( !pSelect && IsOrdinaryTable(p) ){
2958 assert( pCons && pEnd );
2959 if( pCons->z==0 ){
2960 pCons = pEnd;
2962 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
2964 #endif
2967 #ifndef SQLITE_OMIT_VIEW
2969 ** The parser calls this routine in order to create a new VIEW
2971 void sqlite3CreateView(
2972 Parse *pParse, /* The parsing context */
2973 Token *pBegin, /* The CREATE token that begins the statement */
2974 Token *pName1, /* The token that holds the name of the view */
2975 Token *pName2, /* The token that holds the name of the view */
2976 ExprList *pCNames, /* Optional list of view column names */
2977 Select *pSelect, /* A SELECT statement that will become the new view */
2978 int isTemp, /* TRUE for a TEMPORARY view */
2979 int noErr /* Suppress error messages if VIEW already exists */
2981 Table *p;
2982 int n;
2983 const char *z;
2984 Token sEnd;
2985 DbFixer sFix;
2986 Token *pName = 0;
2987 int iDb;
2988 sqlite3 *db = pParse->db;
2990 if( pParse->nVar>0 ){
2991 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
2992 goto create_view_fail;
2994 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
2995 p = pParse->pNewTable;
2996 if( p==0 || pParse->nErr ) goto create_view_fail;
2998 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
2999 ** on a view, even though views do not have rowids. The following flag
3000 ** setting fixes this problem. But the fix can be disabled by compiling
3001 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
3002 ** depend upon the old buggy behavior. */
3003 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
3004 p->tabFlags |= TF_NoVisibleRowid;
3005 #endif
3007 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3008 iDb = sqlite3SchemaToIndex(db, p->pSchema);
3009 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
3010 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
3012 /* Make a copy of the entire SELECT statement that defines the view.
3013 ** This will force all the Expr.token.z values to be dynamically
3014 ** allocated rather than point to the input string - which means that
3015 ** they will persist after the current sqlite3_exec() call returns.
3017 pSelect->selFlags |= SF_View;
3018 if( IN_RENAME_OBJECT ){
3019 p->u.view.pSelect = pSelect;
3020 pSelect = 0;
3021 }else{
3022 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
3024 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
3025 p->eTabType = TABTYP_VIEW;
3026 if( db->mallocFailed ) goto create_view_fail;
3028 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
3029 ** the end.
3031 sEnd = pParse->sLastToken;
3032 assert( sEnd.z[0]!=0 || sEnd.n==0 );
3033 if( sEnd.z[0]!=';' ){
3034 sEnd.z += sEnd.n;
3036 sEnd.n = 0;
3037 n = (int)(sEnd.z - pBegin->z);
3038 assert( n>0 );
3039 z = pBegin->z;
3040 while( sqlite3Isspace(z[n-1]) ){ n--; }
3041 sEnd.z = &z[n-1];
3042 sEnd.n = 1;
3044 /* Use sqlite3EndTable() to add the view to the schema table */
3045 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
3047 create_view_fail:
3048 sqlite3SelectDelete(db, pSelect);
3049 if( IN_RENAME_OBJECT ){
3050 sqlite3RenameExprlistUnmap(pParse, pCNames);
3052 sqlite3ExprListDelete(db, pCNames);
3053 return;
3055 #endif /* SQLITE_OMIT_VIEW */
3057 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3059 ** The Table structure pTable is really a VIEW. Fill in the names of
3060 ** the columns of the view in the pTable structure. Return the number
3061 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
3063 static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
3064 Table *pSelTab; /* A fake table from which we get the result set */
3065 Select *pSel; /* Copy of the SELECT that implements the view */
3066 int nErr = 0; /* Number of errors encountered */
3067 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
3068 #ifndef SQLITE_OMIT_VIRTUALTABLE
3069 int rc;
3070 #endif
3071 #ifndef SQLITE_OMIT_AUTHORIZATION
3072 sqlite3_xauth xAuth; /* Saved xAuth pointer */
3073 #endif
3075 assert( pTable );
3077 #ifndef SQLITE_OMIT_VIRTUALTABLE
3078 if( IsVirtual(pTable) ){
3079 db->nSchemaLock++;
3080 rc = sqlite3VtabCallConnect(pParse, pTable);
3081 db->nSchemaLock--;
3082 return rc;
3084 #endif
3086 #ifndef SQLITE_OMIT_VIEW
3087 /* A positive nCol means the columns names for this view are
3088 ** already known. This routine is not called unless either the
3089 ** table is virtual or nCol is zero.
3091 assert( pTable->nCol<=0 );
3093 /* A negative nCol is a special marker meaning that we are currently
3094 ** trying to compute the column names. If we enter this routine with
3095 ** a negative nCol, it means two or more views form a loop, like this:
3097 ** CREATE VIEW one AS SELECT * FROM two;
3098 ** CREATE VIEW two AS SELECT * FROM one;
3100 ** Actually, the error above is now caught prior to reaching this point.
3101 ** But the following test is still important as it does come up
3102 ** in the following:
3104 ** CREATE TABLE main.ex1(a);
3105 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3106 ** SELECT * FROM temp.ex1;
3108 if( pTable->nCol<0 ){
3109 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
3110 return 1;
3112 assert( pTable->nCol>=0 );
3114 /* If we get this far, it means we need to compute the table names.
3115 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
3116 ** "*" elements in the results set of the view and will assign cursors
3117 ** to the elements of the FROM clause. But we do not want these changes
3118 ** to be permanent. So the computation is done on a copy of the SELECT
3119 ** statement that defines the view.
3121 assert( IsView(pTable) );
3122 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
3123 if( pSel ){
3124 u8 eParseMode = pParse->eParseMode;
3125 int nTab = pParse->nTab;
3126 int nSelect = pParse->nSelect;
3127 pParse->eParseMode = PARSE_MODE_NORMAL;
3128 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
3129 pTable->nCol = -1;
3130 DisableLookaside;
3131 #ifndef SQLITE_OMIT_AUTHORIZATION
3132 xAuth = db->xAuth;
3133 db->xAuth = 0;
3134 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3135 db->xAuth = xAuth;
3136 #else
3137 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3138 #endif
3139 pParse->nTab = nTab;
3140 pParse->nSelect = nSelect;
3141 if( pSelTab==0 ){
3142 pTable->nCol = 0;
3143 nErr++;
3144 }else if( pTable->pCheck ){
3145 /* CREATE VIEW name(arglist) AS ...
3146 ** The names of the columns in the table are taken from
3147 ** arglist which is stored in pTable->pCheck. The pCheck field
3148 ** normally holds CHECK constraints on an ordinary table, but for
3149 ** a VIEW it holds the list of column names.
3151 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
3152 &pTable->nCol, &pTable->aCol);
3153 if( pParse->nErr==0
3154 && pTable->nCol==pSel->pEList->nExpr
3156 assert( db->mallocFailed==0 );
3157 sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
3159 }else{
3160 /* CREATE VIEW name AS... without an argument list. Construct
3161 ** the column names from the SELECT statement that defines the view.
3163 assert( pTable->aCol==0 );
3164 pTable->nCol = pSelTab->nCol;
3165 pTable->aCol = pSelTab->aCol;
3166 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
3167 pSelTab->nCol = 0;
3168 pSelTab->aCol = 0;
3169 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
3171 pTable->nNVCol = pTable->nCol;
3172 sqlite3DeleteTable(db, pSelTab);
3173 sqlite3SelectDelete(db, pSel);
3174 EnableLookaside;
3175 pParse->eParseMode = eParseMode;
3176 } else {
3177 nErr++;
3179 pTable->pSchema->schemaFlags |= DB_UnresetViews;
3180 if( db->mallocFailed ){
3181 sqlite3DeleteColumnNames(db, pTable);
3183 #endif /* SQLITE_OMIT_VIEW */
3184 return nErr;
3186 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
3187 assert( pTable!=0 );
3188 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
3189 return viewGetColumnNames(pParse, pTable);
3191 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3193 #ifndef SQLITE_OMIT_VIEW
3195 ** Clear the column names from every VIEW in database idx.
3197 static void sqliteViewResetAll(sqlite3 *db, int idx){
3198 HashElem *i;
3199 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
3200 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
3201 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
3202 Table *pTab = sqliteHashData(i);
3203 if( IsView(pTab) ){
3204 sqlite3DeleteColumnNames(db, pTab);
3207 DbClearProperty(db, idx, DB_UnresetViews);
3209 #else
3210 # define sqliteViewResetAll(A,B)
3211 #endif /* SQLITE_OMIT_VIEW */
3214 ** This function is called by the VDBE to adjust the internal schema
3215 ** used by SQLite when the btree layer moves a table root page. The
3216 ** root-page of a table or index in database iDb has changed from iFrom
3217 ** to iTo.
3219 ** Ticket #1728: The symbol table might still contain information
3220 ** on tables and/or indices that are the process of being deleted.
3221 ** If you are unlucky, one of those deleted indices or tables might
3222 ** have the same rootpage number as the real table or index that is
3223 ** being moved. So we cannot stop searching after the first match
3224 ** because the first match might be for one of the deleted indices
3225 ** or tables and not the table/index that is actually being moved.
3226 ** We must continue looping until all tables and indices with
3227 ** rootpage==iFrom have been converted to have a rootpage of iTo
3228 ** in order to be certain that we got the right one.
3230 #ifndef SQLITE_OMIT_AUTOVACUUM
3231 void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
3232 HashElem *pElem;
3233 Hash *pHash;
3234 Db *pDb;
3236 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3237 pDb = &db->aDb[iDb];
3238 pHash = &pDb->pSchema->tblHash;
3239 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3240 Table *pTab = sqliteHashData(pElem);
3241 if( pTab->tnum==iFrom ){
3242 pTab->tnum = iTo;
3245 pHash = &pDb->pSchema->idxHash;
3246 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3247 Index *pIdx = sqliteHashData(pElem);
3248 if( pIdx->tnum==iFrom ){
3249 pIdx->tnum = iTo;
3253 #endif
3256 ** Write code to erase the table with root-page iTable from database iDb.
3257 ** Also write code to modify the sqlite_schema table and internal schema
3258 ** if a root-page of another table is moved by the btree-layer whilst
3259 ** erasing iTable (this can happen with an auto-vacuum database).
3261 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
3262 Vdbe *v = sqlite3GetVdbe(pParse);
3263 int r1 = sqlite3GetTempReg(pParse);
3264 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
3265 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
3266 sqlite3MayAbort(pParse);
3267 #ifndef SQLITE_OMIT_AUTOVACUUM
3268 /* OP_Destroy stores an in integer r1. If this integer
3269 ** is non-zero, then it is the root page number of a table moved to
3270 ** location iTable. The following code modifies the sqlite_schema table to
3271 ** reflect this.
3273 ** The "#NNN" in the SQL is a special constant that means whatever value
3274 ** is in register NNN. See grammar rules associated with the TK_REGISTER
3275 ** token for additional information.
3277 sqlite3NestedParse(pParse,
3278 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3279 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3280 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
3281 #endif
3282 sqlite3ReleaseTempReg(pParse, r1);
3286 ** Write VDBE code to erase table pTab and all associated indices on disk.
3287 ** Code to update the sqlite_schema tables and internal schema definitions
3288 ** in case a root-page belonging to another table is moved by the btree layer
3289 ** is also added (this can happen with an auto-vacuum database).
3291 static void destroyTable(Parse *pParse, Table *pTab){
3292 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3293 ** is not defined), then it is important to call OP_Destroy on the
3294 ** table and index root-pages in order, starting with the numerically
3295 ** largest root-page number. This guarantees that none of the root-pages
3296 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3297 ** following were coded:
3299 ** OP_Destroy 4 0
3300 ** ...
3301 ** OP_Destroy 5 0
3303 ** and root page 5 happened to be the largest root-page number in the
3304 ** database, then root page 5 would be moved to page 4 by the
3305 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3306 ** a free-list page.
3308 Pgno iTab = pTab->tnum;
3309 Pgno iDestroyed = 0;
3311 while( 1 ){
3312 Index *pIdx;
3313 Pgno iLargest = 0;
3315 if( iDestroyed==0 || iTab<iDestroyed ){
3316 iLargest = iTab;
3318 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3319 Pgno iIdx = pIdx->tnum;
3320 assert( pIdx->pSchema==pTab->pSchema );
3321 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
3322 iLargest = iIdx;
3325 if( iLargest==0 ){
3326 return;
3327 }else{
3328 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3329 assert( iDb>=0 && iDb<pParse->db->nDb );
3330 destroyRootPage(pParse, iLargest, iDb);
3331 iDestroyed = iLargest;
3337 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3338 ** after a DROP INDEX or DROP TABLE command.
3340 static void sqlite3ClearStatTables(
3341 Parse *pParse, /* The parsing context */
3342 int iDb, /* The database number */
3343 const char *zType, /* "idx" or "tbl" */
3344 const char *zName /* Name of index or table */
3346 int i;
3347 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
3348 for(i=1; i<=4; i++){
3349 char zTab[24];
3350 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
3351 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
3352 sqlite3NestedParse(pParse,
3353 "DELETE FROM %Q.%s WHERE %s=%Q",
3354 zDbName, zTab, zType, zName
3361 ** Generate code to drop a table.
3363 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
3364 Vdbe *v;
3365 sqlite3 *db = pParse->db;
3366 Trigger *pTrigger;
3367 Db *pDb = &db->aDb[iDb];
3369 v = sqlite3GetVdbe(pParse);
3370 assert( v!=0 );
3371 sqlite3BeginWriteOperation(pParse, 1, iDb);
3373 #ifndef SQLITE_OMIT_VIRTUALTABLE
3374 if( IsVirtual(pTab) ){
3375 sqlite3VdbeAddOp0(v, OP_VBegin);
3377 #endif
3379 /* Drop all triggers associated with the table being dropped. Code
3380 ** is generated to remove entries from sqlite_schema and/or
3381 ** sqlite_temp_schema if required.
3383 pTrigger = sqlite3TriggerList(pParse, pTab);
3384 while( pTrigger ){
3385 assert( pTrigger->pSchema==pTab->pSchema ||
3386 pTrigger->pSchema==db->aDb[1].pSchema );
3387 sqlite3DropTriggerPtr(pParse, pTrigger);
3388 pTrigger = pTrigger->pNext;
3391 #ifndef SQLITE_OMIT_AUTOINCREMENT
3392 /* Remove any entries of the sqlite_sequence table associated with
3393 ** the table being dropped. This is done before the table is dropped
3394 ** at the btree level, in case the sqlite_sequence table needs to
3395 ** move as a result of the drop (can happen in auto-vacuum mode).
3397 if( pTab->tabFlags & TF_Autoincrement ){
3398 sqlite3NestedParse(pParse,
3399 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3400 pDb->zDbSName, pTab->zName
3403 #endif
3405 /* Drop all entries in the schema table that refer to the
3406 ** table. The program name loops through the schema table and deletes
3407 ** every row that refers to a table of the same name as the one being
3408 ** dropped. Triggers are handled separately because a trigger can be
3409 ** created in the temp database that refers to a table in another
3410 ** database.
3412 sqlite3NestedParse(pParse,
3413 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3414 " WHERE tbl_name=%Q and type!='trigger'",
3415 pDb->zDbSName, pTab->zName);
3416 if( !isView && !IsVirtual(pTab) ){
3417 destroyTable(pParse, pTab);
3420 /* Remove the table entry from SQLite's internal schema and modify
3421 ** the schema cookie.
3423 if( IsVirtual(pTab) ){
3424 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
3425 sqlite3MayAbort(pParse);
3427 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
3428 sqlite3ChangeCookie(pParse, iDb);
3429 sqliteViewResetAll(db, iDb);
3433 ** Return TRUE if shadow tables should be read-only in the current
3434 ** context.
3436 int sqlite3ReadOnlyShadowTables(sqlite3 *db){
3437 #ifndef SQLITE_OMIT_VIRTUALTABLE
3438 if( (db->flags & SQLITE_Defensive)!=0
3439 && db->pVtabCtx==0
3440 && db->nVdbeExec==0
3441 && !sqlite3VtabInSync(db)
3443 return 1;
3445 #endif
3446 return 0;
3450 ** Return true if it is not allowed to drop the given table
3452 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
3453 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
3454 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
3455 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
3456 return 1;
3458 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
3459 return 1;
3461 if( pTab->tabFlags & TF_Eponymous ){
3462 return 1;
3464 return 0;
3468 ** This routine is called to do the work of a DROP TABLE statement.
3469 ** pName is the name of the table to be dropped.
3471 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3472 Table *pTab;
3473 Vdbe *v;
3474 sqlite3 *db = pParse->db;
3475 int iDb;
3477 if( db->mallocFailed ){
3478 goto exit_drop_table;
3480 assert( pParse->nErr==0 );
3481 assert( pName->nSrc==1 );
3482 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3483 if( noErr ) db->suppressErr++;
3484 assert( isView==0 || isView==LOCATE_VIEW );
3485 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3486 if( noErr ) db->suppressErr--;
3488 if( pTab==0 ){
3489 if( noErr ){
3490 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
3491 sqlite3ForceNotReadOnly(pParse);
3493 goto exit_drop_table;
3495 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3496 assert( iDb>=0 && iDb<db->nDb );
3498 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3499 ** it is initialized.
3501 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3502 goto exit_drop_table;
3504 #ifndef SQLITE_OMIT_AUTHORIZATION
3506 int code;
3507 const char *zTab = SCHEMA_TABLE(iDb);
3508 const char *zDb = db->aDb[iDb].zDbSName;
3509 const char *zArg2 = 0;
3510 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3511 goto exit_drop_table;
3513 if( isView ){
3514 if( !OMIT_TEMPDB && iDb==1 ){
3515 code = SQLITE_DROP_TEMP_VIEW;
3516 }else{
3517 code = SQLITE_DROP_VIEW;
3519 #ifndef SQLITE_OMIT_VIRTUALTABLE
3520 }else if( IsVirtual(pTab) ){
3521 code = SQLITE_DROP_VTABLE;
3522 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
3523 #endif
3524 }else{
3525 if( !OMIT_TEMPDB && iDb==1 ){
3526 code = SQLITE_DROP_TEMP_TABLE;
3527 }else{
3528 code = SQLITE_DROP_TABLE;
3531 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3532 goto exit_drop_table;
3534 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3535 goto exit_drop_table;
3538 #endif
3539 if( tableMayNotBeDropped(db, pTab) ){
3540 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3541 goto exit_drop_table;
3544 #ifndef SQLITE_OMIT_VIEW
3545 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3546 ** on a table.
3548 if( isView && !IsView(pTab) ){
3549 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3550 goto exit_drop_table;
3552 if( !isView && IsView(pTab) ){
3553 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3554 goto exit_drop_table;
3556 #endif
3558 /* Generate code to remove the table from the schema table
3559 ** on disk.
3561 v = sqlite3GetVdbe(pParse);
3562 if( v ){
3563 sqlite3BeginWriteOperation(pParse, 1, iDb);
3564 if( !isView ){
3565 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3566 sqlite3FkDropTable(pParse, pName, pTab);
3568 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
3571 exit_drop_table:
3572 sqlite3SrcListDelete(db, pName);
3576 ** This routine is called to create a new foreign key on the table
3577 ** currently under construction. pFromCol determines which columns
3578 ** in the current table point to the foreign key. If pFromCol==0 then
3579 ** connect the key to the last column inserted. pTo is the name of
3580 ** the table referred to (a.k.a the "parent" table). pToCol is a list
3581 ** of tables in the parent pTo table. flags contains all
3582 ** information about the conflict resolution algorithms specified
3583 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3585 ** An FKey structure is created and added to the table currently
3586 ** under construction in the pParse->pNewTable field.
3588 ** The foreign key is set for IMMEDIATE processing. A subsequent call
3589 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3591 void sqlite3CreateForeignKey(
3592 Parse *pParse, /* Parsing context */
3593 ExprList *pFromCol, /* Columns in this table that point to other table */
3594 Token *pTo, /* Name of the other table */
3595 ExprList *pToCol, /* Columns in the other table */
3596 int flags /* Conflict resolution algorithms. */
3598 sqlite3 *db = pParse->db;
3599 #ifndef SQLITE_OMIT_FOREIGN_KEY
3600 FKey *pFKey = 0;
3601 FKey *pNextTo;
3602 Table *p = pParse->pNewTable;
3603 i64 nByte;
3604 int i;
3605 int nCol;
3606 char *z;
3608 assert( pTo!=0 );
3609 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3610 if( pFromCol==0 ){
3611 int iCol = p->nCol-1;
3612 if( NEVER(iCol<0) ) goto fk_end;
3613 if( pToCol && pToCol->nExpr!=1 ){
3614 sqlite3ErrorMsg(pParse, "foreign key on %s"
3615 " should reference only one column of table %T",
3616 p->aCol[iCol].zCnName, pTo);
3617 goto fk_end;
3619 nCol = 1;
3620 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
3621 sqlite3ErrorMsg(pParse,
3622 "number of columns in foreign key does not match the number of "
3623 "columns in the referenced table");
3624 goto fk_end;
3625 }else{
3626 nCol = pFromCol->nExpr;
3628 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
3629 if( pToCol ){
3630 for(i=0; i<pToCol->nExpr; i++){
3631 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3634 pFKey = sqlite3DbMallocZero(db, nByte );
3635 if( pFKey==0 ){
3636 goto fk_end;
3638 pFKey->pFrom = p;
3639 assert( IsOrdinaryTable(p) );
3640 pFKey->pNextFrom = p->u.tab.pFKey;
3641 z = (char*)&pFKey->aCol[nCol];
3642 pFKey->zTo = z;
3643 if( IN_RENAME_OBJECT ){
3644 sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3646 memcpy(z, pTo->z, pTo->n);
3647 z[pTo->n] = 0;
3648 sqlite3Dequote(z);
3649 z += pTo->n+1;
3650 pFKey->nCol = nCol;
3651 if( pFromCol==0 ){
3652 pFKey->aCol[0].iFrom = p->nCol-1;
3653 }else{
3654 for(i=0; i<nCol; i++){
3655 int j;
3656 for(j=0; j<p->nCol; j++){
3657 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
3658 pFKey->aCol[i].iFrom = j;
3659 break;
3662 if( j>=p->nCol ){
3663 sqlite3ErrorMsg(pParse,
3664 "unknown column \"%s\" in foreign key definition",
3665 pFromCol->a[i].zEName);
3666 goto fk_end;
3668 if( IN_RENAME_OBJECT ){
3669 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3673 if( pToCol ){
3674 for(i=0; i<nCol; i++){
3675 int n = sqlite3Strlen30(pToCol->a[i].zEName);
3676 pFKey->aCol[i].zCol = z;
3677 if( IN_RENAME_OBJECT ){
3678 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
3680 memcpy(z, pToCol->a[i].zEName, n);
3681 z[n] = 0;
3682 z += n+1;
3685 pFKey->isDeferred = 0;
3686 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
3687 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
3689 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
3690 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3691 pFKey->zTo, (void *)pFKey
3693 if( pNextTo==pFKey ){
3694 sqlite3OomFault(db);
3695 goto fk_end;
3697 if( pNextTo ){
3698 assert( pNextTo->pPrevTo==0 );
3699 pFKey->pNextTo = pNextTo;
3700 pNextTo->pPrevTo = pFKey;
3703 /* Link the foreign key to the table as the last step.
3705 assert( IsOrdinaryTable(p) );
3706 p->u.tab.pFKey = pFKey;
3707 pFKey = 0;
3709 fk_end:
3710 sqlite3DbFree(db, pFKey);
3711 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3712 sqlite3ExprListDelete(db, pFromCol);
3713 sqlite3ExprListDelete(db, pToCol);
3717 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3718 ** clause is seen as part of a foreign key definition. The isDeferred
3719 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3720 ** The behavior of the most recently created foreign key is adjusted
3721 ** accordingly.
3723 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3724 #ifndef SQLITE_OMIT_FOREIGN_KEY
3725 Table *pTab;
3726 FKey *pFKey;
3727 if( (pTab = pParse->pNewTable)==0 ) return;
3728 if( NEVER(!IsOrdinaryTable(pTab)) ) return;
3729 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
3730 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3731 pFKey->isDeferred = (u8)isDeferred;
3732 #endif
3736 ** Generate code that will erase and refill index *pIdx. This is
3737 ** used to initialize a newly created index or to recompute the
3738 ** content of an index in response to a REINDEX command.
3740 ** if memRootPage is not negative, it means that the index is newly
3741 ** created. The register specified by memRootPage contains the
3742 ** root page number of the index. If memRootPage is negative, then
3743 ** the index already exists and must be cleared before being refilled and
3744 ** the root page number of the index is taken from pIndex->tnum.
3746 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3747 Table *pTab = pIndex->pTable; /* The table that is indexed */
3748 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
3749 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
3750 int iSorter; /* Cursor opened by OpenSorter (if in use) */
3751 int addr1; /* Address of top of loop */
3752 int addr2; /* Address to jump to for next iteration */
3753 Pgno tnum; /* Root page of index */
3754 int iPartIdxLabel; /* Jump to this label to skip a row */
3755 Vdbe *v; /* Generate code into this virtual machine */
3756 KeyInfo *pKey; /* KeyInfo for index */
3757 int regRecord; /* Register holding assembled index record */
3758 sqlite3 *db = pParse->db; /* The database connection */
3759 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3761 #ifndef SQLITE_OMIT_AUTHORIZATION
3762 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3763 db->aDb[iDb].zDbSName ) ){
3764 return;
3766 #endif
3768 /* Require a write-lock on the table to perform this operation */
3769 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3771 v = sqlite3GetVdbe(pParse);
3772 if( v==0 ) return;
3773 if( memRootPage>=0 ){
3774 tnum = (Pgno)memRootPage;
3775 }else{
3776 tnum = pIndex->tnum;
3778 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3779 assert( pKey!=0 || pParse->nErr );
3781 /* Open the sorter cursor if we are to use one. */
3782 iSorter = pParse->nTab++;
3783 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3784 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3786 /* Open the table. Loop through all rows of the table, inserting index
3787 ** records into the sorter. */
3788 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3789 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3790 regRecord = sqlite3GetTempReg(pParse);
3791 sqlite3MultiWrite(pParse);
3793 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3794 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3795 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3796 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3797 sqlite3VdbeJumpHere(v, addr1);
3798 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3799 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
3800 (char *)pKey, P4_KEYINFO);
3801 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3803 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3804 if( IsUniqueIndex(pIndex) ){
3805 int j2 = sqlite3VdbeGoto(v, 1);
3806 addr2 = sqlite3VdbeCurrentAddr(v);
3807 sqlite3VdbeVerifyAbortable(v, OE_Abort);
3808 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3809 pIndex->nKeyCol); VdbeCoverage(v);
3810 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3811 sqlite3VdbeJumpHere(v, j2);
3812 }else{
3813 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3814 ** abort. The exception is if one of the indexed expressions contains a
3815 ** user function that throws an exception when it is evaluated. But the
3816 ** overhead of adding a statement journal to a CREATE INDEX statement is
3817 ** very small (since most of the pages written do not contain content that
3818 ** needs to be restored if the statement aborts), so we call
3819 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3820 sqlite3MayAbort(pParse);
3821 addr2 = sqlite3VdbeCurrentAddr(v);
3823 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3824 if( !pIndex->bAscKeyBug ){
3825 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3826 ** faster by avoiding unnecessary seeks. But the optimization does
3827 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3828 ** with DESC primary keys, since those indexes have there keys in
3829 ** a different order from the main table.
3830 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3832 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3834 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3835 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3836 sqlite3ReleaseTempReg(pParse, regRecord);
3837 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3838 sqlite3VdbeJumpHere(v, addr1);
3840 sqlite3VdbeAddOp1(v, OP_Close, iTab);
3841 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3842 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3846 ** Allocate heap space to hold an Index object with nCol columns.
3848 ** Increase the allocation size to provide an extra nExtra bytes
3849 ** of 8-byte aligned space after the Index object and return a
3850 ** pointer to this extra space in *ppExtra.
3852 Index *sqlite3AllocateIndexObject(
3853 sqlite3 *db, /* Database connection */
3854 i16 nCol, /* Total number of columns in the index */
3855 int nExtra, /* Number of bytes of extra space to alloc */
3856 char **ppExtra /* Pointer to the "extra" space */
3858 Index *p; /* Allocated index object */
3859 int nByte; /* Bytes of space for Index object + arrays */
3861 nByte = ROUND8(sizeof(Index)) + /* Index structure */
3862 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
3863 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
3864 sizeof(i16)*nCol + /* Index.aiColumn */
3865 sizeof(u8)*nCol); /* Index.aSortOrder */
3866 p = sqlite3DbMallocZero(db, nByte + nExtra);
3867 if( p ){
3868 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
3869 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
3870 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
3871 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
3872 p->aSortOrder = (u8*)pExtra;
3873 p->nColumn = nCol;
3874 p->nKeyCol = nCol - 1;
3875 *ppExtra = ((char*)p) + nByte;
3877 return p;
3881 ** If expression list pList contains an expression that was parsed with
3882 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3883 ** pParse and return non-zero. Otherwise, return zero.
3885 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
3886 if( pList ){
3887 int i;
3888 for(i=0; i<pList->nExpr; i++){
3889 if( pList->a[i].fg.bNulls ){
3890 u8 sf = pList->a[i].fg.sortFlags;
3891 sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
3892 (sf==0 || sf==3) ? "FIRST" : "LAST"
3894 return 1;
3898 return 0;
3902 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
3903 ** and pTblList is the name of the table that is to be indexed. Both will
3904 ** be NULL for a primary key or an index that is created to satisfy a
3905 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
3906 ** as the table to be indexed. pParse->pNewTable is a table that is
3907 ** currently being constructed by a CREATE TABLE statement.
3909 ** pList is a list of columns to be indexed. pList will be NULL if this
3910 ** is a primary key or unique-constraint on the most recent column added
3911 ** to the table currently under construction.
3913 void sqlite3CreateIndex(
3914 Parse *pParse, /* All information about this parse */
3915 Token *pName1, /* First part of index name. May be NULL */
3916 Token *pName2, /* Second part of index name. May be NULL */
3917 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
3918 ExprList *pList, /* A list of columns to be indexed */
3919 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3920 Token *pStart, /* The CREATE token that begins this statement */
3921 Expr *pPIWhere, /* WHERE clause for partial indices */
3922 int sortOrder, /* Sort order of primary key when pList==NULL */
3923 int ifNotExist, /* Omit error if index already exists */
3924 u8 idxType /* The index type */
3926 Table *pTab = 0; /* Table to be indexed */
3927 Index *pIndex = 0; /* The index to be created */
3928 char *zName = 0; /* Name of the index */
3929 int nName; /* Number of characters in zName */
3930 int i, j;
3931 DbFixer sFix; /* For assigning database names to pTable */
3932 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
3933 sqlite3 *db = pParse->db;
3934 Db *pDb; /* The specific table containing the indexed database */
3935 int iDb; /* Index of the database that is being written */
3936 Token *pName = 0; /* Unqualified name of the index to create */
3937 struct ExprList_item *pListItem; /* For looping over pList */
3938 int nExtra = 0; /* Space allocated for zExtra[] */
3939 int nExtraCol; /* Number of extra columns needed */
3940 char *zExtra = 0; /* Extra space after the Index object */
3941 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
3943 assert( db->pParse==pParse );
3944 if( pParse->nErr ){
3945 goto exit_create_index;
3947 assert( db->mallocFailed==0 );
3948 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
3949 goto exit_create_index;
3951 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3952 goto exit_create_index;
3954 if( sqlite3HasExplicitNulls(pParse, pList) ){
3955 goto exit_create_index;
3959 ** Find the table that is to be indexed. Return early if not found.
3961 if( pTblName!=0 ){
3963 /* Use the two-part index name to determine the database
3964 ** to search for the table. 'Fix' the table name to this db
3965 ** before looking up the table.
3967 assert( pName1 && pName2 );
3968 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3969 if( iDb<0 ) goto exit_create_index;
3970 assert( pName && pName->z );
3972 #ifndef SQLITE_OMIT_TEMPDB
3973 /* If the index name was unqualified, check if the table
3974 ** is a temp table. If so, set the database to 1. Do not do this
3975 ** if initialising a database schema.
3977 if( !db->init.busy ){
3978 pTab = sqlite3SrcListLookup(pParse, pTblName);
3979 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
3980 iDb = 1;
3983 #endif
3985 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
3986 if( sqlite3FixSrcList(&sFix, pTblName) ){
3987 /* Because the parser constructs pTblName from a single identifier,
3988 ** sqlite3FixSrcList can never fail. */
3989 assert(0);
3991 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
3992 assert( db->mallocFailed==0 || pTab==0 );
3993 if( pTab==0 ) goto exit_create_index;
3994 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
3995 sqlite3ErrorMsg(pParse,
3996 "cannot create a TEMP index on non-TEMP table \"%s\"",
3997 pTab->zName);
3998 goto exit_create_index;
4000 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
4001 }else{
4002 assert( pName==0 );
4003 assert( pStart==0 );
4004 pTab = pParse->pNewTable;
4005 if( !pTab ) goto exit_create_index;
4006 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4008 pDb = &db->aDb[iDb];
4010 assert( pTab!=0 );
4011 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
4012 && db->init.busy==0
4013 && pTblName!=0
4014 #if SQLITE_USER_AUTHENTICATION
4015 && sqlite3UserAuthTable(pTab->zName)==0
4016 #endif
4018 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
4019 goto exit_create_index;
4021 #ifndef SQLITE_OMIT_VIEW
4022 if( IsView(pTab) ){
4023 sqlite3ErrorMsg(pParse, "views may not be indexed");
4024 goto exit_create_index;
4026 #endif
4027 #ifndef SQLITE_OMIT_VIRTUALTABLE
4028 if( IsVirtual(pTab) ){
4029 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
4030 goto exit_create_index;
4032 #endif
4035 ** Find the name of the index. Make sure there is not already another
4036 ** index or table with the same name.
4038 ** Exception: If we are reading the names of permanent indices from the
4039 ** sqlite_schema table (because some other process changed the schema) and
4040 ** one of the index names collides with the name of a temporary table or
4041 ** index, then we will continue to process this index.
4043 ** If pName==0 it means that we are
4044 ** dealing with a primary key or UNIQUE constraint. We have to invent our
4045 ** own name.
4047 if( pName ){
4048 zName = sqlite3NameFromToken(db, pName);
4049 if( zName==0 ) goto exit_create_index;
4050 assert( pName->z!=0 );
4051 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
4052 goto exit_create_index;
4054 if( !IN_RENAME_OBJECT ){
4055 if( !db->init.busy ){
4056 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
4057 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
4058 goto exit_create_index;
4061 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
4062 if( !ifNotExist ){
4063 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
4064 }else{
4065 assert( !db->init.busy );
4066 sqlite3CodeVerifySchema(pParse, iDb);
4067 sqlite3ForceNotReadOnly(pParse);
4069 goto exit_create_index;
4072 }else{
4073 int n;
4074 Index *pLoop;
4075 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
4076 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
4077 if( zName==0 ){
4078 goto exit_create_index;
4081 /* Automatic index names generated from within sqlite3_declare_vtab()
4082 ** must have names that are distinct from normal automatic index names.
4083 ** The following statement converts "sqlite3_autoindex..." into
4084 ** "sqlite3_butoindex..." in order to make the names distinct.
4085 ** The "vtab_err.test" test demonstrates the need of this statement. */
4086 if( IN_SPECIAL_PARSE ) zName[7]++;
4089 /* Check for authorization to create an index.
4091 #ifndef SQLITE_OMIT_AUTHORIZATION
4092 if( !IN_RENAME_OBJECT ){
4093 const char *zDb = pDb->zDbSName;
4094 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
4095 goto exit_create_index;
4097 i = SQLITE_CREATE_INDEX;
4098 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
4099 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
4100 goto exit_create_index;
4103 #endif
4105 /* If pList==0, it means this routine was called to make a primary
4106 ** key out of the last column added to the table under construction.
4107 ** So create a fake list to simulate this.
4109 if( pList==0 ){
4110 Token prevCol;
4111 Column *pCol = &pTab->aCol[pTab->nCol-1];
4112 pCol->colFlags |= COLFLAG_UNIQUE;
4113 sqlite3TokenInit(&prevCol, pCol->zCnName);
4114 pList = sqlite3ExprListAppend(pParse, 0,
4115 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
4116 if( pList==0 ) goto exit_create_index;
4117 assert( pList->nExpr==1 );
4118 sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
4119 }else{
4120 sqlite3ExprListCheckLength(pParse, pList, "index");
4121 if( pParse->nErr ) goto exit_create_index;
4124 /* Figure out how many bytes of space are required to store explicitly
4125 ** specified collation sequence names.
4127 for(i=0; i<pList->nExpr; i++){
4128 Expr *pExpr = pList->a[i].pExpr;
4129 assert( pExpr!=0 );
4130 if( pExpr->op==TK_COLLATE ){
4131 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4132 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
4137 ** Allocate the index structure.
4139 nName = sqlite3Strlen30(zName);
4140 nExtraCol = pPk ? pPk->nKeyCol : 1;
4141 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
4142 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
4143 nName + nExtra + 1, &zExtra);
4144 if( db->mallocFailed ){
4145 goto exit_create_index;
4147 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
4148 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
4149 pIndex->zName = zExtra;
4150 zExtra += nName + 1;
4151 memcpy(pIndex->zName, zName, nName+1);
4152 pIndex->pTable = pTab;
4153 pIndex->onError = (u8)onError;
4154 pIndex->uniqNotNull = onError!=OE_None;
4155 pIndex->idxType = idxType;
4156 pIndex->pSchema = db->aDb[iDb].pSchema;
4157 pIndex->nKeyCol = pList->nExpr;
4158 if( pPIWhere ){
4159 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
4160 pIndex->pPartIdxWhere = pPIWhere;
4161 pPIWhere = 0;
4163 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4165 /* Check to see if we should honor DESC requests on index columns
4167 if( pDb->pSchema->file_format>=4 ){
4168 sortOrderMask = -1; /* Honor DESC */
4169 }else{
4170 sortOrderMask = 0; /* Ignore DESC */
4173 /* Analyze the list of expressions that form the terms of the index and
4174 ** report any errors. In the common case where the expression is exactly
4175 ** a table column, store that column in aiColumn[]. For general expressions,
4176 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4178 ** TODO: Issue a warning if two or more columns of the index are identical.
4179 ** TODO: Issue a warning if the table primary key is used as part of the
4180 ** index key.
4182 pListItem = pList->a;
4183 if( IN_RENAME_OBJECT ){
4184 pIndex->aColExpr = pList;
4185 pList = 0;
4187 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
4188 Expr *pCExpr; /* The i-th index expression */
4189 int requestedSortOrder; /* ASC or DESC on the i-th expression */
4190 const char *zColl; /* Collation sequence name */
4192 sqlite3StringToId(pListItem->pExpr);
4193 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
4194 if( pParse->nErr ) goto exit_create_index;
4195 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
4196 if( pCExpr->op!=TK_COLUMN ){
4197 if( pTab==pParse->pNewTable ){
4198 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
4199 "UNIQUE constraints");
4200 goto exit_create_index;
4202 if( pIndex->aColExpr==0 ){
4203 pIndex->aColExpr = pList;
4204 pList = 0;
4206 j = XN_EXPR;
4207 pIndex->aiColumn[i] = XN_EXPR;
4208 pIndex->uniqNotNull = 0;
4209 pIndex->bHasExpr = 1;
4210 }else{
4211 j = pCExpr->iColumn;
4212 assert( j<=0x7fff );
4213 if( j<0 ){
4214 j = pTab->iPKey;
4215 }else{
4216 if( pTab->aCol[j].notNull==0 ){
4217 pIndex->uniqNotNull = 0;
4219 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
4220 pIndex->bHasVCol = 1;
4221 pIndex->bHasExpr = 1;
4224 pIndex->aiColumn[i] = (i16)j;
4226 zColl = 0;
4227 if( pListItem->pExpr->op==TK_COLLATE ){
4228 int nColl;
4229 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
4230 zColl = pListItem->pExpr->u.zToken;
4231 nColl = sqlite3Strlen30(zColl) + 1;
4232 assert( nExtra>=nColl );
4233 memcpy(zExtra, zColl, nColl);
4234 zColl = zExtra;
4235 zExtra += nColl;
4236 nExtra -= nColl;
4237 }else if( j>=0 ){
4238 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
4240 if( !zColl ) zColl = sqlite3StrBINARY;
4241 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
4242 goto exit_create_index;
4244 pIndex->azColl[i] = zColl;
4245 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
4246 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
4249 /* Append the table key to the end of the index. For WITHOUT ROWID
4250 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
4251 ** normal tables (when pPk==0) this will be the rowid.
4253 if( pPk ){
4254 for(j=0; j<pPk->nKeyCol; j++){
4255 int x = pPk->aiColumn[j];
4256 assert( x>=0 );
4257 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
4258 pIndex->nColumn--;
4259 }else{
4260 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
4261 pIndex->aiColumn[i] = x;
4262 pIndex->azColl[i] = pPk->azColl[j];
4263 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
4264 i++;
4267 assert( i==pIndex->nColumn );
4268 }else{
4269 pIndex->aiColumn[i] = XN_ROWID;
4270 pIndex->azColl[i] = sqlite3StrBINARY;
4272 sqlite3DefaultRowEst(pIndex);
4273 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
4275 /* If this index contains every column of its table, then mark
4276 ** it as a covering index */
4277 assert( HasRowid(pTab)
4278 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
4279 recomputeColumnsNotIndexed(pIndex);
4280 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
4281 pIndex->isCovering = 1;
4282 for(j=0; j<pTab->nCol; j++){
4283 if( j==pTab->iPKey ) continue;
4284 if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
4285 pIndex->isCovering = 0;
4286 break;
4290 if( pTab==pParse->pNewTable ){
4291 /* This routine has been called to create an automatic index as a
4292 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4293 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4294 ** i.e. one of:
4296 ** CREATE TABLE t(x PRIMARY KEY, y);
4297 ** CREATE TABLE t(x, y, UNIQUE(x, y));
4299 ** Either way, check to see if the table already has such an index. If
4300 ** so, don't bother creating this one. This only applies to
4301 ** automatically created indices. Users can do as they wish with
4302 ** explicit indices.
4304 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4305 ** (and thus suppressing the second one) even if they have different
4306 ** sort orders.
4308 ** If there are different collating sequences or if the columns of
4309 ** the constraint occur in different orders, then the constraints are
4310 ** considered distinct and both result in separate indices.
4312 Index *pIdx;
4313 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4314 int k;
4315 assert( IsUniqueIndex(pIdx) );
4316 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
4317 assert( IsUniqueIndex(pIndex) );
4319 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
4320 for(k=0; k<pIdx->nKeyCol; k++){
4321 const char *z1;
4322 const char *z2;
4323 assert( pIdx->aiColumn[k]>=0 );
4324 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
4325 z1 = pIdx->azColl[k];
4326 z2 = pIndex->azColl[k];
4327 if( sqlite3StrICmp(z1, z2) ) break;
4329 if( k==pIdx->nKeyCol ){
4330 if( pIdx->onError!=pIndex->onError ){
4331 /* This constraint creates the same index as a previous
4332 ** constraint specified somewhere in the CREATE TABLE statement.
4333 ** However the ON CONFLICT clauses are different. If both this
4334 ** constraint and the previous equivalent constraint have explicit
4335 ** ON CONFLICT clauses this is an error. Otherwise, use the
4336 ** explicitly specified behavior for the index.
4338 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
4339 sqlite3ErrorMsg(pParse,
4340 "conflicting ON CONFLICT clauses specified", 0);
4342 if( pIdx->onError==OE_Default ){
4343 pIdx->onError = pIndex->onError;
4346 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
4347 if( IN_RENAME_OBJECT ){
4348 pIndex->pNext = pParse->pNewIndex;
4349 pParse->pNewIndex = pIndex;
4350 pIndex = 0;
4352 goto exit_create_index;
4357 if( !IN_RENAME_OBJECT ){
4359 /* Link the new Index structure to its table and to the other
4360 ** in-memory database structures.
4362 assert( pParse->nErr==0 );
4363 if( db->init.busy ){
4364 Index *p;
4365 assert( !IN_SPECIAL_PARSE );
4366 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
4367 if( pTblName!=0 ){
4368 pIndex->tnum = db->init.newTnum;
4369 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
4370 sqlite3ErrorMsg(pParse, "invalid rootpage");
4371 pParse->rc = SQLITE_CORRUPT_BKPT;
4372 goto exit_create_index;
4375 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
4376 pIndex->zName, pIndex);
4377 if( p ){
4378 assert( p==pIndex ); /* Malloc must have failed */
4379 sqlite3OomFault(db);
4380 goto exit_create_index;
4382 db->mDbFlags |= DBFLAG_SchemaChange;
4385 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4386 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4387 ** emit code to allocate the index rootpage on disk and make an entry for
4388 ** the index in the sqlite_schema table and populate the index with
4389 ** content. But, do not do this if we are simply reading the sqlite_schema
4390 ** table to parse the schema, or if this index is the PRIMARY KEY index
4391 ** of a WITHOUT ROWID table.
4393 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4394 ** or UNIQUE index in a CREATE TABLE statement. Since the table
4395 ** has just been created, it contains no data and the index initialization
4396 ** step can be skipped.
4398 else if( HasRowid(pTab) || pTblName!=0 ){
4399 Vdbe *v;
4400 char *zStmt;
4401 int iMem = ++pParse->nMem;
4403 v = sqlite3GetVdbe(pParse);
4404 if( v==0 ) goto exit_create_index;
4406 sqlite3BeginWriteOperation(pParse, 1, iDb);
4408 /* Create the rootpage for the index using CreateIndex. But before
4409 ** doing so, code a Noop instruction and store its address in
4410 ** Index.tnum. This is required in case this index is actually a
4411 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4412 ** that case the convertToWithoutRowidTable() routine will replace
4413 ** the Noop with a Goto to jump over the VDBE code generated below. */
4414 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
4415 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
4417 /* Gather the complete text of the CREATE INDEX statement into
4418 ** the zStmt variable
4420 assert( pName!=0 || pStart==0 );
4421 if( pStart ){
4422 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
4423 if( pName->z[n-1]==';' ) n--;
4424 /* A named index with an explicit CREATE INDEX statement */
4425 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
4426 onError==OE_None ? "" : " UNIQUE", n, pName->z);
4427 }else{
4428 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4429 /* zStmt = sqlite3MPrintf(""); */
4430 zStmt = 0;
4433 /* Add an entry in sqlite_schema for this index
4435 sqlite3NestedParse(pParse,
4436 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
4437 db->aDb[iDb].zDbSName,
4438 pIndex->zName,
4439 pTab->zName,
4440 iMem,
4441 zStmt
4443 sqlite3DbFree(db, zStmt);
4445 /* Fill the index with data and reparse the schema. Code an OP_Expire
4446 ** to invalidate all pre-compiled statements.
4448 if( pTblName ){
4449 sqlite3RefillIndex(pParse, pIndex, iMem);
4450 sqlite3ChangeCookie(pParse, iDb);
4451 sqlite3VdbeAddParseSchemaOp(v, iDb,
4452 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
4453 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
4456 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
4459 if( db->init.busy || pTblName==0 ){
4460 pIndex->pNext = pTab->pIndex;
4461 pTab->pIndex = pIndex;
4462 pIndex = 0;
4464 else if( IN_RENAME_OBJECT ){
4465 assert( pParse->pNewIndex==0 );
4466 pParse->pNewIndex = pIndex;
4467 pIndex = 0;
4470 /* Clean up before exiting */
4471 exit_create_index:
4472 if( pIndex ) sqlite3FreeIndex(db, pIndex);
4473 if( pTab ){
4474 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
4475 ** The list was already ordered when this routine was entered, so at this
4476 ** point at most a single index (the newly added index) will be out of
4477 ** order. So we have to reorder at most one index. */
4478 Index **ppFrom;
4479 Index *pThis;
4480 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
4481 Index *pNext;
4482 if( pThis->onError!=OE_Replace ) continue;
4483 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4484 *ppFrom = pNext;
4485 pThis->pNext = pNext->pNext;
4486 pNext->pNext = pThis;
4487 ppFrom = &pNext->pNext;
4489 break;
4491 #ifdef SQLITE_DEBUG
4492 /* Verify that all REPLACE indexes really are now at the end
4493 ** of the index list. In other words, no other index type ever
4494 ** comes after a REPLACE index on the list. */
4495 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
4496 assert( pThis->onError!=OE_Replace
4497 || pThis->pNext==0
4498 || pThis->pNext->onError==OE_Replace );
4500 #endif
4502 sqlite3ExprDelete(db, pPIWhere);
4503 sqlite3ExprListDelete(db, pList);
4504 sqlite3SrcListDelete(db, pTblName);
4505 sqlite3DbFree(db, zName);
4509 ** Fill the Index.aiRowEst[] array with default information - information
4510 ** to be used when we have not run the ANALYZE command.
4512 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4513 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
4514 ** number of rows in the table that match any particular value of the
4515 ** first column of the index. aiRowEst[2] is an estimate of the number
4516 ** of rows that match any particular combination of the first 2 columns
4517 ** of the index. And so forth. It must always be the case that
4519 ** aiRowEst[N]<=aiRowEst[N-1]
4520 ** aiRowEst[N]>=1
4522 ** Apart from that, we have little to go on besides intuition as to
4523 ** how aiRowEst[] should be initialized. The numbers generated here
4524 ** are based on typical values found in actual indices.
4526 void sqlite3DefaultRowEst(Index *pIdx){
4527 /* 10, 9, 8, 7, 6 */
4528 static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
4529 LogEst *a = pIdx->aiRowLogEst;
4530 LogEst x;
4531 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
4532 int i;
4534 /* Indexes with default row estimates should not have stat1 data */
4535 assert( !pIdx->hasStat1 );
4537 /* Set the first entry (number of rows in the index) to the estimated
4538 ** number of rows in the table, or half the number of rows in the table
4539 ** for a partial index.
4541 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
4542 ** table but other parts we are having to guess at, then do not let the
4543 ** estimated number of rows in the table be less than 1000 (LogEst 99).
4544 ** Failure to do this can cause the indexes for which we do not have
4545 ** stat1 data to be ignored by the query planner.
4547 x = pIdx->pTable->nRowLogEst;
4548 assert( 99==sqlite3LogEst(1000) );
4549 if( x<99 ){
4550 pIdx->pTable->nRowLogEst = x = 99;
4552 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
4553 a[0] = x;
4555 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4556 ** 6 and each subsequent value (if any) is 5. */
4557 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4558 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4559 a[i] = 23; assert( 23==sqlite3LogEst(5) );
4562 assert( 0==sqlite3LogEst(1) );
4563 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
4567 ** This routine will drop an existing named index. This routine
4568 ** implements the DROP INDEX statement.
4570 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
4571 Index *pIndex;
4572 Vdbe *v;
4573 sqlite3 *db = pParse->db;
4574 int iDb;
4576 if( db->mallocFailed ){
4577 goto exit_drop_index;
4579 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
4580 assert( pName->nSrc==1 );
4581 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4582 goto exit_drop_index;
4584 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
4585 if( pIndex==0 ){
4586 if( !ifExists ){
4587 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
4588 }else{
4589 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
4590 sqlite3ForceNotReadOnly(pParse);
4592 pParse->checkSchema = 1;
4593 goto exit_drop_index;
4595 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
4596 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4597 "or PRIMARY KEY constraint cannot be dropped", 0);
4598 goto exit_drop_index;
4600 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4601 #ifndef SQLITE_OMIT_AUTHORIZATION
4603 int code = SQLITE_DROP_INDEX;
4604 Table *pTab = pIndex->pTable;
4605 const char *zDb = db->aDb[iDb].zDbSName;
4606 const char *zTab = SCHEMA_TABLE(iDb);
4607 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4608 goto exit_drop_index;
4610 if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
4611 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4612 goto exit_drop_index;
4615 #endif
4617 /* Generate code to remove the index and from the schema table */
4618 v = sqlite3GetVdbe(pParse);
4619 if( v ){
4620 sqlite3BeginWriteOperation(pParse, 1, iDb);
4621 sqlite3NestedParse(pParse,
4622 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
4623 db->aDb[iDb].zDbSName, pIndex->zName
4625 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
4626 sqlite3ChangeCookie(pParse, iDb);
4627 destroyRootPage(pParse, pIndex->tnum, iDb);
4628 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
4631 exit_drop_index:
4632 sqlite3SrcListDelete(db, pName);
4636 ** pArray is a pointer to an array of objects. Each object in the
4637 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4638 ** to extend the array so that there is space for a new object at the end.
4640 ** When this function is called, *pnEntry contains the current size of
4641 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4642 ** in total).
4644 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4645 ** space allocated for the new object is zeroed, *pnEntry updated to
4646 ** reflect the new size of the array and a pointer to the new allocation
4647 ** returned. *pIdx is set to the index of the new array entry in this case.
4649 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4650 ** unchanged and a copy of pArray returned.
4652 void *sqlite3ArrayAllocate(
4653 sqlite3 *db, /* Connection to notify of malloc failures */
4654 void *pArray, /* Array of objects. Might be reallocated */
4655 int szEntry, /* Size of each object in the array */
4656 int *pnEntry, /* Number of objects currently in use */
4657 int *pIdx /* Write the index of a new slot here */
4659 char *z;
4660 sqlite3_int64 n = *pIdx = *pnEntry;
4661 if( (n & (n-1))==0 ){
4662 sqlite3_int64 sz = (n==0) ? 1 : 2*n;
4663 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
4664 if( pNew==0 ){
4665 *pIdx = -1;
4666 return pArray;
4668 pArray = pNew;
4670 z = (char*)pArray;
4671 memset(&z[n * szEntry], 0, szEntry);
4672 ++*pnEntry;
4673 return pArray;
4677 ** Append a new element to the given IdList. Create a new IdList if
4678 ** need be.
4680 ** A new IdList is returned, or NULL if malloc() fails.
4682 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
4683 sqlite3 *db = pParse->db;
4684 int i;
4685 if( pList==0 ){
4686 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
4687 if( pList==0 ) return 0;
4688 }else{
4689 IdList *pNew;
4690 pNew = sqlite3DbRealloc(db, pList,
4691 sizeof(IdList) + pList->nId*sizeof(pList->a));
4692 if( pNew==0 ){
4693 sqlite3IdListDelete(db, pList);
4694 return 0;
4696 pList = pNew;
4698 i = pList->nId++;
4699 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4700 if( IN_RENAME_OBJECT && pList->a[i].zName ){
4701 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
4703 return pList;
4707 ** Delete an IdList.
4709 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4710 int i;
4711 assert( db!=0 );
4712 if( pList==0 ) return;
4713 assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */
4714 for(i=0; i<pList->nId; i++){
4715 sqlite3DbFree(db, pList->a[i].zName);
4717 sqlite3DbNNFreeNN(db, pList);
4721 ** Return the index in pList of the identifier named zId. Return -1
4722 ** if not found.
4724 int sqlite3IdListIndex(IdList *pList, const char *zName){
4725 int i;
4726 assert( pList!=0 );
4727 for(i=0; i<pList->nId; i++){
4728 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4730 return -1;
4734 ** Maximum size of a SrcList object.
4735 ** The SrcList object is used to represent the FROM clause of a
4736 ** SELECT statement, and the query planner cannot deal with more
4737 ** than 64 tables in a join. So any value larger than 64 here
4738 ** is sufficient for most uses. Smaller values, like say 10, are
4739 ** appropriate for small and memory-limited applications.
4741 #ifndef SQLITE_MAX_SRCLIST
4742 # define SQLITE_MAX_SRCLIST 200
4743 #endif
4746 ** Expand the space allocated for the given SrcList object by
4747 ** creating nExtra new slots beginning at iStart. iStart is zero based.
4748 ** New slots are zeroed.
4750 ** For example, suppose a SrcList initially contains two entries: A,B.
4751 ** To append 3 new entries onto the end, do this:
4753 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4755 ** After the call above it would contain: A, B, nil, nil, nil.
4756 ** If the iStart argument had been 1 instead of 2, then the result
4757 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
4758 ** the iStart value would be 0. The result then would
4759 ** be: nil, nil, nil, A, B.
4761 ** If a memory allocation fails or the SrcList becomes too large, leave
4762 ** the original SrcList unchanged, return NULL, and leave an error message
4763 ** in pParse.
4765 SrcList *sqlite3SrcListEnlarge(
4766 Parse *pParse, /* Parsing context into which errors are reported */
4767 SrcList *pSrc, /* The SrcList to be enlarged */
4768 int nExtra, /* Number of new slots to add to pSrc->a[] */
4769 int iStart /* Index in pSrc->a[] of first new slot */
4771 int i;
4773 /* Sanity checking on calling parameters */
4774 assert( iStart>=0 );
4775 assert( nExtra>=1 );
4776 assert( pSrc!=0 );
4777 assert( iStart<=pSrc->nSrc );
4779 /* Allocate additional space if needed */
4780 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4781 SrcList *pNew;
4782 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4783 sqlite3 *db = pParse->db;
4785 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4786 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4787 SQLITE_MAX_SRCLIST);
4788 return 0;
4790 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4791 pNew = sqlite3DbRealloc(db, pSrc,
4792 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
4793 if( pNew==0 ){
4794 assert( db->mallocFailed );
4795 return 0;
4797 pSrc = pNew;
4798 pSrc->nAlloc = nAlloc;
4801 /* Move existing slots that come after the newly inserted slots
4802 ** out of the way */
4803 for(i=pSrc->nSrc-1; i>=iStart; i--){
4804 pSrc->a[i+nExtra] = pSrc->a[i];
4806 pSrc->nSrc += nExtra;
4808 /* Zero the newly allocated slots */
4809 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4810 for(i=iStart; i<iStart+nExtra; i++){
4811 pSrc->a[i].iCursor = -1;
4814 /* Return a pointer to the enlarged SrcList */
4815 return pSrc;
4820 ** Append a new table name to the given SrcList. Create a new SrcList if
4821 ** need be. A new entry is created in the SrcList even if pTable is NULL.
4823 ** A SrcList is returned, or NULL if there is an OOM error or if the
4824 ** SrcList grows to large. The returned
4825 ** SrcList might be the same as the SrcList that was input or it might be
4826 ** a new one. If an OOM error does occurs, then the prior value of pList
4827 ** that is input to this routine is automatically freed.
4829 ** If pDatabase is not null, it means that the table has an optional
4830 ** database name prefix. Like this: "database.table". The pDatabase
4831 ** points to the table name and the pTable points to the database name.
4832 ** The SrcList.a[].zName field is filled with the table name which might
4833 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4834 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4835 ** or with NULL if no database is specified.
4837 ** In other words, if call like this:
4839 ** sqlite3SrcListAppend(D,A,B,0);
4841 ** Then B is a table name and the database name is unspecified. If called
4842 ** like this:
4844 ** sqlite3SrcListAppend(D,A,B,C);
4846 ** Then C is the table name and B is the database name. If C is defined
4847 ** then so is B. In other words, we never have a case where:
4849 ** sqlite3SrcListAppend(D,A,0,C);
4851 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
4852 ** before being added to the SrcList.
4854 SrcList *sqlite3SrcListAppend(
4855 Parse *pParse, /* Parsing context, in which errors are reported */
4856 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
4857 Token *pTable, /* Table to append */
4858 Token *pDatabase /* Database of the table */
4860 SrcItem *pItem;
4861 sqlite3 *db;
4862 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
4863 assert( pParse!=0 );
4864 assert( pParse->db!=0 );
4865 db = pParse->db;
4866 if( pList==0 ){
4867 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
4868 if( pList==0 ) return 0;
4869 pList->nAlloc = 1;
4870 pList->nSrc = 1;
4871 memset(&pList->a[0], 0, sizeof(pList->a[0]));
4872 pList->a[0].iCursor = -1;
4873 }else{
4874 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
4875 if( pNew==0 ){
4876 sqlite3SrcListDelete(db, pList);
4877 return 0;
4878 }else{
4879 pList = pNew;
4882 pItem = &pList->a[pList->nSrc-1];
4883 if( pDatabase && pDatabase->z==0 ){
4884 pDatabase = 0;
4886 if( pDatabase ){
4887 pItem->zName = sqlite3NameFromToken(db, pDatabase);
4888 pItem->zDatabase = sqlite3NameFromToken(db, pTable);
4889 }else{
4890 pItem->zName = sqlite3NameFromToken(db, pTable);
4891 pItem->zDatabase = 0;
4893 return pList;
4897 ** Assign VdbeCursor index numbers to all tables in a SrcList
4899 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
4900 int i;
4901 SrcItem *pItem;
4902 assert( pList || pParse->db->mallocFailed );
4903 if( ALWAYS(pList) ){
4904 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
4905 if( pItem->iCursor>=0 ) continue;
4906 pItem->iCursor = pParse->nTab++;
4907 if( pItem->pSelect ){
4908 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
4915 ** Delete an entire SrcList including all its substructure.
4917 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
4918 int i;
4919 SrcItem *pItem;
4920 assert( db!=0 );
4921 if( pList==0 ) return;
4922 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
4923 if( pItem->zDatabase ) sqlite3DbNNFreeNN(db, pItem->zDatabase);
4924 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
4925 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
4926 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
4927 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
4928 sqlite3DeleteTable(db, pItem->pTab);
4929 if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
4930 if( pItem->fg.isUsing ){
4931 sqlite3IdListDelete(db, pItem->u3.pUsing);
4932 }else if( pItem->u3.pOn ){
4933 sqlite3ExprDelete(db, pItem->u3.pOn);
4936 sqlite3DbNNFreeNN(db, pList);
4940 ** This routine is called by the parser to add a new term to the
4941 ** end of a growing FROM clause. The "p" parameter is the part of
4942 ** the FROM clause that has already been constructed. "p" is NULL
4943 ** if this is the first term of the FROM clause. pTable and pDatabase
4944 ** are the name of the table and database named in the FROM clause term.
4945 ** pDatabase is NULL if the database name qualifier is missing - the
4946 ** usual case. If the term has an alias, then pAlias points to the
4947 ** alias token. If the term is a subquery, then pSubquery is the
4948 ** SELECT statement that the subquery encodes. The pTable and
4949 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
4950 ** parameters are the content of the ON and USING clauses.
4952 ** Return a new SrcList which encodes is the FROM with the new
4953 ** term added.
4955 SrcList *sqlite3SrcListAppendFromTerm(
4956 Parse *pParse, /* Parsing context */
4957 SrcList *p, /* The left part of the FROM clause already seen */
4958 Token *pTable, /* Name of the table to add to the FROM clause */
4959 Token *pDatabase, /* Name of the database containing pTable */
4960 Token *pAlias, /* The right-hand side of the AS subexpression */
4961 Select *pSubquery, /* A subquery used in place of a table name */
4962 OnOrUsing *pOnUsing /* Either the ON clause or the USING clause */
4964 SrcItem *pItem;
4965 sqlite3 *db = pParse->db;
4966 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
4967 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
4968 (pOnUsing->pOn ? "ON" : "USING")
4970 goto append_from_error;
4972 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
4973 if( p==0 ){
4974 goto append_from_error;
4976 assert( p->nSrc>0 );
4977 pItem = &p->a[p->nSrc-1];
4978 assert( (pTable==0)==(pDatabase==0) );
4979 assert( pItem->zName==0 || pDatabase!=0 );
4980 if( IN_RENAME_OBJECT && pItem->zName ){
4981 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
4982 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
4984 assert( pAlias!=0 );
4985 if( pAlias->n ){
4986 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
4988 if( pSubquery ){
4989 pItem->pSelect = pSubquery;
4990 if( pSubquery->selFlags & SF_NestedFrom ){
4991 pItem->fg.isNestedFrom = 1;
4994 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
4995 assert( pItem->fg.isUsing==0 );
4996 if( pOnUsing==0 ){
4997 pItem->u3.pOn = 0;
4998 }else if( pOnUsing->pUsing ){
4999 pItem->fg.isUsing = 1;
5000 pItem->u3.pUsing = pOnUsing->pUsing;
5001 }else{
5002 pItem->u3.pOn = pOnUsing->pOn;
5004 return p;
5006 append_from_error:
5007 assert( p==0 );
5008 sqlite3ClearOnOrUsing(db, pOnUsing);
5009 sqlite3SelectDelete(db, pSubquery);
5010 return 0;
5014 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5015 ** element of the source-list passed as the second argument.
5017 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
5018 assert( pIndexedBy!=0 );
5019 if( p && pIndexedBy->n>0 ){
5020 SrcItem *pItem;
5021 assert( p->nSrc>0 );
5022 pItem = &p->a[p->nSrc-1];
5023 assert( pItem->fg.notIndexed==0 );
5024 assert( pItem->fg.isIndexedBy==0 );
5025 assert( pItem->fg.isTabFunc==0 );
5026 if( pIndexedBy->n==1 && !pIndexedBy->z ){
5027 /* A "NOT INDEXED" clause was supplied. See parse.y
5028 ** construct "indexed_opt" for details. */
5029 pItem->fg.notIndexed = 1;
5030 }else{
5031 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
5032 pItem->fg.isIndexedBy = 1;
5033 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
5039 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
5040 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
5041 ** are deleted by this function.
5043 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
5044 assert( p1 && p1->nSrc==1 );
5045 if( p2 ){
5046 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
5047 if( pNew==0 ){
5048 sqlite3SrcListDelete(pParse->db, p2);
5049 }else{
5050 p1 = pNew;
5051 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
5052 sqlite3DbFree(pParse->db, p2);
5053 p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
5056 return p1;
5060 ** Add the list of function arguments to the SrcList entry for a
5061 ** table-valued-function.
5063 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
5064 if( p ){
5065 SrcItem *pItem = &p->a[p->nSrc-1];
5066 assert( pItem->fg.notIndexed==0 );
5067 assert( pItem->fg.isIndexedBy==0 );
5068 assert( pItem->fg.isTabFunc==0 );
5069 pItem->u1.pFuncArg = pList;
5070 pItem->fg.isTabFunc = 1;
5071 }else{
5072 sqlite3ExprListDelete(pParse->db, pList);
5077 ** When building up a FROM clause in the parser, the join operator
5078 ** is initially attached to the left operand. But the code generator
5079 ** expects the join operator to be on the right operand. This routine
5080 ** Shifts all join operators from left to right for an entire FROM
5081 ** clause.
5083 ** Example: Suppose the join is like this:
5085 ** A natural cross join B
5087 ** The operator is "natural cross join". The A and B operands are stored
5088 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
5089 ** operator with A. This routine shifts that operator over to B.
5091 ** Additional changes:
5093 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
5094 ** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
5095 ** code generator can easily tell that the table is part of
5096 ** the left operand of at least one RIGHT JOIN.
5098 void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
5099 (void)pParse;
5100 if( p && p->nSrc>1 ){
5101 int i = p->nSrc-1;
5102 u8 allFlags = 0;
5104 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
5105 }while( (--i)>0 );
5106 p->a[0].fg.jointype = 0;
5108 /* All terms to the left of a RIGHT JOIN should be tagged with the
5109 ** JT_LTORJ flags */
5110 if( allFlags & JT_RIGHT ){
5111 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
5112 i--;
5113 assert( i>=0 );
5115 p->a[i].fg.jointype |= JT_LTORJ;
5116 }while( (--i)>=0 );
5122 ** Generate VDBE code for a BEGIN statement.
5124 void sqlite3BeginTransaction(Parse *pParse, int type){
5125 sqlite3 *db;
5126 Vdbe *v;
5127 int i;
5129 assert( pParse!=0 );
5130 db = pParse->db;
5131 assert( db!=0 );
5132 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
5133 return;
5135 v = sqlite3GetVdbe(pParse);
5136 if( !v ) return;
5137 if( type!=TK_DEFERRED ){
5138 for(i=0; i<db->nDb; i++){
5139 int eTxnType;
5140 Btree *pBt = db->aDb[i].pBt;
5141 if( pBt && sqlite3BtreeIsReadonly(pBt) ){
5142 eTxnType = 0; /* Read txn */
5143 }else if( type==TK_EXCLUSIVE ){
5144 eTxnType = 2; /* Exclusive txn */
5145 }else{
5146 eTxnType = 1; /* Write txn */
5148 sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
5149 sqlite3VdbeUsesBtree(v, i);
5152 sqlite3VdbeAddOp0(v, OP_AutoCommit);
5156 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
5157 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
5158 ** code is generated for a COMMIT.
5160 void sqlite3EndTransaction(Parse *pParse, int eType){
5161 Vdbe *v;
5162 int isRollback;
5164 assert( pParse!=0 );
5165 assert( pParse->db!=0 );
5166 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
5167 isRollback = eType==TK_ROLLBACK;
5168 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
5169 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
5170 return;
5172 v = sqlite3GetVdbe(pParse);
5173 if( v ){
5174 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
5179 ** This function is called by the parser when it parses a command to create,
5180 ** release or rollback an SQL savepoint.
5182 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
5183 char *zName = sqlite3NameFromToken(pParse->db, pName);
5184 if( zName ){
5185 Vdbe *v = sqlite3GetVdbe(pParse);
5186 #ifndef SQLITE_OMIT_AUTHORIZATION
5187 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5188 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
5189 #endif
5190 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
5191 sqlite3DbFree(pParse->db, zName);
5192 return;
5194 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
5199 ** Make sure the TEMP database is open and available for use. Return
5200 ** the number of errors. Leave any error messages in the pParse structure.
5202 int sqlite3OpenTempDatabase(Parse *pParse){
5203 sqlite3 *db = pParse->db;
5204 if( db->aDb[1].pBt==0 && !pParse->explain ){
5205 int rc;
5206 Btree *pBt;
5207 static const int flags =
5208 SQLITE_OPEN_READWRITE |
5209 SQLITE_OPEN_CREATE |
5210 SQLITE_OPEN_EXCLUSIVE |
5211 SQLITE_OPEN_DELETEONCLOSE |
5212 SQLITE_OPEN_TEMP_DB;
5214 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
5215 if( rc!=SQLITE_OK ){
5216 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
5217 "file for storing temporary tables");
5218 pParse->rc = rc;
5219 return 1;
5221 db->aDb[1].pBt = pBt;
5222 assert( db->aDb[1].pSchema );
5223 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
5224 sqlite3OomFault(db);
5225 return 1;
5228 return 0;
5232 ** Record the fact that the schema cookie will need to be verified
5233 ** for database iDb. The code to actually verify the schema cookie
5234 ** will occur at the end of the top-level VDBE and will be generated
5235 ** later, by sqlite3FinishCoding().
5237 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
5238 assert( iDb>=0 && iDb<pToplevel->db->nDb );
5239 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
5240 assert( iDb<SQLITE_MAX_DB );
5241 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
5242 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
5243 DbMaskSet(pToplevel->cookieMask, iDb);
5244 if( !OMIT_TEMPDB && iDb==1 ){
5245 sqlite3OpenTempDatabase(pToplevel);
5249 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
5250 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
5255 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
5256 ** attached database. Otherwise, invoke it for the database named zDb only.
5258 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
5259 sqlite3 *db = pParse->db;
5260 int i;
5261 for(i=0; i<db->nDb; i++){
5262 Db *pDb = &db->aDb[i];
5263 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
5264 sqlite3CodeVerifySchema(pParse, i);
5270 ** Generate VDBE code that prepares for doing an operation that
5271 ** might change the database.
5273 ** This routine starts a new transaction if we are not already within
5274 ** a transaction. If we are already within a transaction, then a checkpoint
5275 ** is set if the setStatement parameter is true. A checkpoint should
5276 ** be set for operations that might fail (due to a constraint) part of
5277 ** the way through and which will need to undo some writes without having to
5278 ** rollback the whole transaction. For operations where all constraints
5279 ** can be checked before any changes are made to the database, it is never
5280 ** necessary to undo a write and the checkpoint should not be set.
5282 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
5283 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5284 sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
5285 DbMaskSet(pToplevel->writeMask, iDb);
5286 pToplevel->isMultiWrite |= setStatement;
5290 ** Indicate that the statement currently under construction might write
5291 ** more than one entry (example: deleting one row then inserting another,
5292 ** inserting multiple rows in a table, or inserting a row and index entries.)
5293 ** If an abort occurs after some of these writes have completed, then it will
5294 ** be necessary to undo the completed writes.
5296 void sqlite3MultiWrite(Parse *pParse){
5297 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5298 pToplevel->isMultiWrite = 1;
5302 ** The code generator calls this routine if is discovers that it is
5303 ** possible to abort a statement prior to completion. In order to
5304 ** perform this abort without corrupting the database, we need to make
5305 ** sure that the statement is protected by a statement transaction.
5307 ** Technically, we only need to set the mayAbort flag if the
5308 ** isMultiWrite flag was previously set. There is a time dependency
5309 ** such that the abort must occur after the multiwrite. This makes
5310 ** some statements involving the REPLACE conflict resolution algorithm
5311 ** go a little faster. But taking advantage of this time dependency
5312 ** makes it more difficult to prove that the code is correct (in
5313 ** particular, it prevents us from writing an effective
5314 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
5315 ** to take the safe route and skip the optimization.
5317 void sqlite3MayAbort(Parse *pParse){
5318 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5319 pToplevel->mayAbort = 1;
5323 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5324 ** error. The onError parameter determines which (if any) of the statement
5325 ** and/or current transaction is rolled back.
5327 void sqlite3HaltConstraint(
5328 Parse *pParse, /* Parsing context */
5329 int errCode, /* extended error code */
5330 int onError, /* Constraint type */
5331 char *p4, /* Error message */
5332 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
5333 u8 p5Errmsg /* P5_ErrMsg type */
5335 Vdbe *v;
5336 assert( pParse->pVdbe!=0 );
5337 v = sqlite3GetVdbe(pParse);
5338 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
5339 if( onError==OE_Abort ){
5340 sqlite3MayAbort(pParse);
5342 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
5343 sqlite3VdbeChangeP5(v, p5Errmsg);
5347 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5349 void sqlite3UniqueConstraint(
5350 Parse *pParse, /* Parsing context */
5351 int onError, /* Constraint type */
5352 Index *pIdx /* The index that triggers the constraint */
5354 char *zErr;
5355 int j;
5356 StrAccum errMsg;
5357 Table *pTab = pIdx->pTable;
5359 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
5360 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
5361 if( pIdx->aColExpr ){
5362 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
5363 }else{
5364 for(j=0; j<pIdx->nKeyCol; j++){
5365 char *zCol;
5366 assert( pIdx->aiColumn[j]>=0 );
5367 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
5368 if( j ) sqlite3_str_append(&errMsg, ", ", 2);
5369 sqlite3_str_appendall(&errMsg, pTab->zName);
5370 sqlite3_str_append(&errMsg, ".", 1);
5371 sqlite3_str_appendall(&errMsg, zCol);
5374 zErr = sqlite3StrAccumFinish(&errMsg);
5375 sqlite3HaltConstraint(pParse,
5376 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
5377 : SQLITE_CONSTRAINT_UNIQUE,
5378 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
5383 ** Code an OP_Halt due to non-unique rowid.
5385 void sqlite3RowidConstraint(
5386 Parse *pParse, /* Parsing context */
5387 int onError, /* Conflict resolution algorithm */
5388 Table *pTab /* The table with the non-unique rowid */
5390 char *zMsg;
5391 int rc;
5392 if( pTab->iPKey>=0 ){
5393 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
5394 pTab->aCol[pTab->iPKey].zCnName);
5395 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
5396 }else{
5397 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
5398 rc = SQLITE_CONSTRAINT_ROWID;
5400 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
5401 P5_ConstraintUnique);
5405 ** Check to see if pIndex uses the collating sequence pColl. Return
5406 ** true if it does and false if it does not.
5408 #ifndef SQLITE_OMIT_REINDEX
5409 static int collationMatch(const char *zColl, Index *pIndex){
5410 int i;
5411 assert( zColl!=0 );
5412 for(i=0; i<pIndex->nColumn; i++){
5413 const char *z = pIndex->azColl[i];
5414 assert( z!=0 || pIndex->aiColumn[i]<0 );
5415 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
5416 return 1;
5419 return 0;
5421 #endif
5424 ** Recompute all indices of pTab that use the collating sequence pColl.
5425 ** If pColl==0 then recompute all indices of pTab.
5427 #ifndef SQLITE_OMIT_REINDEX
5428 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
5429 if( !IsVirtual(pTab) ){
5430 Index *pIndex; /* An index associated with pTab */
5432 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
5433 if( zColl==0 || collationMatch(zColl, pIndex) ){
5434 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
5435 sqlite3BeginWriteOperation(pParse, 0, iDb);
5436 sqlite3RefillIndex(pParse, pIndex, -1);
5441 #endif
5444 ** Recompute all indices of all tables in all databases where the
5445 ** indices use the collating sequence pColl. If pColl==0 then recompute
5446 ** all indices everywhere.
5448 #ifndef SQLITE_OMIT_REINDEX
5449 static void reindexDatabases(Parse *pParse, char const *zColl){
5450 Db *pDb; /* A single database */
5451 int iDb; /* The database index number */
5452 sqlite3 *db = pParse->db; /* The database connection */
5453 HashElem *k; /* For looping over tables in pDb */
5454 Table *pTab; /* A table in the database */
5456 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
5457 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
5458 assert( pDb!=0 );
5459 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
5460 pTab = (Table*)sqliteHashData(k);
5461 reindexTable(pParse, pTab, zColl);
5465 #endif
5468 ** Generate code for the REINDEX command.
5470 ** REINDEX -- 1
5471 ** REINDEX <collation> -- 2
5472 ** REINDEX ?<database>.?<tablename> -- 3
5473 ** REINDEX ?<database>.?<indexname> -- 4
5475 ** Form 1 causes all indices in all attached databases to be rebuilt.
5476 ** Form 2 rebuilds all indices in all databases that use the named
5477 ** collating function. Forms 3 and 4 rebuild the named index or all
5478 ** indices associated with the named table.
5480 #ifndef SQLITE_OMIT_REINDEX
5481 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
5482 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
5483 char *z; /* Name of a table or index */
5484 const char *zDb; /* Name of the database */
5485 Table *pTab; /* A table in the database */
5486 Index *pIndex; /* An index associated with pTab */
5487 int iDb; /* The database index number */
5488 sqlite3 *db = pParse->db; /* The database connection */
5489 Token *pObjName; /* Name of the table or index to be reindexed */
5491 /* Read the database schema. If an error occurs, leave an error message
5492 ** and code in pParse and return NULL. */
5493 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
5494 return;
5497 if( pName1==0 ){
5498 reindexDatabases(pParse, 0);
5499 return;
5500 }else if( NEVER(pName2==0) || pName2->z==0 ){
5501 char *zColl;
5502 assert( pName1->z );
5503 zColl = sqlite3NameFromToken(pParse->db, pName1);
5504 if( !zColl ) return;
5505 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
5506 if( pColl ){
5507 reindexDatabases(pParse, zColl);
5508 sqlite3DbFree(db, zColl);
5509 return;
5511 sqlite3DbFree(db, zColl);
5513 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
5514 if( iDb<0 ) return;
5515 z = sqlite3NameFromToken(db, pObjName);
5516 if( z==0 ) return;
5517 zDb = db->aDb[iDb].zDbSName;
5518 pTab = sqlite3FindTable(db, z, zDb);
5519 if( pTab ){
5520 reindexTable(pParse, pTab, 0);
5521 sqlite3DbFree(db, z);
5522 return;
5524 pIndex = sqlite3FindIndex(db, z, zDb);
5525 sqlite3DbFree(db, z);
5526 if( pIndex ){
5527 sqlite3BeginWriteOperation(pParse, 0, iDb);
5528 sqlite3RefillIndex(pParse, pIndex, -1);
5529 return;
5531 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
5533 #endif
5536 ** Return a KeyInfo structure that is appropriate for the given Index.
5538 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5539 ** when it has finished using it.
5541 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
5542 int i;
5543 int nCol = pIdx->nColumn;
5544 int nKey = pIdx->nKeyCol;
5545 KeyInfo *pKey;
5546 if( pParse->nErr ) return 0;
5547 if( pIdx->uniqNotNull ){
5548 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
5549 }else{
5550 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
5552 if( pKey ){
5553 assert( sqlite3KeyInfoIsWriteable(pKey) );
5554 for(i=0; i<nCol; i++){
5555 const char *zColl = pIdx->azColl[i];
5556 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
5557 sqlite3LocateCollSeq(pParse, zColl);
5558 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
5559 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
5561 if( pParse->nErr ){
5562 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
5563 if( pIdx->bNoQuery==0 ){
5564 /* Deactivate the index because it contains an unknown collating
5565 ** sequence. The only way to reactive the index is to reload the
5566 ** schema. Adding the missing collating sequence later does not
5567 ** reactive the index. The application had the chance to register
5568 ** the missing index using the collation-needed callback. For
5569 ** simplicity, SQLite will not give the application a second chance.
5571 pIdx->bNoQuery = 1;
5572 pParse->rc = SQLITE_ERROR_RETRY;
5574 sqlite3KeyInfoUnref(pKey);
5575 pKey = 0;
5578 return pKey;
5581 #ifndef SQLITE_OMIT_CTE
5583 ** Create a new CTE object
5585 Cte *sqlite3CteNew(
5586 Parse *pParse, /* Parsing context */
5587 Token *pName, /* Name of the common-table */
5588 ExprList *pArglist, /* Optional column name list for the table */
5589 Select *pQuery, /* Query used to initialize the table */
5590 u8 eM10d /* The MATERIALIZED flag */
5592 Cte *pNew;
5593 sqlite3 *db = pParse->db;
5595 pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
5596 assert( pNew!=0 || db->mallocFailed );
5598 if( db->mallocFailed ){
5599 sqlite3ExprListDelete(db, pArglist);
5600 sqlite3SelectDelete(db, pQuery);
5601 }else{
5602 pNew->pSelect = pQuery;
5603 pNew->pCols = pArglist;
5604 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
5605 pNew->eM10d = eM10d;
5607 return pNew;
5611 ** Clear information from a Cte object, but do not deallocate storage
5612 ** for the object itself.
5614 static void cteClear(sqlite3 *db, Cte *pCte){
5615 assert( pCte!=0 );
5616 sqlite3ExprListDelete(db, pCte->pCols);
5617 sqlite3SelectDelete(db, pCte->pSelect);
5618 sqlite3DbFree(db, pCte->zName);
5622 ** Free the contents of the CTE object passed as the second argument.
5624 void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
5625 assert( pCte!=0 );
5626 cteClear(db, pCte);
5627 sqlite3DbFree(db, pCte);
5631 ** This routine is invoked once per CTE by the parser while parsing a
5632 ** WITH clause. The CTE described by teh third argument is added to
5633 ** the WITH clause of the second argument. If the second argument is
5634 ** NULL, then a new WITH argument is created.
5636 With *sqlite3WithAdd(
5637 Parse *pParse, /* Parsing context */
5638 With *pWith, /* Existing WITH clause, or NULL */
5639 Cte *pCte /* CTE to add to the WITH clause */
5641 sqlite3 *db = pParse->db;
5642 With *pNew;
5643 char *zName;
5645 if( pCte==0 ){
5646 return pWith;
5649 /* Check that the CTE name is unique within this WITH clause. If
5650 ** not, store an error in the Parse structure. */
5651 zName = pCte->zName;
5652 if( zName && pWith ){
5653 int i;
5654 for(i=0; i<pWith->nCte; i++){
5655 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5656 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
5661 if( pWith ){
5662 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
5663 pNew = sqlite3DbRealloc(db, pWith, nByte);
5664 }else{
5665 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
5667 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
5669 if( db->mallocFailed ){
5670 sqlite3CteDelete(db, pCte);
5671 pNew = pWith;
5672 }else{
5673 pNew->a[pNew->nCte++] = *pCte;
5674 sqlite3DbFree(db, pCte);
5677 return pNew;
5681 ** Free the contents of the With object passed as the second argument.
5683 void sqlite3WithDelete(sqlite3 *db, With *pWith){
5684 if( pWith ){
5685 int i;
5686 for(i=0; i<pWith->nCte; i++){
5687 cteClear(db, &pWith->a[i]);
5689 sqlite3DbFree(db, pWith);
5692 #endif /* !defined(SQLITE_OMIT_CTE) */