4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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:
25 #include "sqliteInt.h"
27 #ifndef SQLITE_OMIT_SHARED_CACHE
29 ** The TableLock structure is only used by the sqlite3TableLock() and
30 ** codeTableLocks() functions.
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 */
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
);
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
++];
78 p
->isWriteLock
= isWriteLock
;
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 */
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
){
103 Vdbe
*pVdbe
= pParse
->pVdbe
;
106 for(i
=0; i
<pParse
->nTableLock
; i
++){
107 TableLock
*p
= &pParse
->aTableLock
[i
];
109 sqlite3VdbeAddOp4(pVdbe
, OP_TableLock
, p1
, p
->iTab
, p
->isWriteLock
,
110 p
->zLockName
, P4_STATIC
);
114 #define codeTableLocks(x)
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
){
125 for(i
=0; i
<sizeof(yDbMask
); i
++) if( m
[i
] ) return 0;
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
137 ** Note that if an error occurred, it might be the case that
138 ** no VDBE code was generated.
140 void sqlite3FinishCoding(Parse
*pParse
){
145 assert( pParse
->pToplevel
==0 );
147 assert( db
->pParse
==pParse
);
148 if( pParse
->nested
) return;
150 if( db
->mallocFailed
) pParse
->rc
= SQLITE_NOMEM
;
153 assert( db
->mallocFailed
==0 );
155 /* Begin by generating some termination code at the end of the
161 pParse
->rc
= SQLITE_DONE
;
164 v
= sqlite3GetVdbe(pParse
);
165 if( v
==0 ) pParse
->rc
= SQLITE_ERROR
;
167 assert( !pParse
->isMultiWrite
168 || sqlite3VdbeAssertMayAbort(v
, pParse
->mayAbort
));
170 if( pParse
->bReturning
){
171 Returning
*pReturning
= pParse
->u1
.pReturning
;
175 if( pReturning
->nRetCol
){
176 sqlite3VdbeAddOp0(v
, OP_FkCheck
);
178 sqlite3VdbeAddOp1(v
, OP_Rewind
, pReturning
->iRetCur
);
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);
187 sqlite3VdbeJumpHere(v
, addrRewind
);
190 sqlite3VdbeAddOp0(v
, OP_Halt
);
192 #if SQLITE_USER_AUTHENTICATION && !defined(SQLITE_OMIT_SHARED_CACHE)
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
;
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);
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 */
221 DbMaskTest(pParse
->writeMask
,iDb
), /* P2 */
222 pSchema
->schema_cookie
, /* P3 */
223 pSchema
->iGeneration
/* P4 */
225 if( db
->init
.busy
==0 ) sqlite3VdbeChangeP5(v
, 1);
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;
237 #ifndef SQLITE_OMIT_SHARED_CACHE
238 /* Once all the cookies have been verified and transactions opened,
239 ** obtain the required table-locks. This is a no-op unless the
240 ** shared-cache feature is enabled.
242 if( pParse
->nTableLock
) codeTableLocks(pParse
);
245 /* Initialize any AUTOINCREMENT data structures required.
247 if( pParse
->pAinc
) sqlite3AutoincrementBegin(pParse
);
249 /* Code constant expressions that were factored out of inner loops.
251 if( pParse
->pConstExpr
){
252 ExprList
*pEL
= pParse
->pConstExpr
;
253 pParse
->okConstFactor
= 0;
254 for(i
=0; i
<pEL
->nExpr
; i
++){
255 assert( pEL
->a
[i
].u
.iConstExprReg
>0 );
256 sqlite3ExprCode(pParse
, pEL
->a
[i
].pExpr
, pEL
->a
[i
].u
.iConstExprReg
);
260 if( pParse
->bReturning
){
261 Returning
*pRet
= pParse
->u1
.pReturning
;
263 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pRet
->iRetCur
, pRet
->nRetCol
);
267 /* Finally, jump back to the beginning of the executable code. */
268 sqlite3VdbeGoto(v
, 1);
271 /* Get the VDBE program ready for execution
273 assert( v
!=0 || pParse
->nErr
);
274 assert( db
->mallocFailed
==0 || pParse
->nErr
);
275 if( pParse
->nErr
==0 ){
276 /* A minimum of one cursor is required if autoincrement is used
277 * See ticket [a696379c1f08866] */
278 assert( pParse
->pAinc
==0 || pParse
->nTab
>0 );
279 sqlite3VdbeMakeReady(v
, pParse
);
280 pParse
->rc
= SQLITE_DONE
;
282 pParse
->rc
= SQLITE_ERROR
;
287 ** Run the parser and code generator recursively in order to generate
288 ** code for the SQL statement given onto the end of the pParse context
289 ** currently under construction. Notes:
291 ** * The final OP_Halt is not appended and other initialization
292 ** and finalization steps are omitted because those are handling by the
295 ** * Built-in SQL functions always take precedence over application-defined
296 ** SQL functions. In other words, it is not possible to override a
297 ** built-in function.
299 void sqlite3NestedParse(Parse
*pParse
, const char *zFormat
, ...){
302 sqlite3
*db
= pParse
->db
;
303 u32 savedDbFlags
= db
->mDbFlags
;
304 char saveBuf
[PARSE_TAIL_SZ
];
306 if( pParse
->nErr
) return;
307 if( pParse
->eParseMode
) return;
308 assert( pParse
->nested
<10 ); /* Nesting should only be of limited depth */
309 va_start(ap
, zFormat
);
310 zSql
= sqlite3VMPrintf(db
, zFormat
, ap
);
313 /* This can result either from an OOM or because the formatted string
314 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
316 if( !db
->mallocFailed
) pParse
->rc
= SQLITE_TOOBIG
;
321 memcpy(saveBuf
, PARSE_TAIL(pParse
), PARSE_TAIL_SZ
);
322 memset(PARSE_TAIL(pParse
), 0, PARSE_TAIL_SZ
);
323 db
->mDbFlags
|= DBFLAG_PreferBuiltin
;
324 sqlite3RunParser(pParse
, zSql
);
325 db
->mDbFlags
= savedDbFlags
;
326 sqlite3DbFree(db
, zSql
);
327 memcpy(PARSE_TAIL(pParse
), saveBuf
, PARSE_TAIL_SZ
);
331 #if SQLITE_USER_AUTHENTICATION
333 ** Return TRUE if zTable is the name of the system table that stores the
334 ** list of users and their access credentials.
336 int sqlite3UserAuthTable(const char *zTable
){
337 return sqlite3_stricmp(zTable
, "sqlite_user")==0;
342 ** Locate the in-memory structure that describes a particular database
343 ** table given the name of that table and (optionally) the name of the
344 ** database containing the table. Return NULL if not found.
346 ** If zDatabase is 0, all databases are searched for the table and the
347 ** first matching table is returned. (No checking for duplicate table
348 ** names is done.) The search order is TEMP first, then MAIN, then any
349 ** auxiliary databases added using the ATTACH command.
351 ** See also sqlite3LocateTable().
353 Table
*sqlite3FindTable(sqlite3
*db
, const char *zName
, const char *zDatabase
){
357 /* All mutexes are required for schema access. Make sure we hold them. */
358 assert( zDatabase
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
359 #if SQLITE_USER_AUTHENTICATION
360 /* Only the admin user is allowed to know that the sqlite_user table
362 if( db
->auth
.authLevel
<UAUTH_Admin
&& sqlite3UserAuthTable(zName
)!=0 ){
367 for(i
=0; i
<db
->nDb
; i
++){
368 if( sqlite3StrICmp(zDatabase
, db
->aDb
[i
].zDbSName
)==0 ) break;
371 /* No match against the official names. But always match "main"
372 ** to schema 0 as a legacy fallback. */
373 if( sqlite3StrICmp(zDatabase
,"main")==0 ){
379 p
= sqlite3HashFind(&db
->aDb
[i
].pSchema
->tblHash
, zName
);
380 if( p
==0 && sqlite3StrNICmp(zName
, "sqlite_", 7)==0 ){
382 if( sqlite3StrICmp(zName
+7, &PREFERRED_TEMP_SCHEMA_TABLE
[7])==0
383 || sqlite3StrICmp(zName
+7, &PREFERRED_SCHEMA_TABLE
[7])==0
384 || sqlite3StrICmp(zName
+7, &LEGACY_SCHEMA_TABLE
[7])==0
386 p
= sqlite3HashFind(&db
->aDb
[1].pSchema
->tblHash
,
387 LEGACY_TEMP_SCHEMA_TABLE
);
390 if( sqlite3StrICmp(zName
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ){
391 p
= sqlite3HashFind(&db
->aDb
[i
].pSchema
->tblHash
,
392 LEGACY_SCHEMA_TABLE
);
397 /* Match against TEMP first */
398 p
= sqlite3HashFind(&db
->aDb
[1].pSchema
->tblHash
, zName
);
400 /* The main database is second */
401 p
= sqlite3HashFind(&db
->aDb
[0].pSchema
->tblHash
, zName
);
403 /* Attached databases are in order of attachment */
404 for(i
=2; i
<db
->nDb
; i
++){
405 assert( sqlite3SchemaMutexHeld(db
, i
, 0) );
406 p
= sqlite3HashFind(&db
->aDb
[i
].pSchema
->tblHash
, zName
);
409 if( p
==0 && sqlite3StrNICmp(zName
, "sqlite_", 7)==0 ){
410 if( sqlite3StrICmp(zName
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ){
411 p
= sqlite3HashFind(&db
->aDb
[0].pSchema
->tblHash
, LEGACY_SCHEMA_TABLE
);
412 }else if( sqlite3StrICmp(zName
+7, &PREFERRED_TEMP_SCHEMA_TABLE
[7])==0 ){
413 p
= sqlite3HashFind(&db
->aDb
[1].pSchema
->tblHash
,
414 LEGACY_TEMP_SCHEMA_TABLE
);
422 ** Locate the in-memory structure that describes a particular database
423 ** table given the name of that table and (optionally) the name of the
424 ** database containing the table. Return NULL if not found. Also leave an
425 ** error message in pParse->zErrMsg.
427 ** The difference between this routine and sqlite3FindTable() is that this
428 ** routine leaves an error message in pParse->zErrMsg where
429 ** sqlite3FindTable() does not.
431 Table
*sqlite3LocateTable(
432 Parse
*pParse
, /* context in which to report errors */
433 u32 flags
, /* LOCATE_VIEW or LOCATE_NOERR */
434 const char *zName
, /* Name of the table we are looking for */
435 const char *zDbase
/* Name of the database. Might be NULL */
438 sqlite3
*db
= pParse
->db
;
440 /* Read the database schema. If an error occurs, leave an error message
441 ** and code in pParse and return NULL. */
442 if( (db
->mDbFlags
& DBFLAG_SchemaKnownOk
)==0
443 && SQLITE_OK
!=sqlite3ReadSchema(pParse
)
448 p
= sqlite3FindTable(db
, zName
, zDbase
);
450 #ifndef SQLITE_OMIT_VIRTUALTABLE
451 /* If zName is the not the name of a table in the schema created using
452 ** CREATE, then check to see if it is the name of an virtual table that
453 ** can be an eponymous virtual table. */
454 if( (pParse
->prepFlags
& SQLITE_PREPARE_NO_VTAB
)==0 && db
->init
.busy
==0 ){
455 Module
*pMod
= (Module
*)sqlite3HashFind(&db
->aModule
, zName
);
456 if( pMod
==0 && sqlite3_strnicmp(zName
, "pragma_", 7)==0 ){
457 pMod
= sqlite3PragmaVtabRegister(db
, zName
);
459 if( pMod
&& sqlite3VtabEponymousTableInit(pParse
, pMod
) ){
460 testcase( pMod
->pEpoTab
==0 );
461 return pMod
->pEpoTab
;
465 if( flags
& LOCATE_NOERR
) return 0;
466 pParse
->checkSchema
= 1;
467 }else if( IsVirtual(p
) && (pParse
->prepFlags
& SQLITE_PREPARE_NO_VTAB
)!=0 ){
472 const char *zMsg
= flags
& LOCATE_VIEW
? "no such view" : "no such table";
474 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zMsg
, zDbase
, zName
);
476 sqlite3ErrorMsg(pParse
, "%s: %s", zMsg
, zName
);
479 assert( HasRowid(p
) || p
->iPKey
<0 );
486 ** Locate the table identified by *p.
488 ** This is a wrapper around sqlite3LocateTable(). The difference between
489 ** sqlite3LocateTable() and this function is that this function restricts
490 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
491 ** non-NULL if it is part of a view or trigger program definition. See
492 ** sqlite3FixSrcList() for details.
494 Table
*sqlite3LocateTableItem(
500 assert( p
->pSchema
==0 || p
->zDatabase
==0 );
502 int iDb
= sqlite3SchemaToIndex(pParse
->db
, p
->pSchema
);
503 zDb
= pParse
->db
->aDb
[iDb
].zDbSName
;
507 return sqlite3LocateTable(pParse
, flags
, p
->zName
, zDb
);
511 ** Return the preferred table name for system tables. Translate legacy
512 ** names into the new preferred names, as appropriate.
514 const char *sqlite3PreferredTableName(const char *zName
){
515 if( sqlite3StrNICmp(zName
, "sqlite_", 7)==0 ){
516 if( sqlite3StrICmp(zName
+7, &LEGACY_SCHEMA_TABLE
[7])==0 ){
517 return PREFERRED_SCHEMA_TABLE
;
519 if( sqlite3StrICmp(zName
+7, &LEGACY_TEMP_SCHEMA_TABLE
[7])==0 ){
520 return PREFERRED_TEMP_SCHEMA_TABLE
;
527 ** Locate the in-memory structure that describes
528 ** a particular index given the name of that index
529 ** and the name of the database that contains the index.
530 ** Return NULL if not found.
532 ** If zDatabase is 0, all databases are searched for the
533 ** table and the first matching index is returned. (No checking
534 ** for duplicate index names is done.) The search order is
535 ** TEMP first, then MAIN, then any auxiliary databases added
536 ** using the ATTACH command.
538 Index
*sqlite3FindIndex(sqlite3
*db
, const char *zName
, const char *zDb
){
541 /* All mutexes are required for schema access. Make sure we hold them. */
542 assert( zDb
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
543 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
544 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
545 Schema
*pSchema
= db
->aDb
[j
].pSchema
;
547 if( zDb
&& sqlite3DbIsNamed(db
, j
, zDb
)==0 ) continue;
548 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
549 p
= sqlite3HashFind(&pSchema
->idxHash
, zName
);
556 ** Reclaim the memory used by an index
558 void sqlite3FreeIndex(sqlite3
*db
, Index
*p
){
559 #ifndef SQLITE_OMIT_ANALYZE
560 sqlite3DeleteIndexSamples(db
, p
);
562 sqlite3ExprDelete(db
, p
->pPartIdxWhere
);
563 sqlite3ExprListDelete(db
, p
->aColExpr
);
564 sqlite3DbFree(db
, p
->zColAff
);
565 if( p
->isResized
) sqlite3DbFree(db
, (void *)p
->azColl
);
566 #ifdef SQLITE_ENABLE_STAT4
567 sqlite3_free(p
->aiRowEst
);
569 sqlite3DbFree(db
, p
);
573 ** For the index called zIdxName which is found in the database iDb,
574 ** unlike that index from its Table then remove the index from
575 ** the index hash table and free all memory structures associated
578 void sqlite3UnlinkAndDeleteIndex(sqlite3
*db
, int iDb
, const char *zIdxName
){
582 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
583 pHash
= &db
->aDb
[iDb
].pSchema
->idxHash
;
584 pIndex
= sqlite3HashInsert(pHash
, zIdxName
, 0);
585 if( ALWAYS(pIndex
) ){
586 if( pIndex
->pTable
->pIndex
==pIndex
){
587 pIndex
->pTable
->pIndex
= pIndex
->pNext
;
590 /* Justification of ALWAYS(); The index must be on the list of
592 p
= pIndex
->pTable
->pIndex
;
593 while( ALWAYS(p
) && p
->pNext
!=pIndex
){ p
= p
->pNext
; }
594 if( ALWAYS(p
&& p
->pNext
==pIndex
) ){
595 p
->pNext
= pIndex
->pNext
;
598 sqlite3FreeIndex(db
, pIndex
);
600 db
->mDbFlags
|= DBFLAG_SchemaChange
;
604 ** Look through the list of open database files in db->aDb[] and if
605 ** any have been closed, remove them from the list. Reallocate the
606 ** db->aDb[] structure to a smaller size, if possible.
608 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
609 ** are never candidates for being collapsed.
611 void sqlite3CollapseDatabaseArray(sqlite3
*db
){
613 for(i
=j
=2; i
<db
->nDb
; i
++){
614 struct Db
*pDb
= &db
->aDb
[i
];
616 sqlite3DbFree(db
, pDb
->zDbSName
);
621 db
->aDb
[j
] = db
->aDb
[i
];
626 if( db
->nDb
<=2 && db
->aDb
!=db
->aDbStatic
){
627 memcpy(db
->aDbStatic
, db
->aDb
, 2*sizeof(db
->aDb
[0]));
628 sqlite3DbFree(db
, db
->aDb
);
629 db
->aDb
= db
->aDbStatic
;
634 ** Reset the schema for the database at index iDb. Also reset the
635 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
636 ** Deferred resets may be run by calling with iDb<0.
638 void sqlite3ResetOneSchema(sqlite3
*db
, int iDb
){
640 assert( iDb
<db
->nDb
);
643 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
644 DbSetProperty(db
, iDb
, DB_ResetWanted
);
645 DbSetProperty(db
, 1, DB_ResetWanted
);
646 db
->mDbFlags
&= ~DBFLAG_SchemaKnownOk
;
649 if( db
->nSchemaLock
==0 ){
650 for(i
=0; i
<db
->nDb
; i
++){
651 if( DbHasProperty(db
, i
, DB_ResetWanted
) ){
652 sqlite3SchemaClear(db
->aDb
[i
].pSchema
);
659 ** Erase all schema information from all attached databases (including
660 ** "main" and "temp") for a single database connection.
662 void sqlite3ResetAllSchemasOfConnection(sqlite3
*db
){
664 sqlite3BtreeEnterAll(db
);
665 for(i
=0; i
<db
->nDb
; i
++){
666 Db
*pDb
= &db
->aDb
[i
];
668 if( db
->nSchemaLock
==0 ){
669 sqlite3SchemaClear(pDb
->pSchema
);
671 DbSetProperty(db
, i
, DB_ResetWanted
);
675 db
->mDbFlags
&= ~(DBFLAG_SchemaChange
|DBFLAG_SchemaKnownOk
);
676 sqlite3VtabUnlockList(db
);
677 sqlite3BtreeLeaveAll(db
);
678 if( db
->nSchemaLock
==0 ){
679 sqlite3CollapseDatabaseArray(db
);
684 ** This routine is called when a commit occurs.
686 void sqlite3CommitInternalChanges(sqlite3
*db
){
687 db
->mDbFlags
&= ~DBFLAG_SchemaChange
;
691 ** Set the expression associated with a column. This is usually
692 ** the DEFAULT value, but might also be the expression that computes
693 ** the value for a generated column.
695 void sqlite3ColumnSetExpr(
696 Parse
*pParse
, /* Parsing context */
697 Table
*pTab
, /* The table containing the column */
698 Column
*pCol
, /* The column to receive the new DEFAULT expression */
699 Expr
*pExpr
/* The new default expression */
702 assert( IsOrdinaryTable(pTab
) );
703 pList
= pTab
->u
.tab
.pDfltList
;
706 || NEVER(pList
->nExpr
<pCol
->iDflt
)
708 pCol
->iDflt
= pList
==0 ? 1 : pList
->nExpr
+1;
709 pTab
->u
.tab
.pDfltList
= sqlite3ExprListAppend(pParse
, pList
, pExpr
);
711 sqlite3ExprDelete(pParse
->db
, pList
->a
[pCol
->iDflt
-1].pExpr
);
712 pList
->a
[pCol
->iDflt
-1].pExpr
= pExpr
;
717 ** Return the expression associated with a column. The expression might be
718 ** the DEFAULT clause or the AS clause of a generated column.
719 ** Return NULL if the column has no associated expression.
721 Expr
*sqlite3ColumnExpr(Table
*pTab
, Column
*pCol
){
722 if( pCol
->iDflt
==0 ) return 0;
723 if( !IsOrdinaryTable(pTab
) ) return 0;
724 if( NEVER(pTab
->u
.tab
.pDfltList
==0) ) return 0;
725 if( NEVER(pTab
->u
.tab
.pDfltList
->nExpr
<pCol
->iDflt
) ) return 0;
726 return pTab
->u
.tab
.pDfltList
->a
[pCol
->iDflt
-1].pExpr
;
730 ** Set the collating sequence name for a column.
732 void sqlite3ColumnSetColl(
741 n
= sqlite3Strlen30(pCol
->zCnName
) + 1;
742 if( pCol
->colFlags
& COLFLAG_HASTYPE
){
743 n
+= sqlite3Strlen30(pCol
->zCnName
+n
) + 1;
745 nColl
= sqlite3Strlen30(zColl
) + 1;
746 zNew
= sqlite3DbRealloc(db
, pCol
->zCnName
, nColl
+n
);
748 pCol
->zCnName
= zNew
;
749 memcpy(pCol
->zCnName
+ n
, zColl
, nColl
);
750 pCol
->colFlags
|= COLFLAG_HASCOLL
;
755 ** Return the collating sequence name for a column
757 const char *sqlite3ColumnColl(Column
*pCol
){
759 if( (pCol
->colFlags
& COLFLAG_HASCOLL
)==0 ) return 0;
762 if( pCol
->colFlags
& COLFLAG_HASTYPE
){
763 do{ z
++; }while( *z
);
769 ** Delete memory allocated for the column names of a table or view (the
770 ** Table.aCol[] array).
772 void sqlite3DeleteColumnNames(sqlite3
*db
, Table
*pTable
){
777 if( (pCol
= pTable
->aCol
)!=0 ){
778 for(i
=0; i
<pTable
->nCol
; i
++, pCol
++){
779 assert( pCol
->zCnName
==0 || pCol
->hName
==sqlite3StrIHash(pCol
->zCnName
) );
780 sqlite3DbFree(db
, pCol
->zCnName
);
782 sqlite3DbNNFreeNN(db
, pTable
->aCol
);
783 if( IsOrdinaryTable(pTable
) ){
784 sqlite3ExprListDelete(db
, pTable
->u
.tab
.pDfltList
);
786 if( db
->pnBytesFreed
==0 ){
789 if( IsOrdinaryTable(pTable
) ){
790 pTable
->u
.tab
.pDfltList
= 0;
797 ** Remove the memory data structures associated with the given
798 ** Table. No changes are made to disk by this routine.
800 ** This routine just deletes the data structure. It does not unlink
801 ** the table data structure from the hash table. But it does destroy
802 ** memory structures of the indices and foreign keys associated with
805 ** The db parameter is optional. It is needed if the Table object
806 ** contains lookaside memory. (Table objects in the schema do not use
807 ** lookaside memory, but some ephemeral Table objects do.) Or the
808 ** db parameter can be used with db->pnBytesFreed to measure the memory
809 ** used by the Table object.
811 static void SQLITE_NOINLINE
deleteTable(sqlite3
*db
, Table
*pTable
){
812 Index
*pIndex
, *pNext
;
815 /* Record the number of outstanding lookaside allocations in schema Tables
816 ** prior to doing any free() operations. Since schema Tables do not use
817 ** lookaside, this number should not change.
819 ** If malloc has already failed, it may be that it failed while allocating
820 ** a Table object that was going to be marked ephemeral. So do not check
821 ** that no lookaside memory is used in this case either. */
824 if( !db
->mallocFailed
&& (pTable
->tabFlags
& TF_Ephemeral
)==0 ){
825 nLookaside
= sqlite3LookasideUsed(db
, 0);
829 /* Delete all indices associated with this table. */
830 for(pIndex
= pTable
->pIndex
; pIndex
; pIndex
=pNext
){
831 pNext
= pIndex
->pNext
;
832 assert( pIndex
->pSchema
==pTable
->pSchema
833 || (IsVirtual(pTable
) && pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
) );
834 if( db
->pnBytesFreed
==0 && !IsVirtual(pTable
) ){
835 char *zName
= pIndex
->zName
;
836 TESTONLY ( Index
*pOld
= ) sqlite3HashInsert(
837 &pIndex
->pSchema
->idxHash
, zName
, 0
839 assert( db
==0 || sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
840 assert( pOld
==pIndex
|| pOld
==0 );
842 sqlite3FreeIndex(db
, pIndex
);
845 if( IsOrdinaryTable(pTable
) ){
846 sqlite3FkDelete(db
, pTable
);
848 #ifndef SQLITE_OMIT_VIRTUALTABLE
849 else if( IsVirtual(pTable
) ){
850 sqlite3VtabClear(db
, pTable
);
854 assert( IsView(pTable
) );
855 sqlite3SelectDelete(db
, pTable
->u
.view
.pSelect
);
858 /* Delete the Table structure itself.
860 sqlite3DeleteColumnNames(db
, pTable
);
861 sqlite3DbFree(db
, pTable
->zName
);
862 sqlite3DbFree(db
, pTable
->zColAff
);
863 sqlite3ExprListDelete(db
, pTable
->pCheck
);
864 sqlite3DbFree(db
, pTable
);
866 /* Verify that no lookaside memory was used by schema tables */
867 assert( nLookaside
==0 || nLookaside
==sqlite3LookasideUsed(db
,0) );
869 void sqlite3DeleteTable(sqlite3
*db
, Table
*pTable
){
870 /* Do not delete the table until the reference count reaches zero. */
872 if( !pTable
) return;
873 if( db
->pnBytesFreed
==0 && (--pTable
->nTabRef
)>0 ) return;
874 deleteTable(db
, pTable
);
876 void sqlite3DeleteTableGeneric(sqlite3
*db
, void *pTable
){
877 sqlite3DeleteTable(db
, (Table
*)pTable
);
882 ** Unlink the given table from the hash tables and the delete the
883 ** table structure with all its indices and foreign keys.
885 void sqlite3UnlinkAndDeleteTable(sqlite3
*db
, int iDb
, const char *zTabName
){
890 assert( iDb
>=0 && iDb
<db
->nDb
);
892 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
893 testcase( zTabName
[0]==0 ); /* Zero-length table names are allowed */
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
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
){
916 zName
= sqlite3DbStrNDup(db
, (const char*)pName
->z
, pName
->n
);
917 sqlite3Dequote(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);
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 */
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;
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
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
);
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
;
999 if( db
->init
.busy
) {
1000 sqlite3ErrorMsg(pParse
, "corrupt database");
1004 iDb
= sqlite3FindDb(db
, pName1
);
1006 sqlite3ErrorMsg(pParse
, "unknown database %T", pName1
);
1010 assert( db
->init
.iDb
==0 || db
->init
.busy
|| IN_SPECIAL_PARSE
1011 || (db
->mDbFlags
& DBFLAG_Vacuum
)!=0);
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
))==
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
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 */
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
;
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",
1071 return SQLITE_ERROR
;
1079 ** Return the PRIMARY KEY index of a table
1081 Index
*sqlite3PrimaryKeyIndex(Table
*pTab
){
1083 for(p
=pTab
->pIndex
; p
&& !IsPrimaryKeyIndex(p
); p
=p
->pNext
){}
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
){
1095 for(i
=0; i
<pIdx
->nColumn
; i
++){
1096 if( iCol
==pIdx
->aiColumn
[i
] ) return i
;
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
){
1116 for(i
=0; i
<=iCol
; i
++){
1117 if( pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
) iCol
++;
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
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
){
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
;
1173 /* iCol is a normal or stored column */
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
);
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 */
1222 char *zName
= 0; /* The name of the new table */
1223 sqlite3
*db
= pParse
->db
;
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 */
1231 zName
= sqlite3DbStrDup(db
, SCHEMA_TABLE(iDb
));
1234 /* The common case */
1235 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
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");
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
,
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
],
1271 goto begin_table_error
;
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
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
);
1291 sqlite3ErrorMsg(pParse
, "%s %T already exists",
1292 (IsView(pTable
)? "view" : "table"), pName
);
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
));
1308 assert( db
->mallocFailed
);
1309 pParse
->rc
= SQLITE_NOMEM_BKPT
;
1311 goto begin_table_error
;
1313 pTable
->zName
= zName
;
1315 pTable
->pSchema
= db
->aDb
[iDb
].pSchema
;
1316 pTable
->nTabRef
= 1;
1317 #ifdef SQLITE_DEFAULT_ROWEST
1318 pTable
->nRowLogEst
= sqlite3LogEst(SQLITE_DEFAULT_ROWEST
);
1320 pTable
->nRowLogEst
= 200; assert( 200==sqlite3LogEst(1048576) );
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
1333 if( !db
->init
.busy
&& (v
= sqlite3GetVdbe(pParse
))!=0 ){
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
1343 sqlite3VdbeAddOp0(v
, OP_VBegin
);
1347 /* If the file format and encoding in the database have not been set,
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
);
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. */
1392 /* If an error occurs, we jump here */
1394 pParse
->checkSchema
= 1;
1395 sqlite3DbFree(db
, zName
);
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
;
1414 ** Clean up the data structures associated with the RETURNING clause.
1416 static void sqlite3DeleteReturning(sqlite3
*db
, void *pArg
){
1417 Returning
*pRet
= (Returning
*)pArg
;
1419 pHash
= &(db
->aDb
[1].pSchema
->trigHash
);
1420 sqlite3HashInsert(pHash
, pRet
->zName
, 0);
1421 sqlite3ExprListDelete(db
, pRet
->pReturnEL
);
1422 sqlite3DbFree(db
, pRet
);
1426 ** Add the RETURNING clause to the parse currently underway.
1428 ** This routine creates a special TEMP trigger that will fire for each row
1429 ** of the DML statement. That TEMP trigger contains a single SELECT
1430 ** statement with a result set that is the argument of the RETURNING clause.
1431 ** The trigger has the Trigger.bReturning flag and an opcode of
1432 ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
1433 ** knows to handle it specially. The TEMP trigger is automatically
1434 ** removed at the end of the parse.
1436 ** When this routine is called, we do not yet know if the RETURNING clause
1437 ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
1438 ** RETURNING trigger instead. It will then be converted into the appropriate
1439 ** type on the first call to sqlite3TriggersExist().
1441 void sqlite3AddReturning(Parse
*pParse
, ExprList
*pList
){
1444 sqlite3
*db
= pParse
->db
;
1445 if( pParse
->pNewTrigger
){
1446 sqlite3ErrorMsg(pParse
, "cannot use RETURNING in a trigger");
1448 assert( pParse
->bReturning
==0 || pParse
->ifNotExists
);
1450 pParse
->bReturning
= 1;
1451 pRet
= sqlite3DbMallocZero(db
, sizeof(*pRet
));
1453 sqlite3ExprListDelete(db
, pList
);
1456 pParse
->u1
.pReturning
= pRet
;
1457 pRet
->pParse
= pParse
;
1458 pRet
->pReturnEL
= pList
;
1459 sqlite3ParserAddCleanup(pParse
, sqlite3DeleteReturning
, pRet
);
1460 testcase( pParse
->earlyCleanup
);
1461 if( db
->mallocFailed
) return;
1462 sqlite3_snprintf(sizeof(pRet
->zName
), pRet
->zName
,
1463 "sqlite_returning_%p", pParse
);
1464 pRet
->retTrig
.zName
= pRet
->zName
;
1465 pRet
->retTrig
.op
= TK_RETURNING
;
1466 pRet
->retTrig
.tr_tm
= TRIGGER_AFTER
;
1467 pRet
->retTrig
.bReturning
= 1;
1468 pRet
->retTrig
.pSchema
= db
->aDb
[1].pSchema
;
1469 pRet
->retTrig
.pTabSchema
= db
->aDb
[1].pSchema
;
1470 pRet
->retTrig
.step_list
= &pRet
->retTStep
;
1471 pRet
->retTStep
.op
= TK_RETURNING
;
1472 pRet
->retTStep
.pTrig
= &pRet
->retTrig
;
1473 pRet
->retTStep
.pExprList
= pList
;
1474 pHash
= &(db
->aDb
[1].pSchema
->trigHash
);
1475 assert( sqlite3HashFind(pHash
, pRet
->zName
)==0
1476 || pParse
->nErr
|| pParse
->ifNotExists
);
1477 if( sqlite3HashInsert(pHash
, pRet
->zName
, &pRet
->retTrig
)
1479 sqlite3OomFault(db
);
1484 ** Add a new column to the table currently being constructed.
1486 ** The parser calls this routine once for each column declaration
1487 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1488 ** first to get things going. Then this routine is called for each
1491 void sqlite3AddColumn(Parse
*pParse
, Token sName
, Token sType
){
1497 sqlite3
*db
= pParse
->db
;
1500 u8 eType
= COLTYPE_CUSTOM
;
1502 char affinity
= SQLITE_AFF_BLOB
;
1504 if( (p
= pParse
->pNewTable
)==0 ) return;
1505 if( p
->nCol
+1>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1506 sqlite3ErrorMsg(pParse
, "too many columns on %s", p
->zName
);
1509 if( !IN_RENAME_OBJECT
) sqlite3DequoteToken(&sName
);
1511 /* Because keywords GENERATE ALWAYS can be converted into identifiers
1512 ** by the parser, we can sometimes end up with a typename that ends
1513 ** with "generated always". Check for this case and omit the surplus
1516 && sqlite3_strnicmp(sType
.z
+(sType
.n
-6),"always",6)==0
1519 while( ALWAYS(sType
.n
>0) && sqlite3Isspace(sType
.z
[sType
.n
-1]) ) sType
.n
--;
1521 && sqlite3_strnicmp(sType
.z
+(sType
.n
-9),"generated",9)==0
1524 while( sType
.n
>0 && sqlite3Isspace(sType
.z
[sType
.n
-1]) ) sType
.n
--;
1528 /* Check for standard typenames. For standard typenames we will
1529 ** set the Column.eType field rather than storing the typename after
1530 ** the column name, in order to save space. */
1532 sqlite3DequoteToken(&sType
);
1533 for(i
=0; i
<SQLITE_N_STDTYPE
; i
++){
1534 if( sType
.n
==sqlite3StdTypeLen
[i
]
1535 && sqlite3_strnicmp(sType
.z
, sqlite3StdType
[i
], sType
.n
)==0
1539 affinity
= sqlite3StdTypeAffinity
[i
];
1540 if( affinity
<=SQLITE_AFF_TEXT
) szEst
= 5;
1546 z
= sqlite3DbMallocRaw(db
, (i64
)sName
.n
+ 1 + (i64
)sType
.n
+ (sType
.n
>0) );
1548 if( IN_RENAME_OBJECT
) sqlite3RenameTokenMap(pParse
, (void*)z
, &sName
);
1549 memcpy(z
, sName
.z
, sName
.n
);
1552 hName
= sqlite3StrIHash(z
);
1553 for(i
=0; i
<p
->nCol
; i
++){
1554 if( p
->aCol
[i
].hName
==hName
&& sqlite3StrICmp(z
, p
->aCol
[i
].zCnName
)==0 ){
1555 sqlite3ErrorMsg(pParse
, "duplicate column name: %s", z
);
1556 sqlite3DbFree(db
, z
);
1560 aNew
= sqlite3DbRealloc(db
,p
->aCol
,((i64
)p
->nCol
+1)*sizeof(p
->aCol
[0]));
1562 sqlite3DbFree(db
, z
);
1566 pCol
= &p
->aCol
[p
->nCol
];
1567 memset(pCol
, 0, sizeof(p
->aCol
[0]));
1569 pCol
->hName
= hName
;
1570 sqlite3ColumnPropertiesFromName(p
, pCol
);
1573 /* If there is no type specified, columns have the default affinity
1574 ** 'BLOB' with a default size of 4 bytes. */
1575 pCol
->affinity
= affinity
;
1576 pCol
->eCType
= eType
;
1577 pCol
->szEst
= szEst
;
1578 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1579 if( affinity
==SQLITE_AFF_BLOB
){
1580 if( 4>=sqlite3GlobalConfig
.szSorterRef
){
1581 pCol
->colFlags
|= COLFLAG_SORTERREF
;
1586 zType
= z
+ sqlite3Strlen30(z
) + 1;
1587 memcpy(zType
, sType
.z
, sType
.n
);
1589 sqlite3Dequote(zType
);
1590 pCol
->affinity
= sqlite3AffinityType(zType
, pCol
);
1591 pCol
->colFlags
|= COLFLAG_HASTYPE
;
1595 pParse
->constraintName
.n
= 0;
1599 ** This routine is called by the parser while in the middle of
1600 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1601 ** been seen on a column. This routine sets the notNull flag on
1602 ** the column currently under construction.
1604 void sqlite3AddNotNull(Parse
*pParse
, int onError
){
1607 p
= pParse
->pNewTable
;
1608 if( p
==0 || NEVER(p
->nCol
<1) ) return;
1609 pCol
= &p
->aCol
[p
->nCol
-1];
1610 pCol
->notNull
= (u8
)onError
;
1611 p
->tabFlags
|= TF_HasNotNull
;
1613 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1614 ** on this column. */
1615 if( pCol
->colFlags
& COLFLAG_UNIQUE
){
1617 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1618 assert( pIdx
->nKeyCol
==1 && pIdx
->onError
!=OE_None
);
1619 if( pIdx
->aiColumn
[0]==p
->nCol
-1 ){
1620 pIdx
->uniqNotNull
= 1;
1627 ** Scan the column type name zType (length nType) and return the
1628 ** associated affinity type.
1630 ** This routine does a case-independent search of zType for the
1631 ** substrings in the following table. If one of the substrings is
1632 ** found, the corresponding affinity is returned. If zType contains
1633 ** more than one of the substrings, entries toward the top of
1634 ** the table take priority. For example, if zType is 'BLOBINT',
1635 ** SQLITE_AFF_INTEGER is returned.
1637 ** Substring | Affinity
1638 ** --------------------------------
1639 ** 'INT' | SQLITE_AFF_INTEGER
1640 ** 'CHAR' | SQLITE_AFF_TEXT
1641 ** 'CLOB' | SQLITE_AFF_TEXT
1642 ** 'TEXT' | SQLITE_AFF_TEXT
1643 ** 'BLOB' | SQLITE_AFF_BLOB
1644 ** 'REAL' | SQLITE_AFF_REAL
1645 ** 'FLOA' | SQLITE_AFF_REAL
1646 ** 'DOUB' | SQLITE_AFF_REAL
1648 ** If none of the substrings in the above table are found,
1649 ** SQLITE_AFF_NUMERIC is returned.
1651 char sqlite3AffinityType(const char *zIn
, Column
*pCol
){
1653 char aff
= SQLITE_AFF_NUMERIC
;
1654 const char *zChar
= 0;
1659 h
= (h
<<8) + sqlite3UpperToLower
[x
];
1661 if( h
==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1662 aff
= SQLITE_AFF_TEXT
;
1664 }else if( h
==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1665 aff
= SQLITE_AFF_TEXT
;
1666 }else if( h
==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1667 aff
= SQLITE_AFF_TEXT
;
1668 }else if( h
==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1669 && (aff
==SQLITE_AFF_NUMERIC
|| aff
==SQLITE_AFF_REAL
) ){
1670 aff
= SQLITE_AFF_BLOB
;
1671 if( zIn
[0]=='(' ) zChar
= zIn
;
1672 #ifndef SQLITE_OMIT_FLOATING_POINT
1673 }else if( h
==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1674 && aff
==SQLITE_AFF_NUMERIC
){
1675 aff
= SQLITE_AFF_REAL
;
1676 }else if( h
==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1677 && aff
==SQLITE_AFF_NUMERIC
){
1678 aff
= SQLITE_AFF_REAL
;
1679 }else if( h
==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1680 && aff
==SQLITE_AFF_NUMERIC
){
1681 aff
= SQLITE_AFF_REAL
;
1683 }else if( (h
&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1684 aff
= SQLITE_AFF_INTEGER
;
1689 /* If pCol is not NULL, store an estimate of the field size. The
1690 ** estimate is scaled so that the size of an integer is 1. */
1692 int v
= 0; /* default size is approx 4 bytes */
1693 if( aff
<SQLITE_AFF_NUMERIC
){
1696 if( sqlite3Isdigit(zChar
[0]) ){
1697 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1698 sqlite3GetInt32(zChar
, &v
);
1704 v
= 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1707 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1708 if( v
>=sqlite3GlobalConfig
.szSorterRef
){
1709 pCol
->colFlags
|= COLFLAG_SORTERREF
;
1713 if( v
>255 ) v
= 255;
1720 ** The expression is the default value for the most recently added column
1721 ** of the table currently under construction.
1723 ** Default value expressions must be constant. Raise an exception if this
1726 ** This routine is called by the parser while in the middle of
1727 ** parsing a CREATE TABLE statement.
1729 void sqlite3AddDefaultValue(
1730 Parse
*pParse
, /* Parsing context */
1731 Expr
*pExpr
, /* The parsed expression of the default value */
1732 const char *zStart
, /* Start of the default value text */
1733 const char *zEnd
/* First character past end of default value text */
1737 sqlite3
*db
= pParse
->db
;
1738 p
= pParse
->pNewTable
;
1740 int isInit
= db
->init
.busy
&& db
->init
.iDb
!=1;
1741 pCol
= &(p
->aCol
[p
->nCol
-1]);
1742 if( !sqlite3ExprIsConstantOrFunction(pExpr
, isInit
) ){
1743 sqlite3ErrorMsg(pParse
, "default value of column [%s] is not constant",
1745 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1746 }else if( pCol
->colFlags
& COLFLAG_GENERATED
){
1747 testcase( pCol
->colFlags
& COLFLAG_VIRTUAL
);
1748 testcase( pCol
->colFlags
& COLFLAG_STORED
);
1749 sqlite3ErrorMsg(pParse
, "cannot use DEFAULT on a generated column");
1752 /* A copy of pExpr is used instead of the original, as pExpr contains
1753 ** tokens that point to volatile memory.
1756 memset(&x
, 0, sizeof(x
));
1758 x
.u
.zToken
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
1761 pDfltExpr
= sqlite3ExprDup(db
, &x
, EXPRDUP_REDUCE
);
1762 sqlite3DbFree(db
, x
.u
.zToken
);
1763 sqlite3ColumnSetExpr(pParse
, p
, pCol
, pDfltExpr
);
1766 if( IN_RENAME_OBJECT
){
1767 sqlite3RenameExprUnmap(pParse
, pExpr
);
1769 sqlite3ExprDelete(db
, pExpr
);
1773 ** Backwards Compatibility Hack:
1775 ** Historical versions of SQLite accepted strings as column names in
1776 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1778 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1779 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1781 ** This is goofy. But to preserve backwards compatibility we continue to
1782 ** accept it. This routine does the necessary conversion. It converts
1783 ** the expression given in its argument from a TK_STRING into a TK_ID
1784 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1785 ** If the expression is anything other than TK_STRING, the expression is
1788 static void sqlite3StringToId(Expr
*p
){
1789 if( p
->op
==TK_STRING
){
1791 }else if( p
->op
==TK_COLLATE
&& p
->pLeft
->op
==TK_STRING
){
1792 p
->pLeft
->op
= TK_ID
;
1797 ** Tag the given column as being part of the PRIMARY KEY
1799 static void makeColumnPartOfPrimaryKey(Parse
*pParse
, Column
*pCol
){
1800 pCol
->colFlags
|= COLFLAG_PRIMKEY
;
1801 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1802 if( pCol
->colFlags
& COLFLAG_GENERATED
){
1803 testcase( pCol
->colFlags
& COLFLAG_VIRTUAL
);
1804 testcase( pCol
->colFlags
& COLFLAG_STORED
);
1805 sqlite3ErrorMsg(pParse
,
1806 "generated columns cannot be part of the PRIMARY KEY");
1812 ** Designate the PRIMARY KEY for the table. pList is a list of names
1813 ** of columns that form the primary key. If pList is NULL, then the
1814 ** most recently added column of the table is the primary key.
1816 ** A table can have at most one primary key. If the table already has
1817 ** a primary key (and this is the second primary key) then create an
1820 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1821 ** then we will try to use that column as the rowid. Set the Table.iPKey
1822 ** field of the table under construction to be the index of the
1823 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1824 ** no INTEGER PRIMARY KEY.
1826 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1827 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1829 void sqlite3AddPrimaryKey(
1830 Parse
*pParse
, /* Parsing context */
1831 ExprList
*pList
, /* List of field names to be indexed */
1832 int onError
, /* What to do with a uniqueness conflict */
1833 int autoInc
, /* True if the AUTOINCREMENT keyword is present */
1834 int sortOrder
/* SQLITE_SO_ASC or SQLITE_SO_DESC */
1836 Table
*pTab
= pParse
->pNewTable
;
1840 if( pTab
==0 ) goto primary_key_exit
;
1841 if( pTab
->tabFlags
& TF_HasPrimaryKey
){
1842 sqlite3ErrorMsg(pParse
,
1843 "table \"%s\" has more than one primary key", pTab
->zName
);
1844 goto primary_key_exit
;
1846 pTab
->tabFlags
|= TF_HasPrimaryKey
;
1848 iCol
= pTab
->nCol
- 1;
1849 pCol
= &pTab
->aCol
[iCol
];
1850 makeColumnPartOfPrimaryKey(pParse
, pCol
);
1853 nTerm
= pList
->nExpr
;
1854 for(i
=0; i
<nTerm
; i
++){
1855 Expr
*pCExpr
= sqlite3ExprSkipCollate(pList
->a
[i
].pExpr
);
1856 assert( pCExpr
!=0 );
1857 sqlite3StringToId(pCExpr
);
1858 if( pCExpr
->op
==TK_ID
){
1860 assert( !ExprHasProperty(pCExpr
, EP_IntValue
) );
1861 zCName
= pCExpr
->u
.zToken
;
1862 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
1863 if( sqlite3StrICmp(zCName
, pTab
->aCol
[iCol
].zCnName
)==0 ){
1864 pCol
= &pTab
->aCol
[iCol
];
1865 makeColumnPartOfPrimaryKey(pParse
, pCol
);
1874 && pCol
->eCType
==COLTYPE_INTEGER
1875 && sortOrder
!=SQLITE_SO_DESC
1877 if( IN_RENAME_OBJECT
&& pList
){
1878 Expr
*pCExpr
= sqlite3ExprSkipCollate(pList
->a
[0].pExpr
);
1879 sqlite3RenameTokenRemap(pParse
, &pTab
->iPKey
, pCExpr
);
1882 pTab
->keyConf
= (u8
)onError
;
1883 assert( autoInc
==0 || autoInc
==1 );
1884 pTab
->tabFlags
|= autoInc
*TF_Autoincrement
;
1885 if( pList
) pParse
->iPkSortOrder
= pList
->a
[0].fg
.sortFlags
;
1886 (void)sqlite3HasExplicitNulls(pParse
, pList
);
1887 }else if( autoInc
){
1888 #ifndef SQLITE_OMIT_AUTOINCREMENT
1889 sqlite3ErrorMsg(pParse
, "AUTOINCREMENT is only allowed on an "
1890 "INTEGER PRIMARY KEY");
1893 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, onError
, 0,
1894 0, sortOrder
, 0, SQLITE_IDXTYPE_PRIMARYKEY
);
1899 sqlite3ExprListDelete(pParse
->db
, pList
);
1904 ** Add a new CHECK constraint to the table currently under construction.
1906 void sqlite3AddCheckConstraint(
1907 Parse
*pParse
, /* Parsing context */
1908 Expr
*pCheckExpr
, /* The check expression */
1909 const char *zStart
, /* Opening "(" */
1910 const char *zEnd
/* Closing ")" */
1912 #ifndef SQLITE_OMIT_CHECK
1913 Table
*pTab
= pParse
->pNewTable
;
1914 sqlite3
*db
= pParse
->db
;
1915 if( pTab
&& !IN_DECLARE_VTAB
1916 && !sqlite3BtreeIsReadonly(db
->aDb
[db
->init
.iDb
].pBt
)
1918 pTab
->pCheck
= sqlite3ExprListAppend(pParse
, pTab
->pCheck
, pCheckExpr
);
1919 if( pParse
->constraintName
.n
){
1920 sqlite3ExprListSetName(pParse
, pTab
->pCheck
, &pParse
->constraintName
, 1);
1923 for(zStart
++; sqlite3Isspace(zStart
[0]); zStart
++){}
1924 while( sqlite3Isspace(zEnd
[-1]) ){ zEnd
--; }
1926 t
.n
= (int)(zEnd
- t
.z
);
1927 sqlite3ExprListSetName(pParse
, pTab
->pCheck
, &t
, 1);
1932 sqlite3ExprDelete(pParse
->db
, pCheckExpr
);
1937 ** Set the collation function of the most recently parsed table column
1938 ** to the CollSeq given.
1940 void sqlite3AddCollateType(Parse
*pParse
, Token
*pToken
){
1943 char *zColl
; /* Dequoted name of collation sequence */
1946 if( (p
= pParse
->pNewTable
)==0 || IN_RENAME_OBJECT
) return;
1949 zColl
= sqlite3NameFromToken(db
, pToken
);
1950 if( !zColl
) return;
1952 if( sqlite3LocateCollSeq(pParse
, zColl
) ){
1954 sqlite3ColumnSetColl(db
, &p
->aCol
[i
], zColl
);
1956 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1957 ** then an index may have been created on this column before the
1958 ** collation type was added. Correct this if it is the case.
1960 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1961 assert( pIdx
->nKeyCol
==1 );
1962 if( pIdx
->aiColumn
[0]==i
){
1963 pIdx
->azColl
[0] = sqlite3ColumnColl(&p
->aCol
[i
]);
1967 sqlite3DbFree(db
, zColl
);
1970 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1973 void sqlite3AddGenerated(Parse
*pParse
, Expr
*pExpr
, Token
*pType
){
1974 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1975 u8 eType
= COLFLAG_VIRTUAL
;
1976 Table
*pTab
= pParse
->pNewTable
;
1979 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1980 goto generated_done
;
1982 pCol
= &(pTab
->aCol
[pTab
->nCol
-1]);
1983 if( IN_DECLARE_VTAB
){
1984 sqlite3ErrorMsg(pParse
, "virtual tables cannot use computed columns");
1985 goto generated_done
;
1987 if( pCol
->iDflt
>0 ) goto generated_error
;
1989 if( pType
->n
==7 && sqlite3StrNICmp("virtual",pType
->z
,7)==0 ){
1991 }else if( pType
->n
==6 && sqlite3StrNICmp("stored",pType
->z
,6)==0 ){
1992 eType
= COLFLAG_STORED
;
1994 goto generated_error
;
1997 if( eType
==COLFLAG_VIRTUAL
) pTab
->nNVCol
--;
1998 pCol
->colFlags
|= eType
;
1999 assert( TF_HasVirtual
==COLFLAG_VIRTUAL
);
2000 assert( TF_HasStored
==COLFLAG_STORED
);
2001 pTab
->tabFlags
|= eType
;
2002 if( pCol
->colFlags
& COLFLAG_PRIMKEY
){
2003 makeColumnPartOfPrimaryKey(pParse
, pCol
); /* For the error message */
2005 if( ALWAYS(pExpr
) && pExpr
->op
==TK_ID
){
2006 /* The value of a generated column needs to be a real expression, not
2007 ** just a reference to another column, in order for covering index
2008 ** optimizations to work correctly. So if the value is not an expression,
2009 ** turn it into one by adding a unary "+" operator. */
2010 pExpr
= sqlite3PExpr(pParse
, TK_UPLUS
, pExpr
, 0);
2012 if( pExpr
&& pExpr
->op
!=TK_RAISE
) pExpr
->affExpr
= pCol
->affinity
;
2013 sqlite3ColumnSetExpr(pParse
, pTab
, pCol
, pExpr
);
2015 goto generated_done
;
2018 sqlite3ErrorMsg(pParse
, "error in generated column \"%s\"",
2021 sqlite3ExprDelete(pParse
->db
, pExpr
);
2023 /* Throw and error for the GENERATED ALWAYS AS clause if the
2024 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
2025 sqlite3ErrorMsg(pParse
, "generated columns not supported");
2026 sqlite3ExprDelete(pParse
->db
, pExpr
);
2031 ** Generate code that will increment the schema cookie.
2033 ** The schema cookie is used to determine when the schema for the
2034 ** database changes. After each schema change, the cookie value
2035 ** changes. When a process first reads the schema it records the
2036 ** cookie. Thereafter, whenever it goes to access the database,
2037 ** it checks the cookie to make sure the schema has not changed
2038 ** since it was last read.
2040 ** This plan is not completely bullet-proof. It is possible for
2041 ** the schema to change multiple times and for the cookie to be
2042 ** set back to prior value. But schema changes are infrequent
2043 ** and the probability of hitting the same cookie value is only
2044 ** 1 chance in 2^32. So we're safe enough.
2046 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
2047 ** the schema-version whenever the schema changes.
2049 void sqlite3ChangeCookie(Parse
*pParse
, int iDb
){
2050 sqlite3
*db
= pParse
->db
;
2051 Vdbe
*v
= pParse
->pVdbe
;
2052 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2053 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_SCHEMA_VERSION
,
2054 (int)(1+(unsigned)db
->aDb
[iDb
].pSchema
->schema_cookie
));
2058 ** Measure the number of characters needed to output the given
2059 ** identifier. The number returned includes any quotes used
2060 ** but does not include the null terminator.
2062 ** The estimate is conservative. It might be larger that what is
2065 static int identLength(const char *z
){
2067 for(n
=0; *z
; n
++, z
++){
2068 if( *z
=='"' ){ n
++; }
2074 ** The first parameter is a pointer to an output buffer. The second
2075 ** parameter is a pointer to an integer that contains the offset at
2076 ** which to write into the output buffer. This function copies the
2077 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
2078 ** to the specified offset in the buffer and updates *pIdx to refer
2079 ** to the first byte after the last byte written before returning.
2081 ** If the string zSignedIdent consists entirely of alphanumeric
2082 ** characters, does not begin with a digit and is not an SQL keyword,
2083 ** then it is copied to the output buffer exactly as it is. Otherwise,
2084 ** it is quoted using double-quotes.
2086 static void identPut(char *z
, int *pIdx
, char *zSignedIdent
){
2087 unsigned char *zIdent
= (unsigned char*)zSignedIdent
;
2088 int i
, j
, needQuote
;
2091 for(j
=0; zIdent
[j
]; j
++){
2092 if( !sqlite3Isalnum(zIdent
[j
]) && zIdent
[j
]!='_' ) break;
2094 needQuote
= sqlite3Isdigit(zIdent
[0])
2095 || sqlite3KeywordCode(zIdent
, j
)!=TK_ID
2099 if( needQuote
) z
[i
++] = '"';
2100 for(j
=0; zIdent
[j
]; j
++){
2102 if( zIdent
[j
]=='"' ) z
[i
++] = '"';
2104 if( needQuote
) z
[i
++] = '"';
2110 ** Generate a CREATE TABLE statement appropriate for the given
2111 ** table. Memory to hold the text of the statement is obtained
2112 ** from sqliteMalloc() and must be freed by the calling function.
2114 static char *createTableStmt(sqlite3
*db
, Table
*p
){
2117 char *zSep
, *zSep2
, *zEnd
;
2120 for(pCol
= p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
2121 n
+= identLength(pCol
->zCnName
) + 5;
2123 n
+= identLength(p
->zName
);
2133 n
+= 35 + 6*p
->nCol
;
2134 zStmt
= sqlite3DbMallocRaw(0, n
);
2136 sqlite3OomFault(db
);
2139 sqlite3_snprintf(n
, zStmt
, "CREATE TABLE ");
2140 k
= sqlite3Strlen30(zStmt
);
2141 identPut(zStmt
, &k
, p
->zName
);
2143 for(pCol
=p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
2144 static const char * const azType
[] = {
2145 /* SQLITE_AFF_BLOB */ "",
2146 /* SQLITE_AFF_TEXT */ " TEXT",
2147 /* SQLITE_AFF_NUMERIC */ " NUM",
2148 /* SQLITE_AFF_INTEGER */ " INT",
2149 /* SQLITE_AFF_REAL */ " REAL",
2150 /* SQLITE_AFF_FLEXNUM */ " NUM",
2155 sqlite3_snprintf(n
-k
, &zStmt
[k
], zSep
);
2156 k
+= sqlite3Strlen30(&zStmt
[k
]);
2158 identPut(zStmt
, &k
, pCol
->zCnName
);
2159 assert( pCol
->affinity
-SQLITE_AFF_BLOB
>= 0 );
2160 assert( pCol
->affinity
-SQLITE_AFF_BLOB
< ArraySize(azType
) );
2161 testcase( pCol
->affinity
==SQLITE_AFF_BLOB
);
2162 testcase( pCol
->affinity
==SQLITE_AFF_TEXT
);
2163 testcase( pCol
->affinity
==SQLITE_AFF_NUMERIC
);
2164 testcase( pCol
->affinity
==SQLITE_AFF_INTEGER
);
2165 testcase( pCol
->affinity
==SQLITE_AFF_REAL
);
2166 testcase( pCol
->affinity
==SQLITE_AFF_FLEXNUM
);
2168 zType
= azType
[pCol
->affinity
- SQLITE_AFF_BLOB
];
2169 len
= sqlite3Strlen30(zType
);
2170 assert( pCol
->affinity
==SQLITE_AFF_BLOB
2171 || pCol
->affinity
==SQLITE_AFF_FLEXNUM
2172 || pCol
->affinity
==sqlite3AffinityType(zType
, 0) );
2173 memcpy(&zStmt
[k
], zType
, len
);
2177 sqlite3_snprintf(n
-k
, &zStmt
[k
], "%s", zEnd
);
2182 ** Resize an Index object to hold N columns total. Return SQLITE_OK
2183 ** on success and SQLITE_NOMEM on an OOM error.
2185 static int resizeIndexObject(sqlite3
*db
, Index
*pIdx
, int N
){
2188 if( pIdx
->nColumn
>=N
) return SQLITE_OK
;
2189 assert( pIdx
->isResized
==0 );
2190 nByte
= (sizeof(char*) + sizeof(LogEst
) + sizeof(i16
) + 1)*N
;
2191 zExtra
= sqlite3DbMallocZero(db
, nByte
);
2192 if( zExtra
==0 ) return SQLITE_NOMEM_BKPT
;
2193 memcpy(zExtra
, pIdx
->azColl
, sizeof(char*)*pIdx
->nColumn
);
2194 pIdx
->azColl
= (const char**)zExtra
;
2195 zExtra
+= sizeof(char*)*N
;
2196 memcpy(zExtra
, pIdx
->aiRowLogEst
, sizeof(LogEst
)*(pIdx
->nKeyCol
+1));
2197 pIdx
->aiRowLogEst
= (LogEst
*)zExtra
;
2198 zExtra
+= sizeof(LogEst
)*N
;
2199 memcpy(zExtra
, pIdx
->aiColumn
, sizeof(i16
)*pIdx
->nColumn
);
2200 pIdx
->aiColumn
= (i16
*)zExtra
;
2201 zExtra
+= sizeof(i16
)*N
;
2202 memcpy(zExtra
, pIdx
->aSortOrder
, pIdx
->nColumn
);
2203 pIdx
->aSortOrder
= (u8
*)zExtra
;
2205 pIdx
->isResized
= 1;
2210 ** Estimate the total row width for a table.
2212 static void estimateTableWidth(Table
*pTab
){
2213 unsigned wTable
= 0;
2214 const Column
*pTabCol
;
2216 for(i
=pTab
->nCol
, pTabCol
=pTab
->aCol
; i
>0; i
--, pTabCol
++){
2217 wTable
+= pTabCol
->szEst
;
2219 if( pTab
->iPKey
<0 ) wTable
++;
2220 pTab
->szTabRow
= sqlite3LogEst(wTable
*4);
2224 ** Estimate the average size of a row for an index.
2226 static void estimateIndexWidth(Index
*pIdx
){
2227 unsigned wIndex
= 0;
2229 const Column
*aCol
= pIdx
->pTable
->aCol
;
2230 for(i
=0; i
<pIdx
->nColumn
; i
++){
2231 i16 x
= pIdx
->aiColumn
[i
];
2232 assert( x
<pIdx
->pTable
->nCol
);
2233 wIndex
+= x
<0 ? 1 : aCol
[x
].szEst
;
2235 pIdx
->szIdxRow
= sqlite3LogEst(wIndex
*4);
2238 /* Return true if column number x is any of the first nCol entries of aiCol[].
2239 ** This is used to determine if the column number x appears in any of the
2240 ** first nCol entries of an index.
2242 static int hasColumn(const i16
*aiCol
, int nCol
, int x
){
2243 while( nCol
-- > 0 ){
2244 if( x
==*(aiCol
++) ){
2252 ** Return true if any of the first nKey entries of index pIdx exactly
2253 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
2254 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
2255 ** or may not be the same index as pPk.
2257 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2258 ** not a rowid or expression.
2260 ** This routine differs from hasColumn() in that both the column and the
2261 ** collating sequence must match for this routine, but for hasColumn() only
2262 ** the column name must match.
2264 static int isDupColumn(Index
*pIdx
, int nKey
, Index
*pPk
, int iCol
){
2266 assert( nKey
<=pIdx
->nColumn
);
2267 assert( iCol
<MAX(pPk
->nColumn
,pPk
->nKeyCol
) );
2268 assert( pPk
->idxType
==SQLITE_IDXTYPE_PRIMARYKEY
);
2269 assert( pPk
->pTable
->tabFlags
& TF_WithoutRowid
);
2270 assert( pPk
->pTable
==pIdx
->pTable
);
2271 testcase( pPk
==pIdx
);
2272 j
= pPk
->aiColumn
[iCol
];
2273 assert( j
!=XN_ROWID
&& j
!=XN_EXPR
);
2274 for(i
=0; i
<nKey
; i
++){
2275 assert( pIdx
->aiColumn
[i
]>=0 || j
>=0 );
2276 if( pIdx
->aiColumn
[i
]==j
2277 && sqlite3StrICmp(pIdx
->azColl
[i
], pPk
->azColl
[iCol
])==0
2285 /* Recompute the colNotIdxed field of the Index.
2287 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2288 ** columns that are within the first 63 columns of the table and a 1 for
2289 ** all other bits (all columns that are not in the index). The
2290 ** high-order bit of colNotIdxed is always 1. All unindexed columns
2291 ** of the table have a 1.
2293 ** 2019-10-24: For the purpose of this computation, virtual columns are
2294 ** not considered to be covered by the index, even if they are in the
2295 ** index, because we do not trust the logic in whereIndexExprTrans() to be
2296 ** able to find all instances of a reference to the indexed table column
2297 ** and convert them into references to the index. Hence we always want
2298 ** the actual table at hand in order to recompute the virtual column, if
2301 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2302 ** to determine if the index is covering index.
2304 static void recomputeColumnsNotIndexed(Index
*pIdx
){
2307 Table
*pTab
= pIdx
->pTable
;
2308 for(j
=pIdx
->nColumn
-1; j
>=0; j
--){
2309 int x
= pIdx
->aiColumn
[j
];
2310 if( x
>=0 && (pTab
->aCol
[x
].colFlags
& COLFLAG_VIRTUAL
)==0 ){
2311 testcase( x
==BMS
-1 );
2312 testcase( x
==BMS
-2 );
2313 if( x
<BMS
-1 ) m
|= MASKBIT(x
);
2316 pIdx
->colNotIdxed
= ~m
;
2317 assert( (pIdx
->colNotIdxed
>>63)==1 ); /* See note-20221022-a */
2321 ** This routine runs at the end of parsing a CREATE TABLE statement that
2322 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
2323 ** internal schema data structures and the generated VDBE code so that they
2324 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2327 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2328 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2329 ** into BTREE_BLOBKEY.
2330 ** (3) Bypass the creation of the sqlite_schema table entry
2331 ** for the PRIMARY KEY as the primary key index is now
2332 ** identified by the sqlite_schema table entry of the table itself.
2333 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
2334 ** schema to the rootpage from the main table.
2335 ** (5) Add all table columns to the PRIMARY KEY Index object
2336 ** so that the PRIMARY KEY is a covering index. The surplus
2337 ** columns are part of KeyInfo.nAllField and are not used for
2338 ** sorting or lookup or uniqueness checks.
2339 ** (6) Replace the rowid tail on all automatically generated UNIQUE
2340 ** indices with the PRIMARY KEY columns.
2342 ** For virtual tables, only (1) is performed.
2344 static void convertToWithoutRowidTable(Parse
*pParse
, Table
*pTab
){
2350 sqlite3
*db
= pParse
->db
;
2351 Vdbe
*v
= pParse
->pVdbe
;
2353 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2355 if( !db
->init
.imposterTable
){
2356 for(i
=0; i
<pTab
->nCol
; i
++){
2357 if( (pTab
->aCol
[i
].colFlags
& COLFLAG_PRIMKEY
)!=0
2358 && (pTab
->aCol
[i
].notNull
==OE_None
)
2360 pTab
->aCol
[i
].notNull
= OE_Abort
;
2363 pTab
->tabFlags
|= TF_HasNotNull
;
2366 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2367 ** into BTREE_BLOBKEY.
2369 assert( !pParse
->bReturning
);
2370 if( pParse
->u1
.addrCrTab
){
2372 sqlite3VdbeChangeP3(v
, pParse
->u1
.addrCrTab
, BTREE_BLOBKEY
);
2375 /* Locate the PRIMARY KEY index. Or, if this table was originally
2376 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2378 if( pTab
->iPKey
>=0 ){
2381 sqlite3TokenInit(&ipkToken
, pTab
->aCol
[pTab
->iPKey
].zCnName
);
2382 pList
= sqlite3ExprListAppend(pParse
, 0,
2383 sqlite3ExprAlloc(db
, TK_ID
, &ipkToken
, 0));
2385 pTab
->tabFlags
&= ~TF_WithoutRowid
;
2388 if( IN_RENAME_OBJECT
){
2389 sqlite3RenameTokenRemap(pParse
, pList
->a
[0].pExpr
, &pTab
->iPKey
);
2391 pList
->a
[0].fg
.sortFlags
= pParse
->iPkSortOrder
;
2392 assert( pParse
->pNewTable
==pTab
);
2394 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, pTab
->keyConf
, 0, 0, 0, 0,
2395 SQLITE_IDXTYPE_PRIMARYKEY
);
2397 pTab
->tabFlags
&= ~TF_WithoutRowid
;
2400 assert( db
->mallocFailed
==0 );
2401 pPk
= sqlite3PrimaryKeyIndex(pTab
);
2402 assert( pPk
->nKeyCol
==1 );
2404 pPk
= sqlite3PrimaryKeyIndex(pTab
);
2408 ** Remove all redundant columns from the PRIMARY KEY. For example, change
2409 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
2410 ** code assumes the PRIMARY KEY contains no repeated columns.
2412 for(i
=j
=1; i
<pPk
->nKeyCol
; i
++){
2413 if( isDupColumn(pPk
, j
, pPk
, i
) ){
2416 testcase( hasColumn(pPk
->aiColumn
, j
, pPk
->aiColumn
[i
]) );
2417 pPk
->azColl
[j
] = pPk
->azColl
[i
];
2418 pPk
->aSortOrder
[j
] = pPk
->aSortOrder
[i
];
2419 pPk
->aiColumn
[j
++] = pPk
->aiColumn
[i
];
2425 pPk
->isCovering
= 1;
2426 if( !db
->init
.imposterTable
) pPk
->uniqNotNull
= 1;
2427 nPk
= pPk
->nColumn
= pPk
->nKeyCol
;
2429 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2430 ** table entry. This is only required if currently generating VDBE
2431 ** code for a CREATE TABLE (not when parsing one as part of reading
2432 ** a database schema). */
2433 if( v
&& pPk
->tnum
>0 ){
2434 assert( db
->init
.busy
==0 );
2435 sqlite3VdbeChangeOpcode(v
, (int)pPk
->tnum
, OP_Goto
);
2438 /* The root page of the PRIMARY KEY is the table root page */
2439 pPk
->tnum
= pTab
->tnum
;
2441 /* Update the in-memory representation of all UNIQUE indices by converting
2442 ** the final rowid column into one or more columns of the PRIMARY KEY.
2444 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2446 if( IsPrimaryKeyIndex(pIdx
) ) continue;
2447 for(i
=n
=0; i
<nPk
; i
++){
2448 if( !isDupColumn(pIdx
, pIdx
->nKeyCol
, pPk
, i
) ){
2449 testcase( hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) );
2454 /* This index is a superset of the primary key */
2455 pIdx
->nColumn
= pIdx
->nKeyCol
;
2458 if( resizeIndexObject(db
, pIdx
, pIdx
->nKeyCol
+n
) ) return;
2459 for(i
=0, j
=pIdx
->nKeyCol
; i
<nPk
; i
++){
2460 if( !isDupColumn(pIdx
, pIdx
->nKeyCol
, pPk
, i
) ){
2461 testcase( hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) );
2462 pIdx
->aiColumn
[j
] = pPk
->aiColumn
[i
];
2463 pIdx
->azColl
[j
] = pPk
->azColl
[i
];
2464 if( pPk
->aSortOrder
[i
] ){
2465 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2466 pIdx
->bAscKeyBug
= 1;
2471 assert( pIdx
->nColumn
>=pIdx
->nKeyCol
+n
);
2472 assert( pIdx
->nColumn
>=j
);
2475 /* Add all table columns to the PRIMARY KEY index
2478 for(i
=0; i
<pTab
->nCol
; i
++){
2479 if( !hasColumn(pPk
->aiColumn
, nPk
, i
)
2480 && (pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
)==0 ) nExtra
++;
2482 if( resizeIndexObject(db
, pPk
, nPk
+nExtra
) ) return;
2483 for(i
=0, j
=nPk
; i
<pTab
->nCol
; i
++){
2484 if( !hasColumn(pPk
->aiColumn
, j
, i
)
2485 && (pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
)==0
2487 assert( j
<pPk
->nColumn
);
2488 pPk
->aiColumn
[j
] = i
;
2489 pPk
->azColl
[j
] = sqlite3StrBINARY
;
2493 assert( pPk
->nColumn
==j
);
2494 assert( pTab
->nNVCol
<=j
);
2495 recomputeColumnsNotIndexed(pPk
);
2499 #ifndef SQLITE_OMIT_VIRTUALTABLE
2501 ** Return true if pTab is a virtual table and zName is a shadow table name
2502 ** for that virtual table.
2504 int sqlite3IsShadowTableOf(sqlite3
*db
, Table
*pTab
, const char *zName
){
2505 int nName
; /* Length of zName */
2506 Module
*pMod
; /* Module for the virtual table */
2508 if( !IsVirtual(pTab
) ) return 0;
2509 nName
= sqlite3Strlen30(pTab
->zName
);
2510 if( sqlite3_strnicmp(zName
, pTab
->zName
, nName
)!=0 ) return 0;
2511 if( zName
[nName
]!='_' ) return 0;
2512 pMod
= (Module
*)sqlite3HashFind(&db
->aModule
, pTab
->u
.vtab
.azArg
[0]);
2513 if( pMod
==0 ) return 0;
2514 if( pMod
->pModule
->iVersion
<3 ) return 0;
2515 if( pMod
->pModule
->xShadowName
==0 ) return 0;
2516 return pMod
->pModule
->xShadowName(zName
+nName
+1);
2518 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2520 #ifndef SQLITE_OMIT_VIRTUALTABLE
2522 ** Table pTab is a virtual table. If it the virtual table implementation
2523 ** exists and has an xShadowName method, then loop over all other ordinary
2524 ** tables within the same schema looking for shadow tables of pTab, and mark
2525 ** any shadow tables seen using the TF_Shadow flag.
2527 void sqlite3MarkAllShadowTablesOf(sqlite3
*db
, Table
*pTab
){
2528 int nName
; /* Length of pTab->zName */
2529 Module
*pMod
; /* Module for the virtual table */
2530 HashElem
*k
; /* For looping through the symbol table */
2532 assert( IsVirtual(pTab
) );
2533 pMod
= (Module
*)sqlite3HashFind(&db
->aModule
, pTab
->u
.vtab
.azArg
[0]);
2534 if( pMod
==0 ) return;
2535 if( NEVER(pMod
->pModule
==0) ) return;
2536 if( pMod
->pModule
->iVersion
<3 ) return;
2537 if( pMod
->pModule
->xShadowName
==0 ) return;
2538 assert( pTab
->zName
!=0 );
2539 nName
= sqlite3Strlen30(pTab
->zName
);
2540 for(k
=sqliteHashFirst(&pTab
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
2541 Table
*pOther
= sqliteHashData(k
);
2542 assert( pOther
->zName
!=0 );
2543 if( !IsOrdinaryTable(pOther
) ) continue;
2544 if( pOther
->tabFlags
& TF_Shadow
) continue;
2545 if( sqlite3StrNICmp(pOther
->zName
, pTab
->zName
, nName
)==0
2546 && pOther
->zName
[nName
]=='_'
2547 && pMod
->pModule
->xShadowName(pOther
->zName
+nName
+1)
2549 pOther
->tabFlags
|= TF_Shadow
;
2553 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2555 #ifndef SQLITE_OMIT_VIRTUALTABLE
2557 ** Return true if zName is a shadow table name in the current database
2560 ** zName is temporarily modified while this routine is running, but is
2561 ** restored to its original value prior to this routine returning.
2563 int sqlite3ShadowTableName(sqlite3
*db
, const char *zName
){
2564 char *zTail
; /* Pointer to the last "_" in zName */
2565 Table
*pTab
; /* Table that zName is a shadow of */
2566 zTail
= strrchr(zName
, '_');
2567 if( zTail
==0 ) return 0;
2569 pTab
= sqlite3FindTable(db
, zName
, 0);
2571 if( pTab
==0 ) return 0;
2572 if( !IsVirtual(pTab
) ) return 0;
2573 return sqlite3IsShadowTableOf(db
, pTab
, zName
);
2575 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2580 ** Mark all nodes of an expression as EP_Immutable, indicating that
2581 ** they should not be changed. Expressions attached to a table or
2582 ** index definition are tagged this way to help ensure that we do
2583 ** not pass them into code generator routines by mistake.
2585 static int markImmutableExprStep(Walker
*pWalker
, Expr
*pExpr
){
2587 ExprSetVVAProperty(pExpr
, EP_Immutable
);
2588 return WRC_Continue
;
2590 static void markExprListImmutable(ExprList
*pList
){
2593 memset(&w
, 0, sizeof(w
));
2594 w
.xExprCallback
= markImmutableExprStep
;
2595 w
.xSelectCallback
= sqlite3SelectWalkNoop
;
2596 w
.xSelectCallback2
= 0;
2597 sqlite3WalkExprList(&w
, pList
);
2601 #define markExprListImmutable(X) /* no-op */
2602 #endif /* SQLITE_DEBUG */
2606 ** This routine is called to report the final ")" that terminates
2607 ** a CREATE TABLE statement.
2609 ** The table structure that other action routines have been building
2610 ** is added to the internal hash tables, assuming no errors have
2613 ** An entry for the table is made in the schema table on disk, unless
2614 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
2615 ** it means we are reading the sqlite_schema table because we just
2616 ** connected to the database or because the sqlite_schema table has
2617 ** recently changed, so the entry for this table already exists in
2618 ** the sqlite_schema table. We do not want to create it again.
2620 ** If the pSelect argument is not NULL, it means that this routine
2621 ** was called to create a table generated from a
2622 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2623 ** the new table will match the result set of the SELECT.
2625 void sqlite3EndTable(
2626 Parse
*pParse
, /* Parse context */
2627 Token
*pCons
, /* The ',' token after the last column defn. */
2628 Token
*pEnd
, /* The ')' before options in the CREATE TABLE */
2629 u32 tabOpts
, /* Extra table options. Usually 0. */
2630 Select
*pSelect
/* Select from a "CREATE ... AS SELECT" */
2632 Table
*p
; /* The new table */
2633 sqlite3
*db
= pParse
->db
; /* The database connection */
2634 int iDb
; /* Database in which the table lives */
2635 Index
*pIdx
; /* An implied index of the table */
2637 if( pEnd
==0 && pSelect
==0 ){
2640 p
= pParse
->pNewTable
;
2643 if( pSelect
==0 && sqlite3ShadowTableName(db
, p
->zName
) ){
2644 p
->tabFlags
|= TF_Shadow
;
2647 /* If the db->init.busy is 1 it means we are reading the SQL off the
2648 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2649 ** So do not write to the disk again. Extract the root page number
2650 ** for the table from the db->init.newTnum field. (The page number
2651 ** should have been put there by the sqliteOpenCb routine.)
2653 ** If the root page number is 1, that means this is the sqlite_schema
2654 ** table itself. So mark it read-only.
2656 if( db
->init
.busy
){
2657 if( pSelect
|| (!IsOrdinaryTable(p
) && db
->init
.newTnum
) ){
2658 sqlite3ErrorMsg(pParse
, "");
2661 p
->tnum
= db
->init
.newTnum
;
2662 if( p
->tnum
==1 ) p
->tabFlags
|= TF_Readonly
;
2665 /* Special processing for tables that include the STRICT keyword:
2667 ** * Do not allow custom column datatypes. Every column must have
2668 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
2670 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
2671 ** then all columns of the PRIMARY KEY must have a NOT NULL
2674 if( tabOpts
& TF_Strict
){
2676 p
->tabFlags
|= TF_Strict
;
2677 for(ii
=0; ii
<p
->nCol
; ii
++){
2678 Column
*pCol
= &p
->aCol
[ii
];
2679 if( pCol
->eCType
==COLTYPE_CUSTOM
){
2680 if( pCol
->colFlags
& COLFLAG_HASTYPE
){
2681 sqlite3ErrorMsg(pParse
,
2682 "unknown datatype for %s.%s: \"%s\"",
2683 p
->zName
, pCol
->zCnName
, sqlite3ColumnType(pCol
, "")
2686 sqlite3ErrorMsg(pParse
, "missing datatype for %s.%s",
2687 p
->zName
, pCol
->zCnName
);
2690 }else if( pCol
->eCType
==COLTYPE_ANY
){
2691 pCol
->affinity
= SQLITE_AFF_BLOB
;
2693 if( (pCol
->colFlags
& COLFLAG_PRIMKEY
)!=0
2695 && pCol
->notNull
== OE_None
2697 pCol
->notNull
= OE_Abort
;
2698 p
->tabFlags
|= TF_HasNotNull
;
2703 assert( (p
->tabFlags
& TF_HasPrimaryKey
)==0
2704 || p
->iPKey
>=0 || sqlite3PrimaryKeyIndex(p
)!=0 );
2705 assert( (p
->tabFlags
& TF_HasPrimaryKey
)!=0
2706 || (p
->iPKey
<0 && sqlite3PrimaryKeyIndex(p
)==0) );
2708 /* Special processing for WITHOUT ROWID Tables */
2709 if( tabOpts
& TF_WithoutRowid
){
2710 if( (p
->tabFlags
& TF_Autoincrement
) ){
2711 sqlite3ErrorMsg(pParse
,
2712 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2715 if( (p
->tabFlags
& TF_HasPrimaryKey
)==0 ){
2716 sqlite3ErrorMsg(pParse
, "PRIMARY KEY missing on table %s", p
->zName
);
2719 p
->tabFlags
|= TF_WithoutRowid
| TF_NoVisibleRowid
;
2720 convertToWithoutRowidTable(pParse
, p
);
2722 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
2724 #ifndef SQLITE_OMIT_CHECK
2725 /* Resolve names in all CHECK constraint expressions.
2728 sqlite3ResolveSelfReference(pParse
, p
, NC_IsCheck
, 0, p
->pCheck
);
2730 /* If errors are seen, delete the CHECK constraints now, else they might
2731 ** actually be used if PRAGMA writable_schema=ON is set. */
2732 sqlite3ExprListDelete(db
, p
->pCheck
);
2735 markExprListImmutable(p
->pCheck
);
2738 #endif /* !defined(SQLITE_OMIT_CHECK) */
2739 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2740 if( p
->tabFlags
& TF_HasGenerated
){
2742 testcase( p
->tabFlags
& TF_HasVirtual
);
2743 testcase( p
->tabFlags
& TF_HasStored
);
2744 for(ii
=0; ii
<p
->nCol
; ii
++){
2745 u32 colFlags
= p
->aCol
[ii
].colFlags
;
2746 if( (colFlags
& COLFLAG_GENERATED
)!=0 ){
2747 Expr
*pX
= sqlite3ColumnExpr(p
, &p
->aCol
[ii
]);
2748 testcase( colFlags
& COLFLAG_VIRTUAL
);
2749 testcase( colFlags
& COLFLAG_STORED
);
2750 if( sqlite3ResolveSelfReference(pParse
, p
, NC_GenCol
, pX
, 0) ){
2751 /* If there are errors in resolving the expression, change the
2752 ** expression to a NULL. This prevents code generators that operate
2753 ** on the expression from inserting extra parts into the expression
2754 ** tree that have been allocated from lookaside memory, which is
2755 ** illegal in a schema and will lead to errors or heap corruption
2756 ** when the database connection closes. */
2757 sqlite3ColumnSetExpr(pParse
, p
, &p
->aCol
[ii
],
2758 sqlite3ExprAlloc(db
, TK_NULL
, 0, 0));
2765 sqlite3ErrorMsg(pParse
, "must have at least one non-generated column");
2771 /* Estimate the average row size for the table and for all implied indices */
2772 estimateTableWidth(p
);
2773 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2774 estimateIndexWidth(pIdx
);
2777 /* If not initializing, then create a record for the new table
2778 ** in the schema table of the database.
2780 ** If this is a TEMPORARY table, write the entry into the auxiliary
2781 ** file instead of into the main database file.
2783 if( !db
->init
.busy
){
2786 char *zType
; /* "view" or "table" */
2787 char *zType2
; /* "VIEW" or "TABLE" */
2788 char *zStmt
; /* Text of the CREATE TABLE or CREATE VIEW statement */
2790 v
= sqlite3GetVdbe(pParse
);
2791 if( NEVER(v
==0) ) return;
2793 sqlite3VdbeAddOp1(v
, OP_Close
, 0);
2796 ** Initialize zType for the new view or table.
2798 if( IsOrdinaryTable(p
) ){
2799 /* A regular table */
2802 #ifndef SQLITE_OMIT_VIEW
2810 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2811 ** statement to populate the new table. The root-page number for the
2812 ** new table is in register pParse->regRoot.
2814 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2815 ** suitable state to query for the column names and types to be used
2816 ** by the new table.
2818 ** A shared-cache write-lock is not required to write to the new table,
2819 ** as a schema-lock must have already been obtained to create it. Since
2820 ** a schema-lock excludes all other database users, the write-lock would
2824 SelectDest dest
; /* Where the SELECT should store results */
2825 int regYield
; /* Register holding co-routine entry-point */
2826 int addrTop
; /* Top of the co-routine */
2827 int regRec
; /* A record to be insert into the new table */
2828 int regRowid
; /* Rowid of the next row to insert */
2829 int addrInsLoop
; /* Top of the loop for inserting rows */
2830 Table
*pSelTab
; /* A table that describes the SELECT results */
2832 if( IN_SPECIAL_PARSE
){
2833 pParse
->rc
= SQLITE_ERROR
;
2837 regYield
= ++pParse
->nMem
;
2838 regRec
= ++pParse
->nMem
;
2839 regRowid
= ++pParse
->nMem
;
2840 assert(pParse
->nTab
==1);
2841 sqlite3MayAbort(pParse
);
2842 sqlite3VdbeAddOp3(v
, OP_OpenWrite
, 1, pParse
->regRoot
, iDb
);
2843 sqlite3VdbeChangeP5(v
, OPFLAG_P2ISREG
);
2845 addrTop
= sqlite3VdbeCurrentAddr(v
) + 1;
2846 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, addrTop
);
2847 if( pParse
->nErr
) return;
2848 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSelect
, SQLITE_AFF_BLOB
);
2849 if( pSelTab
==0 ) return;
2850 assert( p
->aCol
==0 );
2851 p
->nCol
= p
->nNVCol
= pSelTab
->nCol
;
2852 p
->aCol
= pSelTab
->aCol
;
2855 sqlite3DeleteTable(db
, pSelTab
);
2856 sqlite3SelectDestInit(&dest
, SRT_Coroutine
, regYield
);
2857 sqlite3Select(pParse
, pSelect
, &dest
);
2858 if( pParse
->nErr
) return;
2859 sqlite3VdbeEndCoroutine(v
, regYield
);
2860 sqlite3VdbeJumpHere(v
, addrTop
- 1);
2861 addrInsLoop
= sqlite3VdbeAddOp1(v
, OP_Yield
, dest
.iSDParm
);
2863 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, dest
.iSdst
, dest
.nSdst
, regRec
);
2864 sqlite3TableAffinity(v
, p
, 0);
2865 sqlite3VdbeAddOp2(v
, OP_NewRowid
, 1, regRowid
);
2866 sqlite3VdbeAddOp3(v
, OP_Insert
, 1, regRec
, regRowid
);
2867 sqlite3VdbeGoto(v
, addrInsLoop
);
2868 sqlite3VdbeJumpHere(v
, addrInsLoop
);
2869 sqlite3VdbeAddOp1(v
, OP_Close
, 1);
2872 /* Compute the complete text of the CREATE statement */
2874 zStmt
= createTableStmt(db
, p
);
2876 Token
*pEnd2
= tabOpts
? &pParse
->sLastToken
: pEnd
;
2877 n
= (int)(pEnd2
->z
- pParse
->sNameToken
.z
);
2878 if( pEnd2
->z
[0]!=';' ) n
+= pEnd2
->n
;
2879 zStmt
= sqlite3MPrintf(db
,
2880 "CREATE %s %.*s", zType2
, n
, pParse
->sNameToken
.z
2884 /* A slot for the record has already been allocated in the
2885 ** schema table. We just need to update that slot with all
2886 ** the information we've collected.
2888 sqlite3NestedParse(pParse
,
2889 "UPDATE %Q." LEGACY_SCHEMA_TABLE
2890 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2892 db
->aDb
[iDb
].zDbSName
,
2900 sqlite3DbFree(db
, zStmt
);
2901 sqlite3ChangeCookie(pParse
, iDb
);
2903 #ifndef SQLITE_OMIT_AUTOINCREMENT
2904 /* Check to see if we need to create an sqlite_sequence table for
2905 ** keeping track of autoincrement keys.
2907 if( (p
->tabFlags
& TF_Autoincrement
)!=0 && !IN_SPECIAL_PARSE
){
2908 Db
*pDb
= &db
->aDb
[iDb
];
2909 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2910 if( pDb
->pSchema
->pSeqTab
==0 ){
2911 sqlite3NestedParse(pParse
,
2912 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2919 /* Reparse everything to update our internal data structures */
2920 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
2921 sqlite3MPrintf(db
, "tbl_name='%q' AND type!='trigger'", p
->zName
),0);
2923 /* Test for cycles in generated columns and illegal expressions
2924 ** in CHECK constraints and in DEFAULT clauses. */
2925 if( p
->tabFlags
& TF_HasGenerated
){
2926 sqlite3VdbeAddOp4(v
, OP_SqlExec
, 0x0001, 0, 0,
2927 sqlite3MPrintf(db
, "SELECT*FROM\"%w\".\"%w\"",
2928 db
->aDb
[iDb
].zDbSName
, p
->zName
), P4_DYNAMIC
);
2930 sqlite3VdbeAddOp4(v
, OP_SqlExec
, 0x0001, 0, 0,
2931 sqlite3MPrintf(db
, "PRAGMA \"%w\".integrity_check(%Q)",
2932 db
->aDb
[iDb
].zDbSName
, p
->zName
), P4_DYNAMIC
);
2935 /* Add the table to the in-memory representation of the database.
2937 if( db
->init
.busy
){
2939 Schema
*pSchema
= p
->pSchema
;
2940 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2941 assert( HasRowid(p
) || p
->iPKey
<0 );
2942 pOld
= sqlite3HashInsert(&pSchema
->tblHash
, p
->zName
, p
);
2944 assert( p
==pOld
); /* Malloc must have failed inside HashInsert() */
2945 sqlite3OomFault(db
);
2948 pParse
->pNewTable
= 0;
2949 db
->mDbFlags
|= DBFLAG_SchemaChange
;
2951 /* If this is the magic sqlite_sequence table used by autoincrement,
2952 ** then record a pointer to this table in the main database structure
2953 ** so that INSERT can find the table easily. */
2954 assert( !pParse
->nested
);
2955 #ifndef SQLITE_OMIT_AUTOINCREMENT
2956 if( strcmp(p
->zName
, "sqlite_sequence")==0 ){
2957 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2958 p
->pSchema
->pSeqTab
= p
;
2963 #ifndef SQLITE_OMIT_ALTERTABLE
2964 if( !pSelect
&& IsOrdinaryTable(p
) ){
2965 assert( pCons
&& pEnd
);
2969 p
->u
.tab
.addColOffset
= 13 + (int)(pCons
->z
- pParse
->sNameToken
.z
);
2974 #ifndef SQLITE_OMIT_VIEW
2976 ** The parser calls this routine in order to create a new VIEW
2978 void sqlite3CreateView(
2979 Parse
*pParse
, /* The parsing context */
2980 Token
*pBegin
, /* The CREATE token that begins the statement */
2981 Token
*pName1
, /* The token that holds the name of the view */
2982 Token
*pName2
, /* The token that holds the name of the view */
2983 ExprList
*pCNames
, /* Optional list of view column names */
2984 Select
*pSelect
, /* A SELECT statement that will become the new view */
2985 int isTemp
, /* TRUE for a TEMPORARY view */
2986 int noErr
/* Suppress error messages if VIEW already exists */
2995 sqlite3
*db
= pParse
->db
;
2997 if( pParse
->nVar
>0 ){
2998 sqlite3ErrorMsg(pParse
, "parameters are not allowed in views");
2999 goto create_view_fail
;
3001 sqlite3StartTable(pParse
, pName1
, pName2
, isTemp
, 1, 0, noErr
);
3002 p
= pParse
->pNewTable
;
3003 if( p
==0 || pParse
->nErr
) goto create_view_fail
;
3005 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
3006 ** on a view, even though views do not have rowids. The following flag
3007 ** setting fixes this problem. But the fix can be disabled by compiling
3008 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
3009 ** depend upon the old buggy behavior. */
3010 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
3011 p
->tabFlags
|= TF_NoVisibleRowid
;
3014 sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
3015 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
3016 sqlite3FixInit(&sFix
, pParse
, iDb
, "view", pName
);
3017 if( sqlite3FixSelect(&sFix
, pSelect
) ) goto create_view_fail
;
3019 /* Make a copy of the entire SELECT statement that defines the view.
3020 ** This will force all the Expr.token.z values to be dynamically
3021 ** allocated rather than point to the input string - which means that
3022 ** they will persist after the current sqlite3_exec() call returns.
3024 pSelect
->selFlags
|= SF_View
;
3025 if( IN_RENAME_OBJECT
){
3026 p
->u
.view
.pSelect
= pSelect
;
3029 p
->u
.view
.pSelect
= sqlite3SelectDup(db
, pSelect
, EXPRDUP_REDUCE
);
3031 p
->pCheck
= sqlite3ExprListDup(db
, pCNames
, EXPRDUP_REDUCE
);
3032 p
->eTabType
= TABTYP_VIEW
;
3033 if( db
->mallocFailed
) goto create_view_fail
;
3035 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
3038 sEnd
= pParse
->sLastToken
;
3039 assert( sEnd
.z
[0]!=0 || sEnd
.n
==0 );
3040 if( sEnd
.z
[0]!=';' ){
3044 n
= (int)(sEnd
.z
- pBegin
->z
);
3047 while( sqlite3Isspace(z
[n
-1]) ){ n
--; }
3051 /* Use sqlite3EndTable() to add the view to the schema table */
3052 sqlite3EndTable(pParse
, 0, &sEnd
, 0, 0);
3055 sqlite3SelectDelete(db
, pSelect
);
3056 if( IN_RENAME_OBJECT
){
3057 sqlite3RenameExprlistUnmap(pParse
, pCNames
);
3059 sqlite3ExprListDelete(db
, pCNames
);
3062 #endif /* SQLITE_OMIT_VIEW */
3064 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3066 ** The Table structure pTable is really a VIEW. Fill in the names of
3067 ** the columns of the view in the pTable structure. Return the number
3068 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
3070 static SQLITE_NOINLINE
int viewGetColumnNames(Parse
*pParse
, Table
*pTable
){
3071 Table
*pSelTab
; /* A fake table from which we get the result set */
3072 Select
*pSel
; /* Copy of the SELECT that implements the view */
3073 int nErr
= 0; /* Number of errors encountered */
3074 sqlite3
*db
= pParse
->db
; /* Database connection for malloc errors */
3075 #ifndef SQLITE_OMIT_VIRTUALTABLE
3078 #ifndef SQLITE_OMIT_AUTHORIZATION
3079 sqlite3_xauth xAuth
; /* Saved xAuth pointer */
3084 #ifndef SQLITE_OMIT_VIRTUALTABLE
3085 if( IsVirtual(pTable
) ){
3087 rc
= sqlite3VtabCallConnect(pParse
, pTable
);
3093 #ifndef SQLITE_OMIT_VIEW
3094 /* A positive nCol means the columns names for this view are
3095 ** already known. This routine is not called unless either the
3096 ** table is virtual or nCol is zero.
3098 assert( pTable
->nCol
<=0 );
3100 /* A negative nCol is a special marker meaning that we are currently
3101 ** trying to compute the column names. If we enter this routine with
3102 ** a negative nCol, it means two or more views form a loop, like this:
3104 ** CREATE VIEW one AS SELECT * FROM two;
3105 ** CREATE VIEW two AS SELECT * FROM one;
3107 ** Actually, the error above is now caught prior to reaching this point.
3108 ** But the following test is still important as it does come up
3109 ** in the following:
3111 ** CREATE TABLE main.ex1(a);
3112 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3113 ** SELECT * FROM temp.ex1;
3115 if( pTable
->nCol
<0 ){
3116 sqlite3ErrorMsg(pParse
, "view %s is circularly defined", pTable
->zName
);
3119 assert( pTable
->nCol
>=0 );
3121 /* If we get this far, it means we need to compute the table names.
3122 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
3123 ** "*" elements in the results set of the view and will assign cursors
3124 ** to the elements of the FROM clause. But we do not want these changes
3125 ** to be permanent. So the computation is done on a copy of the SELECT
3126 ** statement that defines the view.
3128 assert( IsView(pTable
) );
3129 pSel
= sqlite3SelectDup(db
, pTable
->u
.view
.pSelect
, 0);
3131 u8 eParseMode
= pParse
->eParseMode
;
3132 int nTab
= pParse
->nTab
;
3133 int nSelect
= pParse
->nSelect
;
3134 pParse
->eParseMode
= PARSE_MODE_NORMAL
;
3135 sqlite3SrcListAssignCursors(pParse
, pSel
->pSrc
);
3138 #ifndef SQLITE_OMIT_AUTHORIZATION
3141 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
, SQLITE_AFF_NONE
);
3144 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
, SQLITE_AFF_NONE
);
3146 pParse
->nTab
= nTab
;
3147 pParse
->nSelect
= nSelect
;
3151 }else if( pTable
->pCheck
){
3152 /* CREATE VIEW name(arglist) AS ...
3153 ** The names of the columns in the table are taken from
3154 ** arglist which is stored in pTable->pCheck. The pCheck field
3155 ** normally holds CHECK constraints on an ordinary table, but for
3156 ** a VIEW it holds the list of column names.
3158 sqlite3ColumnsFromExprList(pParse
, pTable
->pCheck
,
3159 &pTable
->nCol
, &pTable
->aCol
);
3161 && pTable
->nCol
==pSel
->pEList
->nExpr
3163 assert( db
->mallocFailed
==0 );
3164 sqlite3SubqueryColumnTypes(pParse
, pTable
, pSel
, SQLITE_AFF_NONE
);
3167 /* CREATE VIEW name AS... without an argument list. Construct
3168 ** the column names from the SELECT statement that defines the view.
3170 assert( pTable
->aCol
==0 );
3171 pTable
->nCol
= pSelTab
->nCol
;
3172 pTable
->aCol
= pSelTab
->aCol
;
3173 pTable
->tabFlags
|= (pSelTab
->tabFlags
& COLFLAG_NOINSERT
);
3176 assert( sqlite3SchemaMutexHeld(db
, 0, pTable
->pSchema
) );
3178 pTable
->nNVCol
= pTable
->nCol
;
3179 sqlite3DeleteTable(db
, pSelTab
);
3180 sqlite3SelectDelete(db
, pSel
);
3182 pParse
->eParseMode
= eParseMode
;
3186 pTable
->pSchema
->schemaFlags
|= DB_UnresetViews
;
3187 if( db
->mallocFailed
){
3188 sqlite3DeleteColumnNames(db
, pTable
);
3190 #endif /* SQLITE_OMIT_VIEW */
3193 int sqlite3ViewGetColumnNames(Parse
*pParse
, Table
*pTable
){
3194 assert( pTable
!=0 );
3195 if( !IsVirtual(pTable
) && pTable
->nCol
>0 ) return 0;
3196 return viewGetColumnNames(pParse
, pTable
);
3198 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3200 #ifndef SQLITE_OMIT_VIEW
3202 ** Clear the column names from every VIEW in database idx.
3204 static void sqliteViewResetAll(sqlite3
*db
, int idx
){
3206 assert( sqlite3SchemaMutexHeld(db
, idx
, 0) );
3207 if( !DbHasProperty(db
, idx
, DB_UnresetViews
) ) return;
3208 for(i
=sqliteHashFirst(&db
->aDb
[idx
].pSchema
->tblHash
); i
;i
=sqliteHashNext(i
)){
3209 Table
*pTab
= sqliteHashData(i
);
3211 sqlite3DeleteColumnNames(db
, pTab
);
3214 DbClearProperty(db
, idx
, DB_UnresetViews
);
3217 # define sqliteViewResetAll(A,B)
3218 #endif /* SQLITE_OMIT_VIEW */
3221 ** This function is called by the VDBE to adjust the internal schema
3222 ** used by SQLite when the btree layer moves a table root page. The
3223 ** root-page of a table or index in database iDb has changed from iFrom
3226 ** Ticket #1728: The symbol table might still contain information
3227 ** on tables and/or indices that are the process of being deleted.
3228 ** If you are unlucky, one of those deleted indices or tables might
3229 ** have the same rootpage number as the real table or index that is
3230 ** being moved. So we cannot stop searching after the first match
3231 ** because the first match might be for one of the deleted indices
3232 ** or tables and not the table/index that is actually being moved.
3233 ** We must continue looping until all tables and indices with
3234 ** rootpage==iFrom have been converted to have a rootpage of iTo
3235 ** in order to be certain that we got the right one.
3237 #ifndef SQLITE_OMIT_AUTOVACUUM
3238 void sqlite3RootPageMoved(sqlite3
*db
, int iDb
, Pgno iFrom
, Pgno iTo
){
3243 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
3244 pDb
= &db
->aDb
[iDb
];
3245 pHash
= &pDb
->pSchema
->tblHash
;
3246 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
3247 Table
*pTab
= sqliteHashData(pElem
);
3248 if( pTab
->tnum
==iFrom
){
3252 pHash
= &pDb
->pSchema
->idxHash
;
3253 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
3254 Index
*pIdx
= sqliteHashData(pElem
);
3255 if( pIdx
->tnum
==iFrom
){
3263 ** Write code to erase the table with root-page iTable from database iDb.
3264 ** Also write code to modify the sqlite_schema table and internal schema
3265 ** if a root-page of another table is moved by the btree-layer whilst
3266 ** erasing iTable (this can happen with an auto-vacuum database).
3268 static void destroyRootPage(Parse
*pParse
, int iTable
, int iDb
){
3269 Vdbe
*v
= sqlite3GetVdbe(pParse
);
3270 int r1
= sqlite3GetTempReg(pParse
);
3271 if( iTable
<2 ) sqlite3ErrorMsg(pParse
, "corrupt schema");
3272 sqlite3VdbeAddOp3(v
, OP_Destroy
, iTable
, r1
, iDb
);
3273 sqlite3MayAbort(pParse
);
3274 #ifndef SQLITE_OMIT_AUTOVACUUM
3275 /* OP_Destroy stores an in integer r1. If this integer
3276 ** is non-zero, then it is the root page number of a table moved to
3277 ** location iTable. The following code modifies the sqlite_schema table to
3280 ** The "#NNN" in the SQL is a special constant that means whatever value
3281 ** is in register NNN. See grammar rules associated with the TK_REGISTER
3282 ** token for additional information.
3284 sqlite3NestedParse(pParse
,
3285 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3286 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3287 pParse
->db
->aDb
[iDb
].zDbSName
, iTable
, r1
, r1
);
3289 sqlite3ReleaseTempReg(pParse
, r1
);
3293 ** Write VDBE code to erase table pTab and all associated indices on disk.
3294 ** Code to update the sqlite_schema tables and internal schema definitions
3295 ** in case a root-page belonging to another table is moved by the btree layer
3296 ** is also added (this can happen with an auto-vacuum database).
3298 static void destroyTable(Parse
*pParse
, Table
*pTab
){
3299 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3300 ** is not defined), then it is important to call OP_Destroy on the
3301 ** table and index root-pages in order, starting with the numerically
3302 ** largest root-page number. This guarantees that none of the root-pages
3303 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3304 ** following were coded:
3310 ** and root page 5 happened to be the largest root-page number in the
3311 ** database, then root page 5 would be moved to page 4 by the
3312 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3313 ** a free-list page.
3315 Pgno iTab
= pTab
->tnum
;
3316 Pgno iDestroyed
= 0;
3322 if( iDestroyed
==0 || iTab
<iDestroyed
){
3325 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
3326 Pgno iIdx
= pIdx
->tnum
;
3327 assert( pIdx
->pSchema
==pTab
->pSchema
);
3328 if( (iDestroyed
==0 || (iIdx
<iDestroyed
)) && iIdx
>iLargest
){
3335 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
3336 assert( iDb
>=0 && iDb
<pParse
->db
->nDb
);
3337 destroyRootPage(pParse
, iLargest
, iDb
);
3338 iDestroyed
= iLargest
;
3344 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3345 ** after a DROP INDEX or DROP TABLE command.
3347 static void sqlite3ClearStatTables(
3348 Parse
*pParse
, /* The parsing context */
3349 int iDb
, /* The database number */
3350 const char *zType
, /* "idx" or "tbl" */
3351 const char *zName
/* Name of index or table */
3354 const char *zDbName
= pParse
->db
->aDb
[iDb
].zDbSName
;
3355 for(i
=1; i
<=4; i
++){
3357 sqlite3_snprintf(sizeof(zTab
),zTab
,"sqlite_stat%d",i
);
3358 if( sqlite3FindTable(pParse
->db
, zTab
, zDbName
) ){
3359 sqlite3NestedParse(pParse
,
3360 "DELETE FROM %Q.%s WHERE %s=%Q",
3361 zDbName
, zTab
, zType
, zName
3368 ** Generate code to drop a table.
3370 void sqlite3CodeDropTable(Parse
*pParse
, Table
*pTab
, int iDb
, int isView
){
3372 sqlite3
*db
= pParse
->db
;
3374 Db
*pDb
= &db
->aDb
[iDb
];
3376 v
= sqlite3GetVdbe(pParse
);
3378 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3380 #ifndef SQLITE_OMIT_VIRTUALTABLE
3381 if( IsVirtual(pTab
) ){
3382 sqlite3VdbeAddOp0(v
, OP_VBegin
);
3386 /* Drop all triggers associated with the table being dropped. Code
3387 ** is generated to remove entries from sqlite_schema and/or
3388 ** sqlite_temp_schema if required.
3390 pTrigger
= sqlite3TriggerList(pParse
, pTab
);
3392 assert( pTrigger
->pSchema
==pTab
->pSchema
||
3393 pTrigger
->pSchema
==db
->aDb
[1].pSchema
);
3394 sqlite3DropTriggerPtr(pParse
, pTrigger
);
3395 pTrigger
= pTrigger
->pNext
;
3398 #ifndef SQLITE_OMIT_AUTOINCREMENT
3399 /* Remove any entries of the sqlite_sequence table associated with
3400 ** the table being dropped. This is done before the table is dropped
3401 ** at the btree level, in case the sqlite_sequence table needs to
3402 ** move as a result of the drop (can happen in auto-vacuum mode).
3404 if( pTab
->tabFlags
& TF_Autoincrement
){
3405 sqlite3NestedParse(pParse
,
3406 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3407 pDb
->zDbSName
, pTab
->zName
3412 /* Drop all entries in the schema table that refer to the
3413 ** table. The program name loops through the schema table and deletes
3414 ** every row that refers to a table of the same name as the one being
3415 ** dropped. Triggers are handled separately because a trigger can be
3416 ** created in the temp database that refers to a table in another
3419 sqlite3NestedParse(pParse
,
3420 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3421 " WHERE tbl_name=%Q and type!='trigger'",
3422 pDb
->zDbSName
, pTab
->zName
);
3423 if( !isView
&& !IsVirtual(pTab
) ){
3424 destroyTable(pParse
, pTab
);
3427 /* Remove the table entry from SQLite's internal schema and modify
3428 ** the schema cookie.
3430 if( IsVirtual(pTab
) ){
3431 sqlite3VdbeAddOp4(v
, OP_VDestroy
, iDb
, 0, 0, pTab
->zName
, 0);
3432 sqlite3MayAbort(pParse
);
3434 sqlite3VdbeAddOp4(v
, OP_DropTable
, iDb
, 0, 0, pTab
->zName
, 0);
3435 sqlite3ChangeCookie(pParse
, iDb
);
3436 sqliteViewResetAll(db
, iDb
);
3440 ** Return TRUE if shadow tables should be read-only in the current
3443 int sqlite3ReadOnlyShadowTables(sqlite3
*db
){
3444 #ifndef SQLITE_OMIT_VIRTUALTABLE
3445 if( (db
->flags
& SQLITE_Defensive
)!=0
3448 && !sqlite3VtabInSync(db
)
3457 ** Return true if it is not allowed to drop the given table
3459 static int tableMayNotBeDropped(sqlite3
*db
, Table
*pTab
){
3460 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0 ){
3461 if( sqlite3StrNICmp(pTab
->zName
+7, "stat", 4)==0 ) return 0;
3462 if( sqlite3StrNICmp(pTab
->zName
+7, "parameters", 10)==0 ) return 0;
3465 if( (pTab
->tabFlags
& TF_Shadow
)!=0 && sqlite3ReadOnlyShadowTables(db
) ){
3468 if( pTab
->tabFlags
& TF_Eponymous
){
3475 ** This routine is called to do the work of a DROP TABLE statement.
3476 ** pName is the name of the table to be dropped.
3478 void sqlite3DropTable(Parse
*pParse
, SrcList
*pName
, int isView
, int noErr
){
3481 sqlite3
*db
= pParse
->db
;
3484 if( db
->mallocFailed
){
3485 goto exit_drop_table
;
3487 assert( pParse
->nErr
==0 );
3488 assert( pName
->nSrc
==1 );
3489 if( sqlite3ReadSchema(pParse
) ) goto exit_drop_table
;
3490 if( noErr
) db
->suppressErr
++;
3491 assert( isView
==0 || isView
==LOCATE_VIEW
);
3492 pTab
= sqlite3LocateTableItem(pParse
, isView
, &pName
->a
[0]);
3493 if( noErr
) db
->suppressErr
--;
3497 sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
3498 sqlite3ForceNotReadOnly(pParse
);
3500 goto exit_drop_table
;
3502 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
3503 assert( iDb
>=0 && iDb
<db
->nDb
);
3505 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3506 ** it is initialized.
3508 if( IsVirtual(pTab
) && sqlite3ViewGetColumnNames(pParse
, pTab
) ){
3509 goto exit_drop_table
;
3511 #ifndef SQLITE_OMIT_AUTHORIZATION
3514 const char *zTab
= SCHEMA_TABLE(iDb
);
3515 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
3516 const char *zArg2
= 0;
3517 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
)){
3518 goto exit_drop_table
;
3521 if( !OMIT_TEMPDB
&& iDb
==1 ){
3522 code
= SQLITE_DROP_TEMP_VIEW
;
3524 code
= SQLITE_DROP_VIEW
;
3526 #ifndef SQLITE_OMIT_VIRTUALTABLE
3527 }else if( IsVirtual(pTab
) ){
3528 code
= SQLITE_DROP_VTABLE
;
3529 zArg2
= sqlite3GetVTable(db
, pTab
)->pMod
->zName
;
3532 if( !OMIT_TEMPDB
&& iDb
==1 ){
3533 code
= SQLITE_DROP_TEMP_TABLE
;
3535 code
= SQLITE_DROP_TABLE
;
3538 if( sqlite3AuthCheck(pParse
, code
, pTab
->zName
, zArg2
, zDb
) ){
3539 goto exit_drop_table
;
3541 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, pTab
->zName
, 0, zDb
) ){
3542 goto exit_drop_table
;
3546 if( tableMayNotBeDropped(db
, pTab
) ){
3547 sqlite3ErrorMsg(pParse
, "table %s may not be dropped", pTab
->zName
);
3548 goto exit_drop_table
;
3551 #ifndef SQLITE_OMIT_VIEW
3552 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3555 if( isView
&& !IsView(pTab
) ){
3556 sqlite3ErrorMsg(pParse
, "use DROP TABLE to delete table %s", pTab
->zName
);
3557 goto exit_drop_table
;
3559 if( !isView
&& IsView(pTab
) ){
3560 sqlite3ErrorMsg(pParse
, "use DROP VIEW to delete view %s", pTab
->zName
);
3561 goto exit_drop_table
;
3565 /* Generate code to remove the table from the schema table
3568 v
= sqlite3GetVdbe(pParse
);
3570 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3572 sqlite3ClearStatTables(pParse
, iDb
, "tbl", pTab
->zName
);
3573 sqlite3FkDropTable(pParse
, pName
, pTab
);
3575 sqlite3CodeDropTable(pParse
, pTab
, iDb
, isView
);
3579 sqlite3SrcListDelete(db
, pName
);
3583 ** This routine is called to create a new foreign key on the table
3584 ** currently under construction. pFromCol determines which columns
3585 ** in the current table point to the foreign key. If pFromCol==0 then
3586 ** connect the key to the last column inserted. pTo is the name of
3587 ** the table referred to (a.k.a the "parent" table). pToCol is a list
3588 ** of tables in the parent pTo table. flags contains all
3589 ** information about the conflict resolution algorithms specified
3590 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3592 ** An FKey structure is created and added to the table currently
3593 ** under construction in the pParse->pNewTable field.
3595 ** The foreign key is set for IMMEDIATE processing. A subsequent call
3596 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3598 void sqlite3CreateForeignKey(
3599 Parse
*pParse
, /* Parsing context */
3600 ExprList
*pFromCol
, /* Columns in this table that point to other table */
3601 Token
*pTo
, /* Name of the other table */
3602 ExprList
*pToCol
, /* Columns in the other table */
3603 int flags
/* Conflict resolution algorithms. */
3605 sqlite3
*db
= pParse
->db
;
3606 #ifndef SQLITE_OMIT_FOREIGN_KEY
3609 Table
*p
= pParse
->pNewTable
;
3616 if( p
==0 || IN_DECLARE_VTAB
) goto fk_end
;
3618 int iCol
= p
->nCol
-1;
3619 if( NEVER(iCol
<0) ) goto fk_end
;
3620 if( pToCol
&& pToCol
->nExpr
!=1 ){
3621 sqlite3ErrorMsg(pParse
, "foreign key on %s"
3622 " should reference only one column of table %T",
3623 p
->aCol
[iCol
].zCnName
, pTo
);
3627 }else if( pToCol
&& pToCol
->nExpr
!=pFromCol
->nExpr
){
3628 sqlite3ErrorMsg(pParse
,
3629 "number of columns in foreign key does not match the number of "
3630 "columns in the referenced table");
3633 nCol
= pFromCol
->nExpr
;
3635 nByte
= sizeof(*pFKey
) + (nCol
-1)*sizeof(pFKey
->aCol
[0]) + pTo
->n
+ 1;
3637 for(i
=0; i
<pToCol
->nExpr
; i
++){
3638 nByte
+= sqlite3Strlen30(pToCol
->a
[i
].zEName
) + 1;
3641 pFKey
= sqlite3DbMallocZero(db
, nByte
);
3646 assert( IsOrdinaryTable(p
) );
3647 pFKey
->pNextFrom
= p
->u
.tab
.pFKey
;
3648 z
= (char*)&pFKey
->aCol
[nCol
];
3650 if( IN_RENAME_OBJECT
){
3651 sqlite3RenameTokenMap(pParse
, (void*)z
, pTo
);
3653 memcpy(z
, pTo
->z
, pTo
->n
);
3659 pFKey
->aCol
[0].iFrom
= p
->nCol
-1;
3661 for(i
=0; i
<nCol
; i
++){
3663 for(j
=0; j
<p
->nCol
; j
++){
3664 if( sqlite3StrICmp(p
->aCol
[j
].zCnName
, pFromCol
->a
[i
].zEName
)==0 ){
3665 pFKey
->aCol
[i
].iFrom
= j
;
3670 sqlite3ErrorMsg(pParse
,
3671 "unknown column \"%s\" in foreign key definition",
3672 pFromCol
->a
[i
].zEName
);
3675 if( IN_RENAME_OBJECT
){
3676 sqlite3RenameTokenRemap(pParse
, &pFKey
->aCol
[i
], pFromCol
->a
[i
].zEName
);
3681 for(i
=0; i
<nCol
; i
++){
3682 int n
= sqlite3Strlen30(pToCol
->a
[i
].zEName
);
3683 pFKey
->aCol
[i
].zCol
= z
;
3684 if( IN_RENAME_OBJECT
){
3685 sqlite3RenameTokenRemap(pParse
, z
, pToCol
->a
[i
].zEName
);
3687 memcpy(z
, pToCol
->a
[i
].zEName
, n
);
3692 pFKey
->isDeferred
= 0;
3693 pFKey
->aAction
[0] = (u8
)(flags
& 0xff); /* ON DELETE action */
3694 pFKey
->aAction
[1] = (u8
)((flags
>> 8 ) & 0xff); /* ON UPDATE action */
3696 assert( sqlite3SchemaMutexHeld(db
, 0, p
->pSchema
) );
3697 pNextTo
= (FKey
*)sqlite3HashInsert(&p
->pSchema
->fkeyHash
,
3698 pFKey
->zTo
, (void *)pFKey
3700 if( pNextTo
==pFKey
){
3701 sqlite3OomFault(db
);
3705 assert( pNextTo
->pPrevTo
==0 );
3706 pFKey
->pNextTo
= pNextTo
;
3707 pNextTo
->pPrevTo
= pFKey
;
3710 /* Link the foreign key to the table as the last step.
3712 assert( IsOrdinaryTable(p
) );
3713 p
->u
.tab
.pFKey
= pFKey
;
3717 sqlite3DbFree(db
, pFKey
);
3718 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3719 sqlite3ExprListDelete(db
, pFromCol
);
3720 sqlite3ExprListDelete(db
, pToCol
);
3724 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3725 ** clause is seen as part of a foreign key definition. The isDeferred
3726 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3727 ** The behavior of the most recently created foreign key is adjusted
3730 void sqlite3DeferForeignKey(Parse
*pParse
, int isDeferred
){
3731 #ifndef SQLITE_OMIT_FOREIGN_KEY
3734 if( (pTab
= pParse
->pNewTable
)==0 ) return;
3735 if( NEVER(!IsOrdinaryTable(pTab
)) ) return;
3736 if( (pFKey
= pTab
->u
.tab
.pFKey
)==0 ) return;
3737 assert( isDeferred
==0 || isDeferred
==1 ); /* EV: R-30323-21917 */
3738 pFKey
->isDeferred
= (u8
)isDeferred
;
3743 ** Generate code that will erase and refill index *pIdx. This is
3744 ** used to initialize a newly created index or to recompute the
3745 ** content of an index in response to a REINDEX command.
3747 ** if memRootPage is not negative, it means that the index is newly
3748 ** created. The register specified by memRootPage contains the
3749 ** root page number of the index. If memRootPage is negative, then
3750 ** the index already exists and must be cleared before being refilled and
3751 ** the root page number of the index is taken from pIndex->tnum.
3753 static void sqlite3RefillIndex(Parse
*pParse
, Index
*pIndex
, int memRootPage
){
3754 Table
*pTab
= pIndex
->pTable
; /* The table that is indexed */
3755 int iTab
= pParse
->nTab
++; /* Btree cursor used for pTab */
3756 int iIdx
= pParse
->nTab
++; /* Btree cursor used for pIndex */
3757 int iSorter
; /* Cursor opened by OpenSorter (if in use) */
3758 int addr1
; /* Address of top of loop */
3759 int addr2
; /* Address to jump to for next iteration */
3760 Pgno tnum
; /* Root page of index */
3761 int iPartIdxLabel
; /* Jump to this label to skip a row */
3762 Vdbe
*v
; /* Generate code into this virtual machine */
3763 KeyInfo
*pKey
; /* KeyInfo for index */
3764 int regRecord
; /* Register holding assembled index record */
3765 sqlite3
*db
= pParse
->db
; /* The database connection */
3766 int iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
3768 #ifndef SQLITE_OMIT_AUTHORIZATION
3769 if( sqlite3AuthCheck(pParse
, SQLITE_REINDEX
, pIndex
->zName
, 0,
3770 db
->aDb
[iDb
].zDbSName
) ){
3775 /* Require a write-lock on the table to perform this operation */
3776 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 1, pTab
->zName
);
3778 v
= sqlite3GetVdbe(pParse
);
3780 if( memRootPage
>=0 ){
3781 tnum
= (Pgno
)memRootPage
;
3783 tnum
= pIndex
->tnum
;
3785 pKey
= sqlite3KeyInfoOfIndex(pParse
, pIndex
);
3786 assert( pKey
!=0 || pParse
->nErr
);
3788 /* Open the sorter cursor if we are to use one. */
3789 iSorter
= pParse
->nTab
++;
3790 sqlite3VdbeAddOp4(v
, OP_SorterOpen
, iSorter
, 0, pIndex
->nKeyCol
, (char*)
3791 sqlite3KeyInfoRef(pKey
), P4_KEYINFO
);
3793 /* Open the table. Loop through all rows of the table, inserting index
3794 ** records into the sorter. */
3795 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
3796 addr1
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, 0); VdbeCoverage(v
);
3797 regRecord
= sqlite3GetTempReg(pParse
);
3798 sqlite3MultiWrite(pParse
);
3800 sqlite3GenerateIndexKey(pParse
,pIndex
,iTab
,regRecord
,0,&iPartIdxLabel
,0,0);
3801 sqlite3VdbeAddOp2(v
, OP_SorterInsert
, iSorter
, regRecord
);
3802 sqlite3ResolvePartIdxLabel(pParse
, iPartIdxLabel
);
3803 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addr1
+1); VdbeCoverage(v
);
3804 sqlite3VdbeJumpHere(v
, addr1
);
3805 if( memRootPage
<0 ) sqlite3VdbeAddOp2(v
, OP_Clear
, tnum
, iDb
);
3806 sqlite3VdbeAddOp4(v
, OP_OpenWrite
, iIdx
, (int)tnum
, iDb
,
3807 (char *)pKey
, P4_KEYINFO
);
3808 sqlite3VdbeChangeP5(v
, OPFLAG_BULKCSR
|((memRootPage
>=0)?OPFLAG_P2ISREG
:0));
3810 addr1
= sqlite3VdbeAddOp2(v
, OP_SorterSort
, iSorter
, 0); VdbeCoverage(v
);
3811 if( IsUniqueIndex(pIndex
) ){
3812 int j2
= sqlite3VdbeGoto(v
, 1);
3813 addr2
= sqlite3VdbeCurrentAddr(v
);
3814 sqlite3VdbeVerifyAbortable(v
, OE_Abort
);
3815 sqlite3VdbeAddOp4Int(v
, OP_SorterCompare
, iSorter
, j2
, regRecord
,
3816 pIndex
->nKeyCol
); VdbeCoverage(v
);
3817 sqlite3UniqueConstraint(pParse
, OE_Abort
, pIndex
);
3818 sqlite3VdbeJumpHere(v
, j2
);
3820 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3821 ** abort. The exception is if one of the indexed expressions contains a
3822 ** user function that throws an exception when it is evaluated. But the
3823 ** overhead of adding a statement journal to a CREATE INDEX statement is
3824 ** very small (since most of the pages written do not contain content that
3825 ** needs to be restored if the statement aborts), so we call
3826 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3827 sqlite3MayAbort(pParse
);
3828 addr2
= sqlite3VdbeCurrentAddr(v
);
3830 sqlite3VdbeAddOp3(v
, OP_SorterData
, iSorter
, regRecord
, iIdx
);
3831 if( !pIndex
->bAscKeyBug
){
3832 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3833 ** faster by avoiding unnecessary seeks. But the optimization does
3834 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3835 ** with DESC primary keys, since those indexes have there keys in
3836 ** a different order from the main table.
3837 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3839 sqlite3VdbeAddOp1(v
, OP_SeekEnd
, iIdx
);
3841 sqlite3VdbeAddOp2(v
, OP_IdxInsert
, iIdx
, regRecord
);
3842 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
3843 sqlite3ReleaseTempReg(pParse
, regRecord
);
3844 sqlite3VdbeAddOp2(v
, OP_SorterNext
, iSorter
, addr2
); VdbeCoverage(v
);
3845 sqlite3VdbeJumpHere(v
, addr1
);
3847 sqlite3VdbeAddOp1(v
, OP_Close
, iTab
);
3848 sqlite3VdbeAddOp1(v
, OP_Close
, iIdx
);
3849 sqlite3VdbeAddOp1(v
, OP_Close
, iSorter
);
3853 ** Allocate heap space to hold an Index object with nCol columns.
3855 ** Increase the allocation size to provide an extra nExtra bytes
3856 ** of 8-byte aligned space after the Index object and return a
3857 ** pointer to this extra space in *ppExtra.
3859 Index
*sqlite3AllocateIndexObject(
3860 sqlite3
*db
, /* Database connection */
3861 i16 nCol
, /* Total number of columns in the index */
3862 int nExtra
, /* Number of bytes of extra space to alloc */
3863 char **ppExtra
/* Pointer to the "extra" space */
3865 Index
*p
; /* Allocated index object */
3866 int nByte
; /* Bytes of space for Index object + arrays */
3868 nByte
= ROUND8(sizeof(Index
)) + /* Index structure */
3869 ROUND8(sizeof(char*)*nCol
) + /* Index.azColl */
3870 ROUND8(sizeof(LogEst
)*(nCol
+1) + /* Index.aiRowLogEst */
3871 sizeof(i16
)*nCol
+ /* Index.aiColumn */
3872 sizeof(u8
)*nCol
); /* Index.aSortOrder */
3873 p
= sqlite3DbMallocZero(db
, nByte
+ nExtra
);
3875 char *pExtra
= ((char*)p
)+ROUND8(sizeof(Index
));
3876 p
->azColl
= (const char**)pExtra
; pExtra
+= ROUND8(sizeof(char*)*nCol
);
3877 p
->aiRowLogEst
= (LogEst
*)pExtra
; pExtra
+= sizeof(LogEst
)*(nCol
+1);
3878 p
->aiColumn
= (i16
*)pExtra
; pExtra
+= sizeof(i16
)*nCol
;
3879 p
->aSortOrder
= (u8
*)pExtra
;
3881 p
->nKeyCol
= nCol
- 1;
3882 *ppExtra
= ((char*)p
) + nByte
;
3888 ** If expression list pList contains an expression that was parsed with
3889 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3890 ** pParse and return non-zero. Otherwise, return zero.
3892 int sqlite3HasExplicitNulls(Parse
*pParse
, ExprList
*pList
){
3895 for(i
=0; i
<pList
->nExpr
; i
++){
3896 if( pList
->a
[i
].fg
.bNulls
){
3897 u8 sf
= pList
->a
[i
].fg
.sortFlags
;
3898 sqlite3ErrorMsg(pParse
, "unsupported use of NULLS %s",
3899 (sf
==0 || sf
==3) ? "FIRST" : "LAST"
3909 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
3910 ** and pTblList is the name of the table that is to be indexed. Both will
3911 ** be NULL for a primary key or an index that is created to satisfy a
3912 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
3913 ** as the table to be indexed. pParse->pNewTable is a table that is
3914 ** currently being constructed by a CREATE TABLE statement.
3916 ** pList is a list of columns to be indexed. pList will be NULL if this
3917 ** is a primary key or unique-constraint on the most recent column added
3918 ** to the table currently under construction.
3920 void sqlite3CreateIndex(
3921 Parse
*pParse
, /* All information about this parse */
3922 Token
*pName1
, /* First part of index name. May be NULL */
3923 Token
*pName2
, /* Second part of index name. May be NULL */
3924 SrcList
*pTblName
, /* Table to index. Use pParse->pNewTable if 0 */
3925 ExprList
*pList
, /* A list of columns to be indexed */
3926 int onError
, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3927 Token
*pStart
, /* The CREATE token that begins this statement */
3928 Expr
*pPIWhere
, /* WHERE clause for partial indices */
3929 int sortOrder
, /* Sort order of primary key when pList==NULL */
3930 int ifNotExist
, /* Omit error if index already exists */
3931 u8 idxType
/* The index type */
3933 Table
*pTab
= 0; /* Table to be indexed */
3934 Index
*pIndex
= 0; /* The index to be created */
3935 char *zName
= 0; /* Name of the index */
3936 int nName
; /* Number of characters in zName */
3938 DbFixer sFix
; /* For assigning database names to pTable */
3939 int sortOrderMask
; /* 1 to honor DESC in index. 0 to ignore. */
3940 sqlite3
*db
= pParse
->db
;
3941 Db
*pDb
; /* The specific table containing the indexed database */
3942 int iDb
; /* Index of the database that is being written */
3943 Token
*pName
= 0; /* Unqualified name of the index to create */
3944 struct ExprList_item
*pListItem
; /* For looping over pList */
3945 int nExtra
= 0; /* Space allocated for zExtra[] */
3946 int nExtraCol
; /* Number of extra columns needed */
3947 char *zExtra
= 0; /* Extra space after the Index object */
3948 Index
*pPk
= 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
3950 assert( db
->pParse
==pParse
);
3952 goto exit_create_index
;
3954 assert( db
->mallocFailed
==0 );
3955 if( IN_DECLARE_VTAB
&& idxType
!=SQLITE_IDXTYPE_PRIMARYKEY
){
3956 goto exit_create_index
;
3958 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
3959 goto exit_create_index
;
3961 if( sqlite3HasExplicitNulls(pParse
, pList
) ){
3962 goto exit_create_index
;
3966 ** Find the table that is to be indexed. Return early if not found.
3970 /* Use the two-part index name to determine the database
3971 ** to search for the table. 'Fix' the table name to this db
3972 ** before looking up the table.
3974 assert( pName1
&& pName2
);
3975 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
3976 if( iDb
<0 ) goto exit_create_index
;
3977 assert( pName
&& pName
->z
);
3979 #ifndef SQLITE_OMIT_TEMPDB
3980 /* If the index name was unqualified, check if the table
3981 ** is a temp table. If so, set the database to 1. Do not do this
3982 ** if initializing a database schema.
3984 if( !db
->init
.busy
){
3985 pTab
= sqlite3SrcListLookup(pParse
, pTblName
);
3986 if( pName2
->n
==0 && pTab
&& pTab
->pSchema
==db
->aDb
[1].pSchema
){
3992 sqlite3FixInit(&sFix
, pParse
, iDb
, "index", pName
);
3993 if( sqlite3FixSrcList(&sFix
, pTblName
) ){
3994 /* Because the parser constructs pTblName from a single identifier,
3995 ** sqlite3FixSrcList can never fail. */
3998 pTab
= sqlite3LocateTableItem(pParse
, 0, &pTblName
->a
[0]);
3999 assert( db
->mallocFailed
==0 || pTab
==0 );
4000 if( pTab
==0 ) goto exit_create_index
;
4001 if( iDb
==1 && db
->aDb
[iDb
].pSchema
!=pTab
->pSchema
){
4002 sqlite3ErrorMsg(pParse
,
4003 "cannot create a TEMP index on non-TEMP table \"%s\"",
4005 goto exit_create_index
;
4007 if( !HasRowid(pTab
) ) pPk
= sqlite3PrimaryKeyIndex(pTab
);
4010 assert( pStart
==0 );
4011 pTab
= pParse
->pNewTable
;
4012 if( !pTab
) goto exit_create_index
;
4013 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
4015 pDb
= &db
->aDb
[iDb
];
4018 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0
4021 #if SQLITE_USER_AUTHENTICATION
4022 && sqlite3UserAuthTable(pTab
->zName
)==0
4025 sqlite3ErrorMsg(pParse
, "table %s may not be indexed", pTab
->zName
);
4026 goto exit_create_index
;
4028 #ifndef SQLITE_OMIT_VIEW
4030 sqlite3ErrorMsg(pParse
, "views may not be indexed");
4031 goto exit_create_index
;
4034 #ifndef SQLITE_OMIT_VIRTUALTABLE
4035 if( IsVirtual(pTab
) ){
4036 sqlite3ErrorMsg(pParse
, "virtual tables may not be indexed");
4037 goto exit_create_index
;
4042 ** Find the name of the index. Make sure there is not already another
4043 ** index or table with the same name.
4045 ** Exception: If we are reading the names of permanent indices from the
4046 ** sqlite_schema table (because some other process changed the schema) and
4047 ** one of the index names collides with the name of a temporary table or
4048 ** index, then we will continue to process this index.
4050 ** If pName==0 it means that we are
4051 ** dealing with a primary key or UNIQUE constraint. We have to invent our
4055 zName
= sqlite3NameFromToken(db
, pName
);
4056 if( zName
==0 ) goto exit_create_index
;
4057 assert( pName
->z
!=0 );
4058 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
,"index",pTab
->zName
) ){
4059 goto exit_create_index
;
4061 if( !IN_RENAME_OBJECT
){
4062 if( !db
->init
.busy
){
4063 if( sqlite3FindTable(db
, zName
, pDb
->zDbSName
)!=0 ){
4064 sqlite3ErrorMsg(pParse
, "there is already a table named %s", zName
);
4065 goto exit_create_index
;
4068 if( sqlite3FindIndex(db
, zName
, pDb
->zDbSName
)!=0 ){
4070 sqlite3ErrorMsg(pParse
, "index %s already exists", zName
);
4072 assert( !db
->init
.busy
);
4073 sqlite3CodeVerifySchema(pParse
, iDb
);
4074 sqlite3ForceNotReadOnly(pParse
);
4076 goto exit_create_index
;
4082 for(pLoop
=pTab
->pIndex
, n
=1; pLoop
; pLoop
=pLoop
->pNext
, n
++){}
4083 zName
= sqlite3MPrintf(db
, "sqlite_autoindex_%s_%d", pTab
->zName
, n
);
4085 goto exit_create_index
;
4088 /* Automatic index names generated from within sqlite3_declare_vtab()
4089 ** must have names that are distinct from normal automatic index names.
4090 ** The following statement converts "sqlite3_autoindex..." into
4091 ** "sqlite3_butoindex..." in order to make the names distinct.
4092 ** The "vtab_err.test" test demonstrates the need of this statement. */
4093 if( IN_SPECIAL_PARSE
) zName
[7]++;
4096 /* Check for authorization to create an index.
4098 #ifndef SQLITE_OMIT_AUTHORIZATION
4099 if( !IN_RENAME_OBJECT
){
4100 const char *zDb
= pDb
->zDbSName
;
4101 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(iDb
), 0, zDb
) ){
4102 goto exit_create_index
;
4104 i
= SQLITE_CREATE_INDEX
;
4105 if( !OMIT_TEMPDB
&& iDb
==1 ) i
= SQLITE_CREATE_TEMP_INDEX
;
4106 if( sqlite3AuthCheck(pParse
, i
, zName
, pTab
->zName
, zDb
) ){
4107 goto exit_create_index
;
4112 /* If pList==0, it means this routine was called to make a primary
4113 ** key out of the last column added to the table under construction.
4114 ** So create a fake list to simulate this.
4118 Column
*pCol
= &pTab
->aCol
[pTab
->nCol
-1];
4119 pCol
->colFlags
|= COLFLAG_UNIQUE
;
4120 sqlite3TokenInit(&prevCol
, pCol
->zCnName
);
4121 pList
= sqlite3ExprListAppend(pParse
, 0,
4122 sqlite3ExprAlloc(db
, TK_ID
, &prevCol
, 0));
4123 if( pList
==0 ) goto exit_create_index
;
4124 assert( pList
->nExpr
==1 );
4125 sqlite3ExprListSetSortOrder(pList
, sortOrder
, SQLITE_SO_UNDEFINED
);
4127 sqlite3ExprListCheckLength(pParse
, pList
, "index");
4128 if( pParse
->nErr
) goto exit_create_index
;
4131 /* Figure out how many bytes of space are required to store explicitly
4132 ** specified collation sequence names.
4134 for(i
=0; i
<pList
->nExpr
; i
++){
4135 Expr
*pExpr
= pList
->a
[i
].pExpr
;
4137 if( pExpr
->op
==TK_COLLATE
){
4138 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4139 nExtra
+= (1 + sqlite3Strlen30(pExpr
->u
.zToken
));
4144 ** Allocate the index structure.
4146 nName
= sqlite3Strlen30(zName
);
4147 nExtraCol
= pPk
? pPk
->nKeyCol
: 1;
4148 assert( pList
->nExpr
+ nExtraCol
<= 32767 /* Fits in i16 */ );
4149 pIndex
= sqlite3AllocateIndexObject(db
, pList
->nExpr
+ nExtraCol
,
4150 nName
+ nExtra
+ 1, &zExtra
);
4151 if( db
->mallocFailed
){
4152 goto exit_create_index
;
4154 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->aiRowLogEst
) );
4155 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->azColl
) );
4156 pIndex
->zName
= zExtra
;
4157 zExtra
+= nName
+ 1;
4158 memcpy(pIndex
->zName
, zName
, nName
+1);
4159 pIndex
->pTable
= pTab
;
4160 pIndex
->onError
= (u8
)onError
;
4161 pIndex
->uniqNotNull
= onError
!=OE_None
;
4162 pIndex
->idxType
= idxType
;
4163 pIndex
->pSchema
= db
->aDb
[iDb
].pSchema
;
4164 pIndex
->nKeyCol
= pList
->nExpr
;
4166 sqlite3ResolveSelfReference(pParse
, pTab
, NC_PartIdx
, pPIWhere
, 0);
4167 pIndex
->pPartIdxWhere
= pPIWhere
;
4170 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
4172 /* Check to see if we should honor DESC requests on index columns
4174 if( pDb
->pSchema
->file_format
>=4 ){
4175 sortOrderMask
= -1; /* Honor DESC */
4177 sortOrderMask
= 0; /* Ignore DESC */
4180 /* Analyze the list of expressions that form the terms of the index and
4181 ** report any errors. In the common case where the expression is exactly
4182 ** a table column, store that column in aiColumn[]. For general expressions,
4183 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4185 ** TODO: Issue a warning if two or more columns of the index are identical.
4186 ** TODO: Issue a warning if the table primary key is used as part of the
4189 pListItem
= pList
->a
;
4190 if( IN_RENAME_OBJECT
){
4191 pIndex
->aColExpr
= pList
;
4194 for(i
=0; i
<pIndex
->nKeyCol
; i
++, pListItem
++){
4195 Expr
*pCExpr
; /* The i-th index expression */
4196 int requestedSortOrder
; /* ASC or DESC on the i-th expression */
4197 const char *zColl
; /* Collation sequence name */
4199 sqlite3StringToId(pListItem
->pExpr
);
4200 sqlite3ResolveSelfReference(pParse
, pTab
, NC_IdxExpr
, pListItem
->pExpr
, 0);
4201 if( pParse
->nErr
) goto exit_create_index
;
4202 pCExpr
= sqlite3ExprSkipCollate(pListItem
->pExpr
);
4203 if( pCExpr
->op
!=TK_COLUMN
){
4204 if( pTab
==pParse
->pNewTable
){
4205 sqlite3ErrorMsg(pParse
, "expressions prohibited in PRIMARY KEY and "
4206 "UNIQUE constraints");
4207 goto exit_create_index
;
4209 if( pIndex
->aColExpr
==0 ){
4210 pIndex
->aColExpr
= pList
;
4214 pIndex
->aiColumn
[i
] = XN_EXPR
;
4215 pIndex
->uniqNotNull
= 0;
4216 pIndex
->bHasExpr
= 1;
4218 j
= pCExpr
->iColumn
;
4219 assert( j
<=0x7fff );
4223 if( pTab
->aCol
[j
].notNull
==0 ){
4224 pIndex
->uniqNotNull
= 0;
4226 if( pTab
->aCol
[j
].colFlags
& COLFLAG_VIRTUAL
){
4227 pIndex
->bHasVCol
= 1;
4228 pIndex
->bHasExpr
= 1;
4231 pIndex
->aiColumn
[i
] = (i16
)j
;
4234 if( pListItem
->pExpr
->op
==TK_COLLATE
){
4236 assert( !ExprHasProperty(pListItem
->pExpr
, EP_IntValue
) );
4237 zColl
= pListItem
->pExpr
->u
.zToken
;
4238 nColl
= sqlite3Strlen30(zColl
) + 1;
4239 assert( nExtra
>=nColl
);
4240 memcpy(zExtra
, zColl
, nColl
);
4245 zColl
= sqlite3ColumnColl(&pTab
->aCol
[j
]);
4247 if( !zColl
) zColl
= sqlite3StrBINARY
;
4248 if( !db
->init
.busy
&& !sqlite3LocateCollSeq(pParse
, zColl
) ){
4249 goto exit_create_index
;
4251 pIndex
->azColl
[i
] = zColl
;
4252 requestedSortOrder
= pListItem
->fg
.sortFlags
& sortOrderMask
;
4253 pIndex
->aSortOrder
[i
] = (u8
)requestedSortOrder
;
4256 /* Append the table key to the end of the index. For WITHOUT ROWID
4257 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
4258 ** normal tables (when pPk==0) this will be the rowid.
4261 for(j
=0; j
<pPk
->nKeyCol
; j
++){
4262 int x
= pPk
->aiColumn
[j
];
4264 if( isDupColumn(pIndex
, pIndex
->nKeyCol
, pPk
, j
) ){
4267 testcase( hasColumn(pIndex
->aiColumn
,pIndex
->nKeyCol
,x
) );
4268 pIndex
->aiColumn
[i
] = x
;
4269 pIndex
->azColl
[i
] = pPk
->azColl
[j
];
4270 pIndex
->aSortOrder
[i
] = pPk
->aSortOrder
[j
];
4274 assert( i
==pIndex
->nColumn
);
4276 pIndex
->aiColumn
[i
] = XN_ROWID
;
4277 pIndex
->azColl
[i
] = sqlite3StrBINARY
;
4279 sqlite3DefaultRowEst(pIndex
);
4280 if( pParse
->pNewTable
==0 ) estimateIndexWidth(pIndex
);
4282 /* If this index contains every column of its table, then mark
4283 ** it as a covering index */
4284 assert( HasRowid(pTab
)
4285 || pTab
->iPKey
<0 || sqlite3TableColumnToIndex(pIndex
, pTab
->iPKey
)>=0 );
4286 recomputeColumnsNotIndexed(pIndex
);
4287 if( pTblName
!=0 && pIndex
->nColumn
>=pTab
->nCol
){
4288 pIndex
->isCovering
= 1;
4289 for(j
=0; j
<pTab
->nCol
; j
++){
4290 if( j
==pTab
->iPKey
) continue;
4291 if( sqlite3TableColumnToIndex(pIndex
,j
)>=0 ) continue;
4292 pIndex
->isCovering
= 0;
4297 if( pTab
==pParse
->pNewTable
){
4298 /* This routine has been called to create an automatic index as a
4299 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4300 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4303 ** CREATE TABLE t(x PRIMARY KEY, y);
4304 ** CREATE TABLE t(x, y, UNIQUE(x, y));
4306 ** Either way, check to see if the table already has such an index. If
4307 ** so, don't bother creating this one. This only applies to
4308 ** automatically created indices. Users can do as they wish with
4309 ** explicit indices.
4311 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4312 ** (and thus suppressing the second one) even if they have different
4315 ** If there are different collating sequences or if the columns of
4316 ** the constraint occur in different orders, then the constraints are
4317 ** considered distinct and both result in separate indices.
4320 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
4322 assert( IsUniqueIndex(pIdx
) );
4323 assert( pIdx
->idxType
!=SQLITE_IDXTYPE_APPDEF
);
4324 assert( IsUniqueIndex(pIndex
) );
4326 if( pIdx
->nKeyCol
!=pIndex
->nKeyCol
) continue;
4327 for(k
=0; k
<pIdx
->nKeyCol
; k
++){
4330 assert( pIdx
->aiColumn
[k
]>=0 );
4331 if( pIdx
->aiColumn
[k
]!=pIndex
->aiColumn
[k
] ) break;
4332 z1
= pIdx
->azColl
[k
];
4333 z2
= pIndex
->azColl
[k
];
4334 if( sqlite3StrICmp(z1
, z2
) ) break;
4336 if( k
==pIdx
->nKeyCol
){
4337 if( pIdx
->onError
!=pIndex
->onError
){
4338 /* This constraint creates the same index as a previous
4339 ** constraint specified somewhere in the CREATE TABLE statement.
4340 ** However the ON CONFLICT clauses are different. If both this
4341 ** constraint and the previous equivalent constraint have explicit
4342 ** ON CONFLICT clauses this is an error. Otherwise, use the
4343 ** explicitly specified behavior for the index.
4345 if( !(pIdx
->onError
==OE_Default
|| pIndex
->onError
==OE_Default
) ){
4346 sqlite3ErrorMsg(pParse
,
4347 "conflicting ON CONFLICT clauses specified", 0);
4349 if( pIdx
->onError
==OE_Default
){
4350 pIdx
->onError
= pIndex
->onError
;
4353 if( idxType
==SQLITE_IDXTYPE_PRIMARYKEY
) pIdx
->idxType
= idxType
;
4354 if( IN_RENAME_OBJECT
){
4355 pIndex
->pNext
= pParse
->pNewIndex
;
4356 pParse
->pNewIndex
= pIndex
;
4359 goto exit_create_index
;
4364 if( !IN_RENAME_OBJECT
){
4366 /* Link the new Index structure to its table and to the other
4367 ** in-memory database structures.
4369 assert( pParse
->nErr
==0 );
4370 if( db
->init
.busy
){
4372 assert( !IN_SPECIAL_PARSE
);
4373 assert( sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
4375 pIndex
->tnum
= db
->init
.newTnum
;
4376 if( sqlite3IndexHasDuplicateRootPage(pIndex
) ){
4377 sqlite3ErrorMsg(pParse
, "invalid rootpage");
4378 pParse
->rc
= SQLITE_CORRUPT_BKPT
;
4379 goto exit_create_index
;
4382 p
= sqlite3HashInsert(&pIndex
->pSchema
->idxHash
,
4383 pIndex
->zName
, pIndex
);
4385 assert( p
==pIndex
); /* Malloc must have failed */
4386 sqlite3OomFault(db
);
4387 goto exit_create_index
;
4389 db
->mDbFlags
|= DBFLAG_SchemaChange
;
4392 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4393 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4394 ** emit code to allocate the index rootpage on disk and make an entry for
4395 ** the index in the sqlite_schema table and populate the index with
4396 ** content. But, do not do this if we are simply reading the sqlite_schema
4397 ** table to parse the schema, or if this index is the PRIMARY KEY index
4398 ** of a WITHOUT ROWID table.
4400 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4401 ** or UNIQUE index in a CREATE TABLE statement. Since the table
4402 ** has just been created, it contains no data and the index initialization
4403 ** step can be skipped.
4405 else if( HasRowid(pTab
) || pTblName
!=0 ){
4408 int iMem
= ++pParse
->nMem
;
4410 v
= sqlite3GetVdbe(pParse
);
4411 if( v
==0 ) goto exit_create_index
;
4413 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
4415 /* Create the rootpage for the index using CreateIndex. But before
4416 ** doing so, code a Noop instruction and store its address in
4417 ** Index.tnum. This is required in case this index is actually a
4418 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4419 ** that case the convertToWithoutRowidTable() routine will replace
4420 ** the Noop with a Goto to jump over the VDBE code generated below. */
4421 pIndex
->tnum
= (Pgno
)sqlite3VdbeAddOp0(v
, OP_Noop
);
4422 sqlite3VdbeAddOp3(v
, OP_CreateBtree
, iDb
, iMem
, BTREE_BLOBKEY
);
4424 /* Gather the complete text of the CREATE INDEX statement into
4425 ** the zStmt variable
4427 assert( pName
!=0 || pStart
==0 );
4429 int n
= (int)(pParse
->sLastToken
.z
- pName
->z
) + pParse
->sLastToken
.n
;
4430 if( pName
->z
[n
-1]==';' ) n
--;
4431 /* A named index with an explicit CREATE INDEX statement */
4432 zStmt
= sqlite3MPrintf(db
, "CREATE%s INDEX %.*s",
4433 onError
==OE_None
? "" : " UNIQUE", n
, pName
->z
);
4435 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4436 /* zStmt = sqlite3MPrintf(""); */
4440 /* Add an entry in sqlite_schema for this index
4442 sqlite3NestedParse(pParse
,
4443 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
" VALUES('index',%Q,%Q,#%d,%Q);",
4444 db
->aDb
[iDb
].zDbSName
,
4450 sqlite3DbFree(db
, zStmt
);
4452 /* Fill the index with data and reparse the schema. Code an OP_Expire
4453 ** to invalidate all pre-compiled statements.
4456 sqlite3RefillIndex(pParse
, pIndex
, iMem
);
4457 sqlite3ChangeCookie(pParse
, iDb
);
4458 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
4459 sqlite3MPrintf(db
, "name='%q' AND type='index'", pIndex
->zName
), 0);
4460 sqlite3VdbeAddOp2(v
, OP_Expire
, 0, 1);
4463 sqlite3VdbeJumpHere(v
, (int)pIndex
->tnum
);
4466 if( db
->init
.busy
|| pTblName
==0 ){
4467 pIndex
->pNext
= pTab
->pIndex
;
4468 pTab
->pIndex
= pIndex
;
4471 else if( IN_RENAME_OBJECT
){
4472 assert( pParse
->pNewIndex
==0 );
4473 pParse
->pNewIndex
= pIndex
;
4477 /* Clean up before exiting */
4479 if( pIndex
) sqlite3FreeIndex(db
, pIndex
);
4481 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
4482 ** The list was already ordered when this routine was entered, so at this
4483 ** point at most a single index (the newly added index) will be out of
4484 ** order. So we have to reorder at most one index. */
4487 for(ppFrom
=&pTab
->pIndex
; (pThis
= *ppFrom
)!=0; ppFrom
=&pThis
->pNext
){
4489 if( pThis
->onError
!=OE_Replace
) continue;
4490 while( (pNext
= pThis
->pNext
)!=0 && pNext
->onError
!=OE_Replace
){
4492 pThis
->pNext
= pNext
->pNext
;
4493 pNext
->pNext
= pThis
;
4494 ppFrom
= &pNext
->pNext
;
4499 /* Verify that all REPLACE indexes really are now at the end
4500 ** of the index list. In other words, no other index type ever
4501 ** comes after a REPLACE index on the list. */
4502 for(pThis
= pTab
->pIndex
; pThis
; pThis
=pThis
->pNext
){
4503 assert( pThis
->onError
!=OE_Replace
4505 || pThis
->pNext
->onError
==OE_Replace
);
4509 sqlite3ExprDelete(db
, pPIWhere
);
4510 sqlite3ExprListDelete(db
, pList
);
4511 sqlite3SrcListDelete(db
, pTblName
);
4512 sqlite3DbFree(db
, zName
);
4516 ** Fill the Index.aiRowEst[] array with default information - information
4517 ** to be used when we have not run the ANALYZE command.
4519 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4520 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
4521 ** number of rows in the table that match any particular value of the
4522 ** first column of the index. aiRowEst[2] is an estimate of the number
4523 ** of rows that match any particular combination of the first 2 columns
4524 ** of the index. And so forth. It must always be the case that
4526 ** aiRowEst[N]<=aiRowEst[N-1]
4529 ** Apart from that, we have little to go on besides intuition as to
4530 ** how aiRowEst[] should be initialized. The numbers generated here
4531 ** are based on typical values found in actual indices.
4533 void sqlite3DefaultRowEst(Index
*pIdx
){
4534 /* 10, 9, 8, 7, 6 */
4535 static const LogEst aVal
[] = { 33, 32, 30, 28, 26 };
4536 LogEst
*a
= pIdx
->aiRowLogEst
;
4538 int nCopy
= MIN(ArraySize(aVal
), pIdx
->nKeyCol
);
4541 /* Indexes with default row estimates should not have stat1 data */
4542 assert( !pIdx
->hasStat1
);
4544 /* Set the first entry (number of rows in the index) to the estimated
4545 ** number of rows in the table, or half the number of rows in the table
4546 ** for a partial index.
4548 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
4549 ** table but other parts we are having to guess at, then do not let the
4550 ** estimated number of rows in the table be less than 1000 (LogEst 99).
4551 ** Failure to do this can cause the indexes for which we do not have
4552 ** stat1 data to be ignored by the query planner.
4554 x
= pIdx
->pTable
->nRowLogEst
;
4555 assert( 99==sqlite3LogEst(1000) );
4557 pIdx
->pTable
->nRowLogEst
= x
= 99;
4559 if( pIdx
->pPartIdxWhere
!=0 ){ x
-= 10; assert( 10==sqlite3LogEst(2) ); }
4562 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4563 ** 6 and each subsequent value (if any) is 5. */
4564 memcpy(&a
[1], aVal
, nCopy
*sizeof(LogEst
));
4565 for(i
=nCopy
+1; i
<=pIdx
->nKeyCol
; i
++){
4566 a
[i
] = 23; assert( 23==sqlite3LogEst(5) );
4569 assert( 0==sqlite3LogEst(1) );
4570 if( IsUniqueIndex(pIdx
) ) a
[pIdx
->nKeyCol
] = 0;
4574 ** This routine will drop an existing named index. This routine
4575 ** implements the DROP INDEX statement.
4577 void sqlite3DropIndex(Parse
*pParse
, SrcList
*pName
, int ifExists
){
4580 sqlite3
*db
= pParse
->db
;
4583 if( db
->mallocFailed
){
4584 goto exit_drop_index
;
4586 assert( pParse
->nErr
==0 ); /* Never called with prior non-OOM errors */
4587 assert( pName
->nSrc
==1 );
4588 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
4589 goto exit_drop_index
;
4591 pIndex
= sqlite3FindIndex(db
, pName
->a
[0].zName
, pName
->a
[0].zDatabase
);
4594 sqlite3ErrorMsg(pParse
, "no such index: %S", pName
->a
);
4596 sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
4597 sqlite3ForceNotReadOnly(pParse
);
4599 pParse
->checkSchema
= 1;
4600 goto exit_drop_index
;
4602 if( pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
){
4603 sqlite3ErrorMsg(pParse
, "index associated with UNIQUE "
4604 "or PRIMARY KEY constraint cannot be dropped", 0);
4605 goto exit_drop_index
;
4607 iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
4608 #ifndef SQLITE_OMIT_AUTHORIZATION
4610 int code
= SQLITE_DROP_INDEX
;
4611 Table
*pTab
= pIndex
->pTable
;
4612 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
4613 const char *zTab
= SCHEMA_TABLE(iDb
);
4614 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
) ){
4615 goto exit_drop_index
;
4617 if( !OMIT_TEMPDB
&& iDb
==1 ) code
= SQLITE_DROP_TEMP_INDEX
;
4618 if( sqlite3AuthCheck(pParse
, code
, pIndex
->zName
, pTab
->zName
, zDb
) ){
4619 goto exit_drop_index
;
4624 /* Generate code to remove the index and from the schema table */
4625 v
= sqlite3GetVdbe(pParse
);
4627 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
4628 sqlite3NestedParse(pParse
,
4629 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
" WHERE name=%Q AND type='index'",
4630 db
->aDb
[iDb
].zDbSName
, pIndex
->zName
4632 sqlite3ClearStatTables(pParse
, iDb
, "idx", pIndex
->zName
);
4633 sqlite3ChangeCookie(pParse
, iDb
);
4634 destroyRootPage(pParse
, pIndex
->tnum
, iDb
);
4635 sqlite3VdbeAddOp4(v
, OP_DropIndex
, iDb
, 0, 0, pIndex
->zName
, 0);
4639 sqlite3SrcListDelete(db
, pName
);
4643 ** pArray is a pointer to an array of objects. Each object in the
4644 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4645 ** to extend the array so that there is space for a new object at the end.
4647 ** When this function is called, *pnEntry contains the current size of
4648 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4651 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4652 ** space allocated for the new object is zeroed, *pnEntry updated to
4653 ** reflect the new size of the array and a pointer to the new allocation
4654 ** returned. *pIdx is set to the index of the new array entry in this case.
4656 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4657 ** unchanged and a copy of pArray returned.
4659 void *sqlite3ArrayAllocate(
4660 sqlite3
*db
, /* Connection to notify of malloc failures */
4661 void *pArray
, /* Array of objects. Might be reallocated */
4662 int szEntry
, /* Size of each object in the array */
4663 int *pnEntry
, /* Number of objects currently in use */
4664 int *pIdx
/* Write the index of a new slot here */
4667 sqlite3_int64 n
= *pIdx
= *pnEntry
;
4668 if( (n
& (n
-1))==0 ){
4669 sqlite3_int64 sz
= (n
==0) ? 1 : 2*n
;
4670 void *pNew
= sqlite3DbRealloc(db
, pArray
, sz
*szEntry
);
4678 memset(&z
[n
* szEntry
], 0, szEntry
);
4684 ** Append a new element to the given IdList. Create a new IdList if
4687 ** A new IdList is returned, or NULL if malloc() fails.
4689 IdList
*sqlite3IdListAppend(Parse
*pParse
, IdList
*pList
, Token
*pToken
){
4690 sqlite3
*db
= pParse
->db
;
4693 pList
= sqlite3DbMallocZero(db
, sizeof(IdList
) );
4694 if( pList
==0 ) return 0;
4697 pNew
= sqlite3DbRealloc(db
, pList
,
4698 sizeof(IdList
) + pList
->nId
*sizeof(pList
->a
));
4700 sqlite3IdListDelete(db
, pList
);
4706 pList
->a
[i
].zName
= sqlite3NameFromToken(db
, pToken
);
4707 if( IN_RENAME_OBJECT
&& pList
->a
[i
].zName
){
4708 sqlite3RenameTokenMap(pParse
, (void*)pList
->a
[i
].zName
, pToken
);
4714 ** Delete an IdList.
4716 void sqlite3IdListDelete(sqlite3
*db
, IdList
*pList
){
4719 if( pList
==0 ) return;
4720 assert( pList
->eU4
!=EU4_EXPR
); /* EU4_EXPR mode is not currently used */
4721 for(i
=0; i
<pList
->nId
; i
++){
4722 sqlite3DbFree(db
, pList
->a
[i
].zName
);
4724 sqlite3DbNNFreeNN(db
, pList
);
4728 ** Return the index in pList of the identifier named zId. Return -1
4731 int sqlite3IdListIndex(IdList
*pList
, const char *zName
){
4734 for(i
=0; i
<pList
->nId
; i
++){
4735 if( sqlite3StrICmp(pList
->a
[i
].zName
, zName
)==0 ) return i
;
4741 ** Maximum size of a SrcList object.
4742 ** The SrcList object is used to represent the FROM clause of a
4743 ** SELECT statement, and the query planner cannot deal with more
4744 ** than 64 tables in a join. So any value larger than 64 here
4745 ** is sufficient for most uses. Smaller values, like say 10, are
4746 ** appropriate for small and memory-limited applications.
4748 #ifndef SQLITE_MAX_SRCLIST
4749 # define SQLITE_MAX_SRCLIST 200
4753 ** Expand the space allocated for the given SrcList object by
4754 ** creating nExtra new slots beginning at iStart. iStart is zero based.
4755 ** New slots are zeroed.
4757 ** For example, suppose a SrcList initially contains two entries: A,B.
4758 ** To append 3 new entries onto the end, do this:
4760 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4762 ** After the call above it would contain: A, B, nil, nil, nil.
4763 ** If the iStart argument had been 1 instead of 2, then the result
4764 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
4765 ** the iStart value would be 0. The result then would
4766 ** be: nil, nil, nil, A, B.
4768 ** If a memory allocation fails or the SrcList becomes too large, leave
4769 ** the original SrcList unchanged, return NULL, and leave an error message
4772 SrcList
*sqlite3SrcListEnlarge(
4773 Parse
*pParse
, /* Parsing context into which errors are reported */
4774 SrcList
*pSrc
, /* The SrcList to be enlarged */
4775 int nExtra
, /* Number of new slots to add to pSrc->a[] */
4776 int iStart
/* Index in pSrc->a[] of first new slot */
4780 /* Sanity checking on calling parameters */
4781 assert( iStart
>=0 );
4782 assert( nExtra
>=1 );
4784 assert( iStart
<=pSrc
->nSrc
);
4786 /* Allocate additional space if needed */
4787 if( (u32
)pSrc
->nSrc
+nExtra
>pSrc
->nAlloc
){
4789 sqlite3_int64 nAlloc
= 2*(sqlite3_int64
)pSrc
->nSrc
+nExtra
;
4790 sqlite3
*db
= pParse
->db
;
4792 if( pSrc
->nSrc
+nExtra
>=SQLITE_MAX_SRCLIST
){
4793 sqlite3ErrorMsg(pParse
, "too many FROM clause terms, max: %d",
4794 SQLITE_MAX_SRCLIST
);
4797 if( nAlloc
>SQLITE_MAX_SRCLIST
) nAlloc
= SQLITE_MAX_SRCLIST
;
4798 pNew
= sqlite3DbRealloc(db
, pSrc
,
4799 sizeof(*pSrc
) + (nAlloc
-1)*sizeof(pSrc
->a
[0]) );
4801 assert( db
->mallocFailed
);
4805 pSrc
->nAlloc
= nAlloc
;
4808 /* Move existing slots that come after the newly inserted slots
4809 ** out of the way */
4810 for(i
=pSrc
->nSrc
-1; i
>=iStart
; i
--){
4811 pSrc
->a
[i
+nExtra
] = pSrc
->a
[i
];
4813 pSrc
->nSrc
+= nExtra
;
4815 /* Zero the newly allocated slots */
4816 memset(&pSrc
->a
[iStart
], 0, sizeof(pSrc
->a
[0])*nExtra
);
4817 for(i
=iStart
; i
<iStart
+nExtra
; i
++){
4818 pSrc
->a
[i
].iCursor
= -1;
4821 /* Return a pointer to the enlarged SrcList */
4827 ** Append a new table name to the given SrcList. Create a new SrcList if
4828 ** need be. A new entry is created in the SrcList even if pTable is NULL.
4830 ** A SrcList is returned, or NULL if there is an OOM error or if the
4831 ** SrcList grows to large. The returned
4832 ** SrcList might be the same as the SrcList that was input or it might be
4833 ** a new one. If an OOM error does occurs, then the prior value of pList
4834 ** that is input to this routine is automatically freed.
4836 ** If pDatabase is not null, it means that the table has an optional
4837 ** database name prefix. Like this: "database.table". The pDatabase
4838 ** points to the table name and the pTable points to the database name.
4839 ** The SrcList.a[].zName field is filled with the table name which might
4840 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4841 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4842 ** or with NULL if no database is specified.
4844 ** In other words, if call like this:
4846 ** sqlite3SrcListAppend(D,A,B,0);
4848 ** Then B is a table name and the database name is unspecified. If called
4851 ** sqlite3SrcListAppend(D,A,B,C);
4853 ** Then C is the table name and B is the database name. If C is defined
4854 ** then so is B. In other words, we never have a case where:
4856 ** sqlite3SrcListAppend(D,A,0,C);
4858 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
4859 ** before being added to the SrcList.
4861 SrcList
*sqlite3SrcListAppend(
4862 Parse
*pParse
, /* Parsing context, in which errors are reported */
4863 SrcList
*pList
, /* Append to this SrcList. NULL creates a new SrcList */
4864 Token
*pTable
, /* Table to append */
4865 Token
*pDatabase
/* Database of the table */
4869 assert( pDatabase
==0 || pTable
!=0 ); /* Cannot have C without B */
4870 assert( pParse
!=0 );
4871 assert( pParse
->db
!=0 );
4874 pList
= sqlite3DbMallocRawNN(pParse
->db
, sizeof(SrcList
) );
4875 if( pList
==0 ) return 0;
4878 memset(&pList
->a
[0], 0, sizeof(pList
->a
[0]));
4879 pList
->a
[0].iCursor
= -1;
4881 SrcList
*pNew
= sqlite3SrcListEnlarge(pParse
, pList
, 1, pList
->nSrc
);
4883 sqlite3SrcListDelete(db
, pList
);
4889 pItem
= &pList
->a
[pList
->nSrc
-1];
4890 if( pDatabase
&& pDatabase
->z
==0 ){
4894 pItem
->zName
= sqlite3NameFromToken(db
, pDatabase
);
4895 pItem
->zDatabase
= sqlite3NameFromToken(db
, pTable
);
4897 pItem
->zName
= sqlite3NameFromToken(db
, pTable
);
4898 pItem
->zDatabase
= 0;
4904 ** Assign VdbeCursor index numbers to all tables in a SrcList
4906 void sqlite3SrcListAssignCursors(Parse
*pParse
, SrcList
*pList
){
4909 assert( pList
|| pParse
->db
->mallocFailed
);
4910 if( ALWAYS(pList
) ){
4911 for(i
=0, pItem
=pList
->a
; i
<pList
->nSrc
; i
++, pItem
++){
4912 if( pItem
->iCursor
>=0 ) continue;
4913 pItem
->iCursor
= pParse
->nTab
++;
4914 if( pItem
->pSelect
){
4915 sqlite3SrcListAssignCursors(pParse
, pItem
->pSelect
->pSrc
);
4922 ** Delete an entire SrcList including all its substructure.
4924 void sqlite3SrcListDelete(sqlite3
*db
, SrcList
*pList
){
4928 if( pList
==0 ) return;
4929 for(pItem
=pList
->a
, i
=0; i
<pList
->nSrc
; i
++, pItem
++){
4930 if( pItem
->zDatabase
) sqlite3DbNNFreeNN(db
, pItem
->zDatabase
);
4931 if( pItem
->zName
) sqlite3DbNNFreeNN(db
, pItem
->zName
);
4932 if( pItem
->zAlias
) sqlite3DbNNFreeNN(db
, pItem
->zAlias
);
4933 if( pItem
->fg
.isIndexedBy
) sqlite3DbFree(db
, pItem
->u1
.zIndexedBy
);
4934 if( pItem
->fg
.isTabFunc
) sqlite3ExprListDelete(db
, pItem
->u1
.pFuncArg
);
4935 sqlite3DeleteTable(db
, pItem
->pTab
);
4936 if( pItem
->pSelect
) sqlite3SelectDelete(db
, pItem
->pSelect
);
4937 if( pItem
->fg
.isUsing
){
4938 sqlite3IdListDelete(db
, pItem
->u3
.pUsing
);
4939 }else if( pItem
->u3
.pOn
){
4940 sqlite3ExprDelete(db
, pItem
->u3
.pOn
);
4943 sqlite3DbNNFreeNN(db
, pList
);
4947 ** This routine is called by the parser to add a new term to the
4948 ** end of a growing FROM clause. The "p" parameter is the part of
4949 ** the FROM clause that has already been constructed. "p" is NULL
4950 ** if this is the first term of the FROM clause. pTable and pDatabase
4951 ** are the name of the table and database named in the FROM clause term.
4952 ** pDatabase is NULL if the database name qualifier is missing - the
4953 ** usual case. If the term has an alias, then pAlias points to the
4954 ** alias token. If the term is a subquery, then pSubquery is the
4955 ** SELECT statement that the subquery encodes. The pTable and
4956 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
4957 ** parameters are the content of the ON and USING clauses.
4959 ** Return a new SrcList which encodes is the FROM with the new
4962 SrcList
*sqlite3SrcListAppendFromTerm(
4963 Parse
*pParse
, /* Parsing context */
4964 SrcList
*p
, /* The left part of the FROM clause already seen */
4965 Token
*pTable
, /* Name of the table to add to the FROM clause */
4966 Token
*pDatabase
, /* Name of the database containing pTable */
4967 Token
*pAlias
, /* The right-hand side of the AS subexpression */
4968 Select
*pSubquery
, /* A subquery used in place of a table name */
4969 OnOrUsing
*pOnUsing
/* Either the ON clause or the USING clause */
4972 sqlite3
*db
= pParse
->db
;
4973 if( !p
&& pOnUsing
!=0 && (pOnUsing
->pOn
|| pOnUsing
->pUsing
) ){
4974 sqlite3ErrorMsg(pParse
, "a JOIN clause is required before %s",
4975 (pOnUsing
->pOn
? "ON" : "USING")
4977 goto append_from_error
;
4979 p
= sqlite3SrcListAppend(pParse
, p
, pTable
, pDatabase
);
4981 goto append_from_error
;
4983 assert( p
->nSrc
>0 );
4984 pItem
= &p
->a
[p
->nSrc
-1];
4985 assert( (pTable
==0)==(pDatabase
==0) );
4986 assert( pItem
->zName
==0 || pDatabase
!=0 );
4987 if( IN_RENAME_OBJECT
&& pItem
->zName
){
4988 Token
*pToken
= (ALWAYS(pDatabase
) && pDatabase
->z
) ? pDatabase
: pTable
;
4989 sqlite3RenameTokenMap(pParse
, pItem
->zName
, pToken
);
4991 assert( pAlias
!=0 );
4993 pItem
->zAlias
= sqlite3NameFromToken(db
, pAlias
);
4996 pItem
->pSelect
= pSubquery
;
4997 if( pSubquery
->selFlags
& SF_NestedFrom
){
4998 pItem
->fg
.isNestedFrom
= 1;
5001 assert( pOnUsing
==0 || pOnUsing
->pOn
==0 || pOnUsing
->pUsing
==0 );
5002 assert( pItem
->fg
.isUsing
==0 );
5005 }else if( pOnUsing
->pUsing
){
5006 pItem
->fg
.isUsing
= 1;
5007 pItem
->u3
.pUsing
= pOnUsing
->pUsing
;
5009 pItem
->u3
.pOn
= pOnUsing
->pOn
;
5015 sqlite3ClearOnOrUsing(db
, pOnUsing
);
5016 sqlite3SelectDelete(db
, pSubquery
);
5021 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5022 ** element of the source-list passed as the second argument.
5024 void sqlite3SrcListIndexedBy(Parse
*pParse
, SrcList
*p
, Token
*pIndexedBy
){
5025 assert( pIndexedBy
!=0 );
5026 if( p
&& pIndexedBy
->n
>0 ){
5028 assert( p
->nSrc
>0 );
5029 pItem
= &p
->a
[p
->nSrc
-1];
5030 assert( pItem
->fg
.notIndexed
==0 );
5031 assert( pItem
->fg
.isIndexedBy
==0 );
5032 assert( pItem
->fg
.isTabFunc
==0 );
5033 if( pIndexedBy
->n
==1 && !pIndexedBy
->z
){
5034 /* A "NOT INDEXED" clause was supplied. See parse.y
5035 ** construct "indexed_opt" for details. */
5036 pItem
->fg
.notIndexed
= 1;
5038 pItem
->u1
.zIndexedBy
= sqlite3NameFromToken(pParse
->db
, pIndexedBy
);
5039 pItem
->fg
.isIndexedBy
= 1;
5040 assert( pItem
->fg
.isCte
==0 ); /* No collision on union u2 */
5046 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
5047 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
5048 ** are deleted by this function.
5050 SrcList
*sqlite3SrcListAppendList(Parse
*pParse
, SrcList
*p1
, SrcList
*p2
){
5051 assert( p1
&& p1
->nSrc
==1 );
5053 SrcList
*pNew
= sqlite3SrcListEnlarge(pParse
, p1
, p2
->nSrc
, 1);
5055 sqlite3SrcListDelete(pParse
->db
, p2
);
5058 memcpy(&p1
->a
[1], p2
->a
, p2
->nSrc
*sizeof(SrcItem
));
5059 sqlite3DbFree(pParse
->db
, p2
);
5060 p1
->a
[0].fg
.jointype
|= (JT_LTORJ
& p1
->a
[1].fg
.jointype
);
5067 ** Add the list of function arguments to the SrcList entry for a
5068 ** table-valued-function.
5070 void sqlite3SrcListFuncArgs(Parse
*pParse
, SrcList
*p
, ExprList
*pList
){
5072 SrcItem
*pItem
= &p
->a
[p
->nSrc
-1];
5073 assert( pItem
->fg
.notIndexed
==0 );
5074 assert( pItem
->fg
.isIndexedBy
==0 );
5075 assert( pItem
->fg
.isTabFunc
==0 );
5076 pItem
->u1
.pFuncArg
= pList
;
5077 pItem
->fg
.isTabFunc
= 1;
5079 sqlite3ExprListDelete(pParse
->db
, pList
);
5084 ** When building up a FROM clause in the parser, the join operator
5085 ** is initially attached to the left operand. But the code generator
5086 ** expects the join operator to be on the right operand. This routine
5087 ** Shifts all join operators from left to right for an entire FROM
5090 ** Example: Suppose the join is like this:
5092 ** A natural cross join B
5094 ** The operator is "natural cross join". The A and B operands are stored
5095 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
5096 ** operator with A. This routine shifts that operator over to B.
5098 ** Additional changes:
5100 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
5101 ** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
5102 ** code generator can easily tell that the table is part of
5103 ** the left operand of at least one RIGHT JOIN.
5105 void sqlite3SrcListShiftJoinType(Parse
*pParse
, SrcList
*p
){
5107 if( p
&& p
->nSrc
>1 ){
5111 allFlags
|= p
->a
[i
].fg
.jointype
= p
->a
[i
-1].fg
.jointype
;
5113 p
->a
[0].fg
.jointype
= 0;
5115 /* All terms to the left of a RIGHT JOIN should be tagged with the
5116 ** JT_LTORJ flags */
5117 if( allFlags
& JT_RIGHT
){
5118 for(i
=p
->nSrc
-1; ALWAYS(i
>0) && (p
->a
[i
].fg
.jointype
&JT_RIGHT
)==0; i
--){}
5122 p
->a
[i
].fg
.jointype
|= JT_LTORJ
;
5129 ** Generate VDBE code for a BEGIN statement.
5131 void sqlite3BeginTransaction(Parse
*pParse
, int type
){
5136 assert( pParse
!=0 );
5139 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
, "BEGIN", 0, 0) ){
5142 v
= sqlite3GetVdbe(pParse
);
5144 if( type
!=TK_DEFERRED
){
5145 for(i
=0; i
<db
->nDb
; i
++){
5147 Btree
*pBt
= db
->aDb
[i
].pBt
;
5148 if( pBt
&& sqlite3BtreeIsReadonly(pBt
) ){
5149 eTxnType
= 0; /* Read txn */
5150 }else if( type
==TK_EXCLUSIVE
){
5151 eTxnType
= 2; /* Exclusive txn */
5153 eTxnType
= 1; /* Write txn */
5155 sqlite3VdbeAddOp2(v
, OP_Transaction
, i
, eTxnType
);
5156 sqlite3VdbeUsesBtree(v
, i
);
5159 sqlite3VdbeAddOp0(v
, OP_AutoCommit
);
5163 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
5164 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
5165 ** code is generated for a COMMIT.
5167 void sqlite3EndTransaction(Parse
*pParse
, int eType
){
5171 assert( pParse
!=0 );
5172 assert( pParse
->db
!=0 );
5173 assert( eType
==TK_COMMIT
|| eType
==TK_END
|| eType
==TK_ROLLBACK
);
5174 isRollback
= eType
==TK_ROLLBACK
;
5175 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
,
5176 isRollback
? "ROLLBACK" : "COMMIT", 0, 0) ){
5179 v
= sqlite3GetVdbe(pParse
);
5181 sqlite3VdbeAddOp2(v
, OP_AutoCommit
, 1, isRollback
);
5186 ** This function is called by the parser when it parses a command to create,
5187 ** release or rollback an SQL savepoint.
5189 void sqlite3Savepoint(Parse
*pParse
, int op
, Token
*pName
){
5190 char *zName
= sqlite3NameFromToken(pParse
->db
, pName
);
5192 Vdbe
*v
= sqlite3GetVdbe(pParse
);
5193 #ifndef SQLITE_OMIT_AUTHORIZATION
5194 static const char * const az
[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5195 assert( !SAVEPOINT_BEGIN
&& SAVEPOINT_RELEASE
==1 && SAVEPOINT_ROLLBACK
==2 );
5197 if( !v
|| sqlite3AuthCheck(pParse
, SQLITE_SAVEPOINT
, az
[op
], zName
, 0) ){
5198 sqlite3DbFree(pParse
->db
, zName
);
5201 sqlite3VdbeAddOp4(v
, OP_Savepoint
, op
, 0, 0, zName
, P4_DYNAMIC
);
5206 ** Make sure the TEMP database is open and available for use. Return
5207 ** the number of errors. Leave any error messages in the pParse structure.
5209 int sqlite3OpenTempDatabase(Parse
*pParse
){
5210 sqlite3
*db
= pParse
->db
;
5211 if( db
->aDb
[1].pBt
==0 && !pParse
->explain
){
5214 static const int flags
=
5215 SQLITE_OPEN_READWRITE
|
5216 SQLITE_OPEN_CREATE
|
5217 SQLITE_OPEN_EXCLUSIVE
|
5218 SQLITE_OPEN_DELETEONCLOSE
|
5219 SQLITE_OPEN_TEMP_DB
;
5221 rc
= sqlite3BtreeOpen(db
->pVfs
, 0, db
, &pBt
, 0, flags
);
5222 if( rc
!=SQLITE_OK
){
5223 sqlite3ErrorMsg(pParse
, "unable to open a temporary database "
5224 "file for storing temporary tables");
5228 db
->aDb
[1].pBt
= pBt
;
5229 assert( db
->aDb
[1].pSchema
);
5230 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
, 0, 0) ){
5231 sqlite3OomFault(db
);
5239 ** Record the fact that the schema cookie will need to be verified
5240 ** for database iDb. The code to actually verify the schema cookie
5241 ** will occur at the end of the top-level VDBE and will be generated
5242 ** later, by sqlite3FinishCoding().
5244 static void sqlite3CodeVerifySchemaAtToplevel(Parse
*pToplevel
, int iDb
){
5245 assert( iDb
>=0 && iDb
<pToplevel
->db
->nDb
);
5246 assert( pToplevel
->db
->aDb
[iDb
].pBt
!=0 || iDb
==1 );
5247 assert( iDb
<SQLITE_MAX_DB
);
5248 assert( sqlite3SchemaMutexHeld(pToplevel
->db
, iDb
, 0) );
5249 if( DbMaskTest(pToplevel
->cookieMask
, iDb
)==0 ){
5250 DbMaskSet(pToplevel
->cookieMask
, iDb
);
5251 if( !OMIT_TEMPDB
&& iDb
==1 ){
5252 sqlite3OpenTempDatabase(pToplevel
);
5256 void sqlite3CodeVerifySchema(Parse
*pParse
, int iDb
){
5257 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse
), iDb
);
5262 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
5263 ** attached database. Otherwise, invoke it for the database named zDb only.
5265 void sqlite3CodeVerifyNamedSchema(Parse
*pParse
, const char *zDb
){
5266 sqlite3
*db
= pParse
->db
;
5268 for(i
=0; i
<db
->nDb
; i
++){
5269 Db
*pDb
= &db
->aDb
[i
];
5270 if( pDb
->pBt
&& (!zDb
|| 0==sqlite3StrICmp(zDb
, pDb
->zDbSName
)) ){
5271 sqlite3CodeVerifySchema(pParse
, i
);
5277 ** Generate VDBE code that prepares for doing an operation that
5278 ** might change the database.
5280 ** This routine starts a new transaction if we are not already within
5281 ** a transaction. If we are already within a transaction, then a checkpoint
5282 ** is set if the setStatement parameter is true. A checkpoint should
5283 ** be set for operations that might fail (due to a constraint) part of
5284 ** the way through and which will need to undo some writes without having to
5285 ** rollback the whole transaction. For operations where all constraints
5286 ** can be checked before any changes are made to the database, it is never
5287 ** necessary to undo a write and the checkpoint should not be set.
5289 void sqlite3BeginWriteOperation(Parse
*pParse
, int setStatement
, int iDb
){
5290 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
5291 sqlite3CodeVerifySchemaAtToplevel(pToplevel
, iDb
);
5292 DbMaskSet(pToplevel
->writeMask
, iDb
);
5293 pToplevel
->isMultiWrite
|= setStatement
;
5297 ** Indicate that the statement currently under construction might write
5298 ** more than one entry (example: deleting one row then inserting another,
5299 ** inserting multiple rows in a table, or inserting a row and index entries.)
5300 ** If an abort occurs after some of these writes have completed, then it will
5301 ** be necessary to undo the completed writes.
5303 void sqlite3MultiWrite(Parse
*pParse
){
5304 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
5305 pToplevel
->isMultiWrite
= 1;
5309 ** The code generator calls this routine if is discovers that it is
5310 ** possible to abort a statement prior to completion. In order to
5311 ** perform this abort without corrupting the database, we need to make
5312 ** sure that the statement is protected by a statement transaction.
5314 ** Technically, we only need to set the mayAbort flag if the
5315 ** isMultiWrite flag was previously set. There is a time dependency
5316 ** such that the abort must occur after the multiwrite. This makes
5317 ** some statements involving the REPLACE conflict resolution algorithm
5318 ** go a little faster. But taking advantage of this time dependency
5319 ** makes it more difficult to prove that the code is correct (in
5320 ** particular, it prevents us from writing an effective
5321 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
5322 ** to take the safe route and skip the optimization.
5324 void sqlite3MayAbort(Parse
*pParse
){
5325 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
5326 pToplevel
->mayAbort
= 1;
5330 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5331 ** error. The onError parameter determines which (if any) of the statement
5332 ** and/or current transaction is rolled back.
5334 void sqlite3HaltConstraint(
5335 Parse
*pParse
, /* Parsing context */
5336 int errCode
, /* extended error code */
5337 int onError
, /* Constraint type */
5338 char *p4
, /* Error message */
5339 i8 p4type
, /* P4_STATIC or P4_TRANSIENT */
5340 u8 p5Errmsg
/* P5_ErrMsg type */
5343 assert( pParse
->pVdbe
!=0 );
5344 v
= sqlite3GetVdbe(pParse
);
5345 assert( (errCode
&0xff)==SQLITE_CONSTRAINT
|| pParse
->nested
);
5346 if( onError
==OE_Abort
){
5347 sqlite3MayAbort(pParse
);
5349 sqlite3VdbeAddOp4(v
, OP_Halt
, errCode
, onError
, 0, p4
, p4type
);
5350 sqlite3VdbeChangeP5(v
, p5Errmsg
);
5354 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5356 void sqlite3UniqueConstraint(
5357 Parse
*pParse
, /* Parsing context */
5358 int onError
, /* Constraint type */
5359 Index
*pIdx
/* The index that triggers the constraint */
5364 Table
*pTab
= pIdx
->pTable
;
5366 sqlite3StrAccumInit(&errMsg
, pParse
->db
, 0, 0,
5367 pParse
->db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
5368 if( pIdx
->aColExpr
){
5369 sqlite3_str_appendf(&errMsg
, "index '%q'", pIdx
->zName
);
5371 for(j
=0; j
<pIdx
->nKeyCol
; j
++){
5373 assert( pIdx
->aiColumn
[j
]>=0 );
5374 zCol
= pTab
->aCol
[pIdx
->aiColumn
[j
]].zCnName
;
5375 if( j
) sqlite3_str_append(&errMsg
, ", ", 2);
5376 sqlite3_str_appendall(&errMsg
, pTab
->zName
);
5377 sqlite3_str_append(&errMsg
, ".", 1);
5378 sqlite3_str_appendall(&errMsg
, zCol
);
5381 zErr
= sqlite3StrAccumFinish(&errMsg
);
5382 sqlite3HaltConstraint(pParse
,
5383 IsPrimaryKeyIndex(pIdx
) ? SQLITE_CONSTRAINT_PRIMARYKEY
5384 : SQLITE_CONSTRAINT_UNIQUE
,
5385 onError
, zErr
, P4_DYNAMIC
, P5_ConstraintUnique
);
5390 ** Code an OP_Halt due to non-unique rowid.
5392 void sqlite3RowidConstraint(
5393 Parse
*pParse
, /* Parsing context */
5394 int onError
, /* Conflict resolution algorithm */
5395 Table
*pTab
/* The table with the non-unique rowid */
5399 if( pTab
->iPKey
>=0 ){
5400 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.%s", pTab
->zName
,
5401 pTab
->aCol
[pTab
->iPKey
].zCnName
);
5402 rc
= SQLITE_CONSTRAINT_PRIMARYKEY
;
5404 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.rowid", pTab
->zName
);
5405 rc
= SQLITE_CONSTRAINT_ROWID
;
5407 sqlite3HaltConstraint(pParse
, rc
, onError
, zMsg
, P4_DYNAMIC
,
5408 P5_ConstraintUnique
);
5412 ** Check to see if pIndex uses the collating sequence pColl. Return
5413 ** true if it does and false if it does not.
5415 #ifndef SQLITE_OMIT_REINDEX
5416 static int collationMatch(const char *zColl
, Index
*pIndex
){
5419 for(i
=0; i
<pIndex
->nColumn
; i
++){
5420 const char *z
= pIndex
->azColl
[i
];
5421 assert( z
!=0 || pIndex
->aiColumn
[i
]<0 );
5422 if( pIndex
->aiColumn
[i
]>=0 && 0==sqlite3StrICmp(z
, zColl
) ){
5431 ** Recompute all indices of pTab that use the collating sequence pColl.
5432 ** If pColl==0 then recompute all indices of pTab.
5434 #ifndef SQLITE_OMIT_REINDEX
5435 static void reindexTable(Parse
*pParse
, Table
*pTab
, char const *zColl
){
5436 if( !IsVirtual(pTab
) ){
5437 Index
*pIndex
; /* An index associated with pTab */
5439 for(pIndex
=pTab
->pIndex
; pIndex
; pIndex
=pIndex
->pNext
){
5440 if( zColl
==0 || collationMatch(zColl
, pIndex
) ){
5441 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
5442 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
5443 sqlite3RefillIndex(pParse
, pIndex
, -1);
5451 ** Recompute all indices of all tables in all databases where the
5452 ** indices use the collating sequence pColl. If pColl==0 then recompute
5453 ** all indices everywhere.
5455 #ifndef SQLITE_OMIT_REINDEX
5456 static void reindexDatabases(Parse
*pParse
, char const *zColl
){
5457 Db
*pDb
; /* A single database */
5458 int iDb
; /* The database index number */
5459 sqlite3
*db
= pParse
->db
; /* The database connection */
5460 HashElem
*k
; /* For looping over tables in pDb */
5461 Table
*pTab
; /* A table in the database */
5463 assert( sqlite3BtreeHoldsAllMutexes(db
) ); /* Needed for schema access */
5464 for(iDb
=0, pDb
=db
->aDb
; iDb
<db
->nDb
; iDb
++, pDb
++){
5466 for(k
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
5467 pTab
= (Table
*)sqliteHashData(k
);
5468 reindexTable(pParse
, pTab
, zColl
);
5475 ** Generate code for the REINDEX command.
5478 ** REINDEX <collation> -- 2
5479 ** REINDEX ?<database>.?<tablename> -- 3
5480 ** REINDEX ?<database>.?<indexname> -- 4
5482 ** Form 1 causes all indices in all attached databases to be rebuilt.
5483 ** Form 2 rebuilds all indices in all databases that use the named
5484 ** collating function. Forms 3 and 4 rebuild the named index or all
5485 ** indices associated with the named table.
5487 #ifndef SQLITE_OMIT_REINDEX
5488 void sqlite3Reindex(Parse
*pParse
, Token
*pName1
, Token
*pName2
){
5489 CollSeq
*pColl
; /* Collating sequence to be reindexed, or NULL */
5490 char *z
; /* Name of a table or index */
5491 const char *zDb
; /* Name of the database */
5492 Table
*pTab
; /* A table in the database */
5493 Index
*pIndex
; /* An index associated with pTab */
5494 int iDb
; /* The database index number */
5495 sqlite3
*db
= pParse
->db
; /* The database connection */
5496 Token
*pObjName
; /* Name of the table or index to be reindexed */
5498 /* Read the database schema. If an error occurs, leave an error message
5499 ** and code in pParse and return NULL. */
5500 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
5505 reindexDatabases(pParse
, 0);
5507 }else if( NEVER(pName2
==0) || pName2
->z
==0 ){
5509 assert( pName1
->z
);
5510 zColl
= sqlite3NameFromToken(pParse
->db
, pName1
);
5511 if( !zColl
) return;
5512 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
5514 reindexDatabases(pParse
, zColl
);
5515 sqlite3DbFree(db
, zColl
);
5518 sqlite3DbFree(db
, zColl
);
5520 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pObjName
);
5522 z
= sqlite3NameFromToken(db
, pObjName
);
5524 zDb
= pName2
->n
? db
->aDb
[iDb
].zDbSName
: 0;
5525 pTab
= sqlite3FindTable(db
, z
, zDb
);
5527 reindexTable(pParse
, pTab
, 0);
5528 sqlite3DbFree(db
, z
);
5531 pIndex
= sqlite3FindIndex(db
, z
, zDb
);
5532 sqlite3DbFree(db
, z
);
5534 iDb
= sqlite3SchemaToIndex(db
, pIndex
->pTable
->pSchema
);
5535 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
5536 sqlite3RefillIndex(pParse
, pIndex
, -1);
5539 sqlite3ErrorMsg(pParse
, "unable to identify the object to be reindexed");
5544 ** Return a KeyInfo structure that is appropriate for the given Index.
5546 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5547 ** when it has finished using it.
5549 KeyInfo
*sqlite3KeyInfoOfIndex(Parse
*pParse
, Index
*pIdx
){
5551 int nCol
= pIdx
->nColumn
;
5552 int nKey
= pIdx
->nKeyCol
;
5554 if( pParse
->nErr
) return 0;
5555 if( pIdx
->uniqNotNull
){
5556 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nKey
, nCol
-nKey
);
5558 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nCol
, 0);
5561 assert( sqlite3KeyInfoIsWriteable(pKey
) );
5562 for(i
=0; i
<nCol
; i
++){
5563 const char *zColl
= pIdx
->azColl
[i
];
5564 pKey
->aColl
[i
] = zColl
==sqlite3StrBINARY
? 0 :
5565 sqlite3LocateCollSeq(pParse
, zColl
);
5566 pKey
->aSortFlags
[i
] = pIdx
->aSortOrder
[i
];
5567 assert( 0==(pKey
->aSortFlags
[i
] & KEYINFO_ORDER_BIGNULL
) );
5570 assert( pParse
->rc
==SQLITE_ERROR_MISSING_COLLSEQ
);
5571 if( pIdx
->bNoQuery
==0 ){
5572 /* Deactivate the index because it contains an unknown collating
5573 ** sequence. The only way to reactive the index is to reload the
5574 ** schema. Adding the missing collating sequence later does not
5575 ** reactive the index. The application had the chance to register
5576 ** the missing index using the collation-needed callback. For
5577 ** simplicity, SQLite will not give the application a second chance.
5580 pParse
->rc
= SQLITE_ERROR_RETRY
;
5582 sqlite3KeyInfoUnref(pKey
);
5589 #ifndef SQLITE_OMIT_CTE
5591 ** Create a new CTE object
5594 Parse
*pParse
, /* Parsing context */
5595 Token
*pName
, /* Name of the common-table */
5596 ExprList
*pArglist
, /* Optional column name list for the table */
5597 Select
*pQuery
, /* Query used to initialize the table */
5598 u8 eM10d
/* The MATERIALIZED flag */
5601 sqlite3
*db
= pParse
->db
;
5603 pNew
= sqlite3DbMallocZero(db
, sizeof(*pNew
));
5604 assert( pNew
!=0 || db
->mallocFailed
);
5606 if( db
->mallocFailed
){
5607 sqlite3ExprListDelete(db
, pArglist
);
5608 sqlite3SelectDelete(db
, pQuery
);
5610 pNew
->pSelect
= pQuery
;
5611 pNew
->pCols
= pArglist
;
5612 pNew
->zName
= sqlite3NameFromToken(pParse
->db
, pName
);
5613 pNew
->eM10d
= eM10d
;
5619 ** Clear information from a Cte object, but do not deallocate storage
5620 ** for the object itself.
5622 static void cteClear(sqlite3
*db
, Cte
*pCte
){
5624 sqlite3ExprListDelete(db
, pCte
->pCols
);
5625 sqlite3SelectDelete(db
, pCte
->pSelect
);
5626 sqlite3DbFree(db
, pCte
->zName
);
5630 ** Free the contents of the CTE object passed as the second argument.
5632 void sqlite3CteDelete(sqlite3
*db
, Cte
*pCte
){
5635 sqlite3DbFree(db
, pCte
);
5639 ** This routine is invoked once per CTE by the parser while parsing a
5640 ** WITH clause. The CTE described by the third argument is added to
5641 ** the WITH clause of the second argument. If the second argument is
5642 ** NULL, then a new WITH argument is created.
5644 With
*sqlite3WithAdd(
5645 Parse
*pParse
, /* Parsing context */
5646 With
*pWith
, /* Existing WITH clause, or NULL */
5647 Cte
*pCte
/* CTE to add to the WITH clause */
5649 sqlite3
*db
= pParse
->db
;
5657 /* Check that the CTE name is unique within this WITH clause. If
5658 ** not, store an error in the Parse structure. */
5659 zName
= pCte
->zName
;
5660 if( zName
&& pWith
){
5662 for(i
=0; i
<pWith
->nCte
; i
++){
5663 if( sqlite3StrICmp(zName
, pWith
->a
[i
].zName
)==0 ){
5664 sqlite3ErrorMsg(pParse
, "duplicate WITH table name: %s", zName
);
5670 sqlite3_int64 nByte
= sizeof(*pWith
) + (sizeof(pWith
->a
[1]) * pWith
->nCte
);
5671 pNew
= sqlite3DbRealloc(db
, pWith
, nByte
);
5673 pNew
= sqlite3DbMallocZero(db
, sizeof(*pWith
));
5675 assert( (pNew
!=0 && zName
!=0) || db
->mallocFailed
);
5677 if( db
->mallocFailed
){
5678 sqlite3CteDelete(db
, pCte
);
5681 pNew
->a
[pNew
->nCte
++] = *pCte
;
5682 sqlite3DbFree(db
, pCte
);
5689 ** Free the contents of the With object passed as the second argument.
5691 void sqlite3WithDelete(sqlite3
*db
, With
*pWith
){
5694 for(i
=0; i
<pWith
->nCte
; i
++){
5695 cteClear(db
, &pWith
->a
[i
]);
5697 sqlite3DbFree(db
, pWith
);
5700 void sqlite3WithDeleteGeneric(sqlite3
*db
, void *pWith
){
5701 sqlite3WithDelete(db
, (With
*)pWith
);
5703 #endif /* !defined(SQLITE_OMIT_CTE) */