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
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 /* Once all the cookies have been verified and transactions opened,
238 ** obtain the required table-locks. This is a no-op unless the
239 ** shared-cache feature is enabled.
241 codeTableLocks(pParse
);
243 /* Initialize any AUTOINCREMENT data structures required.
245 sqlite3AutoincrementBegin(pParse
);
247 /* Code constant expressions that where factored out of inner loops.
249 ** The pConstExpr list might also contain expressions that we simply
250 ** want to keep around until the Parse object is deleted. Such
251 ** expressions have iConstExprReg==0. Do not generate code for
252 ** those expressions, of course.
254 if( pParse
->pConstExpr
){
255 ExprList
*pEL
= pParse
->pConstExpr
;
256 pParse
->okConstFactor
= 0;
257 for(i
=0; i
<pEL
->nExpr
; i
++){
258 int iReg
= pEL
->a
[i
].u
.iConstExprReg
;
259 sqlite3ExprCode(pParse
, pEL
->a
[i
].pExpr
, iReg
);
263 if( pParse
->bReturning
){
264 Returning
*pRet
= pParse
->u1
.pReturning
;
266 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pRet
->iRetCur
, pRet
->nRetCol
);
270 /* Finally, jump back to the beginning of the executable code. */
271 sqlite3VdbeGoto(v
, 1);
274 /* Get the VDBE program ready for execution
276 assert( v
!=0 || pParse
->nErr
);
277 assert( db
->mallocFailed
==0 || pParse
->nErr
);
278 if( pParse
->nErr
==0 ){
279 /* A minimum of one cursor is required if autoincrement is used
280 * See ticket [a696379c1f08866] */
281 assert( pParse
->pAinc
==0 || pParse
->nTab
>0 );
282 sqlite3VdbeMakeReady(v
, pParse
);
283 pParse
->rc
= SQLITE_DONE
;
285 pParse
->rc
= SQLITE_ERROR
;
290 ** Run the parser and code generator recursively in order to generate
291 ** code for the SQL statement given onto the end of the pParse context
292 ** currently under construction. Notes:
294 ** * The final OP_Halt is not appended and other initialization
295 ** and finalization steps are omitted because those are handling by the
298 ** * Built-in SQL functions always take precedence over application-defined
299 ** SQL functions. In other words, it is not possible to override a
300 ** built-in function.
302 void sqlite3NestedParse(Parse
*pParse
, const char *zFormat
, ...){
305 sqlite3
*db
= pParse
->db
;
306 u32 savedDbFlags
= db
->mDbFlags
;
307 char saveBuf
[PARSE_TAIL_SZ
];
309 if( pParse
->nErr
) return;
310 if( pParse
->eParseMode
) return;
311 assert( pParse
->nested
<10 ); /* Nesting should only be of limited depth */
312 va_start(ap
, zFormat
);
313 zSql
= sqlite3VMPrintf(db
, zFormat
, ap
);
316 /* This can result either from an OOM or because the formatted string
317 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
319 if( !db
->mallocFailed
) pParse
->rc
= SQLITE_TOOBIG
;
324 memcpy(saveBuf
, PARSE_TAIL(pParse
), PARSE_TAIL_SZ
);
325 memset(PARSE_TAIL(pParse
), 0, PARSE_TAIL_SZ
);
326 db
->mDbFlags
|= DBFLAG_PreferBuiltin
;
327 sqlite3RunParser(pParse
, zSql
);
328 db
->mDbFlags
= savedDbFlags
;
329 sqlite3DbFree(db
, zSql
);
330 memcpy(PARSE_TAIL(pParse
), saveBuf
, PARSE_TAIL_SZ
);
334 #if SQLITE_USER_AUTHENTICATION
336 ** Return TRUE if zTable is the name of the system table that stores the
337 ** list of users and their access credentials.
339 int sqlite3UserAuthTable(const char *zTable
){
340 return sqlite3_stricmp(zTable
, "sqlite_user")==0;
345 ** Locate the in-memory structure that describes a particular database
346 ** table given the name of that table and (optionally) the name of the
347 ** database containing the table. Return NULL if not found.
349 ** If zDatabase is 0, all databases are searched for the table and the
350 ** first matching table is returned. (No checking for duplicate table
351 ** names is done.) The search order is TEMP first, then MAIN, then any
352 ** auxiliary databases added using the ATTACH command.
354 ** See also sqlite3LocateTable().
356 Table
*sqlite3FindTable(sqlite3
*db
, const char *zName
, const char *zDatabase
){
360 /* All mutexes are required for schema access. Make sure we hold them. */
361 assert( zDatabase
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
362 #if SQLITE_USER_AUTHENTICATION
363 /* Only the admin user is allowed to know that the sqlite_user table
365 if( db
->auth
.authLevel
<UAUTH_Admin
&& sqlite3UserAuthTable(zName
)!=0 ){
370 for(i
=0; i
<db
->nDb
; i
++){
371 if( sqlite3StrICmp(zDatabase
, db
->aDb
[i
].zDbSName
)==0 ) break;
374 /* No match against the official names. But always match "main"
375 ** to schema 0 as a legacy fallback. */
376 if( sqlite3StrICmp(zDatabase
,"main")==0 ){
382 p
= sqlite3HashFind(&db
->aDb
[i
].pSchema
->tblHash
, zName
);
383 if( p
==0 && sqlite3StrNICmp(zName
, "sqlite_", 7)==0 ){
385 if( sqlite3StrICmp(zName
+7, &PREFERRED_TEMP_SCHEMA_TABLE
[7])==0
386 || sqlite3StrICmp(zName
+7, &PREFERRED_SCHEMA_TABLE
[7])==0
387 || sqlite3StrICmp(zName
+7, &LEGACY_SCHEMA_TABLE
[7])==0
389 p
= sqlite3HashFind(&db
->aDb
[1].pSchema
->tblHash
,
390 LEGACY_TEMP_SCHEMA_TABLE
);
393 if( sqlite3StrICmp(zName
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ){
394 p
= sqlite3HashFind(&db
->aDb
[i
].pSchema
->tblHash
,
395 LEGACY_SCHEMA_TABLE
);
400 /* Match against TEMP first */
401 p
= sqlite3HashFind(&db
->aDb
[1].pSchema
->tblHash
, zName
);
403 /* The main database is second */
404 p
= sqlite3HashFind(&db
->aDb
[0].pSchema
->tblHash
, zName
);
406 /* Attached databases are in order of attachment */
407 for(i
=2; i
<db
->nDb
; i
++){
408 assert( sqlite3SchemaMutexHeld(db
, i
, 0) );
409 p
= sqlite3HashFind(&db
->aDb
[i
].pSchema
->tblHash
, zName
);
412 if( p
==0 && sqlite3StrNICmp(zName
, "sqlite_", 7)==0 ){
413 if( sqlite3StrICmp(zName
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ){
414 p
= sqlite3HashFind(&db
->aDb
[0].pSchema
->tblHash
, LEGACY_SCHEMA_TABLE
);
415 }else if( sqlite3StrICmp(zName
+7, &PREFERRED_TEMP_SCHEMA_TABLE
[7])==0 ){
416 p
= sqlite3HashFind(&db
->aDb
[1].pSchema
->tblHash
,
417 LEGACY_TEMP_SCHEMA_TABLE
);
425 ** Locate the in-memory structure that describes a particular database
426 ** table given the name of that table and (optionally) the name of the
427 ** database containing the table. Return NULL if not found. Also leave an
428 ** error message in pParse->zErrMsg.
430 ** The difference between this routine and sqlite3FindTable() is that this
431 ** routine leaves an error message in pParse->zErrMsg where
432 ** sqlite3FindTable() does not.
434 Table
*sqlite3LocateTable(
435 Parse
*pParse
, /* context in which to report errors */
436 u32 flags
, /* LOCATE_VIEW or LOCATE_NOERR */
437 const char *zName
, /* Name of the table we are looking for */
438 const char *zDbase
/* Name of the database. Might be NULL */
441 sqlite3
*db
= pParse
->db
;
443 /* Read the database schema. If an error occurs, leave an error message
444 ** and code in pParse and return NULL. */
445 if( (db
->mDbFlags
& DBFLAG_SchemaKnownOk
)==0
446 && SQLITE_OK
!=sqlite3ReadSchema(pParse
)
451 p
= sqlite3FindTable(db
, zName
, zDbase
);
453 #ifndef SQLITE_OMIT_VIRTUALTABLE
454 /* If zName is the not the name of a table in the schema created using
455 ** CREATE, then check to see if it is the name of an virtual table that
456 ** can be an eponymous virtual table. */
457 if( (pParse
->prepFlags
& SQLITE_PREPARE_NO_VTAB
)==0 && db
->init
.busy
==0 ){
458 Module
*pMod
= (Module
*)sqlite3HashFind(&db
->aModule
, zName
);
459 if( pMod
==0 && sqlite3_strnicmp(zName
, "pragma_", 7)==0 ){
460 pMod
= sqlite3PragmaVtabRegister(db
, zName
);
462 if( pMod
&& sqlite3VtabEponymousTableInit(pParse
, pMod
) ){
463 testcase( pMod
->pEpoTab
==0 );
464 return pMod
->pEpoTab
;
468 if( flags
& LOCATE_NOERR
) return 0;
469 pParse
->checkSchema
= 1;
470 }else if( IsVirtual(p
) && (pParse
->prepFlags
& SQLITE_PREPARE_NO_VTAB
)!=0 ){
475 const char *zMsg
= flags
& LOCATE_VIEW
? "no such view" : "no such table";
477 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zMsg
, zDbase
, zName
);
479 sqlite3ErrorMsg(pParse
, "%s: %s", zMsg
, zName
);
482 assert( HasRowid(p
) || p
->iPKey
<0 );
489 ** Locate the table identified by *p.
491 ** This is a wrapper around sqlite3LocateTable(). The difference between
492 ** sqlite3LocateTable() and this function is that this function restricts
493 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
494 ** non-NULL if it is part of a view or trigger program definition. See
495 ** sqlite3FixSrcList() for details.
497 Table
*sqlite3LocateTableItem(
503 assert( p
->pSchema
==0 || p
->zDatabase
==0 );
505 int iDb
= sqlite3SchemaToIndex(pParse
->db
, p
->pSchema
);
506 zDb
= pParse
->db
->aDb
[iDb
].zDbSName
;
510 return sqlite3LocateTable(pParse
, flags
, p
->zName
, zDb
);
514 ** Return the preferred table name for system tables. Translate legacy
515 ** names into the new preferred names, as appropriate.
517 const char *sqlite3PreferredTableName(const char *zName
){
518 if( sqlite3StrNICmp(zName
, "sqlite_", 7)==0 ){
519 if( sqlite3StrICmp(zName
+7, &LEGACY_SCHEMA_TABLE
[7])==0 ){
520 return PREFERRED_SCHEMA_TABLE
;
522 if( sqlite3StrICmp(zName
+7, &LEGACY_TEMP_SCHEMA_TABLE
[7])==0 ){
523 return PREFERRED_TEMP_SCHEMA_TABLE
;
530 ** Locate the in-memory structure that describes
531 ** a particular index given the name of that index
532 ** and the name of the database that contains the index.
533 ** Return NULL if not found.
535 ** If zDatabase is 0, all databases are searched for the
536 ** table and the first matching index is returned. (No checking
537 ** for duplicate index names is done.) The search order is
538 ** TEMP first, then MAIN, then any auxiliary databases added
539 ** using the ATTACH command.
541 Index
*sqlite3FindIndex(sqlite3
*db
, const char *zName
, const char *zDb
){
544 /* All mutexes are required for schema access. Make sure we hold them. */
545 assert( zDb
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
546 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
547 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
548 Schema
*pSchema
= db
->aDb
[j
].pSchema
;
550 if( zDb
&& sqlite3DbIsNamed(db
, j
, zDb
)==0 ) continue;
551 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
552 p
= sqlite3HashFind(&pSchema
->idxHash
, zName
);
559 ** Reclaim the memory used by an index
561 void sqlite3FreeIndex(sqlite3
*db
, Index
*p
){
562 #ifndef SQLITE_OMIT_ANALYZE
563 sqlite3DeleteIndexSamples(db
, p
);
565 sqlite3ExprDelete(db
, p
->pPartIdxWhere
);
566 sqlite3ExprListDelete(db
, p
->aColExpr
);
567 sqlite3DbFree(db
, p
->zColAff
);
568 if( p
->isResized
) sqlite3DbFree(db
, (void *)p
->azColl
);
569 #ifdef SQLITE_ENABLE_STAT4
570 sqlite3_free(p
->aiRowEst
);
572 sqlite3DbFree(db
, p
);
576 ** For the index called zIdxName which is found in the database iDb,
577 ** unlike that index from its Table then remove the index from
578 ** the index hash table and free all memory structures associated
581 void sqlite3UnlinkAndDeleteIndex(sqlite3
*db
, int iDb
, const char *zIdxName
){
585 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
586 pHash
= &db
->aDb
[iDb
].pSchema
->idxHash
;
587 pIndex
= sqlite3HashInsert(pHash
, zIdxName
, 0);
588 if( ALWAYS(pIndex
) ){
589 if( pIndex
->pTable
->pIndex
==pIndex
){
590 pIndex
->pTable
->pIndex
= pIndex
->pNext
;
593 /* Justification of ALWAYS(); The index must be on the list of
595 p
= pIndex
->pTable
->pIndex
;
596 while( ALWAYS(p
) && p
->pNext
!=pIndex
){ p
= p
->pNext
; }
597 if( ALWAYS(p
&& p
->pNext
==pIndex
) ){
598 p
->pNext
= pIndex
->pNext
;
601 sqlite3FreeIndex(db
, pIndex
);
603 db
->mDbFlags
|= DBFLAG_SchemaChange
;
607 ** Look through the list of open database files in db->aDb[] and if
608 ** any have been closed, remove them from the list. Reallocate the
609 ** db->aDb[] structure to a smaller size, if possible.
611 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
612 ** are never candidates for being collapsed.
614 void sqlite3CollapseDatabaseArray(sqlite3
*db
){
616 for(i
=j
=2; i
<db
->nDb
; i
++){
617 struct Db
*pDb
= &db
->aDb
[i
];
619 sqlite3DbFree(db
, pDb
->zDbSName
);
624 db
->aDb
[j
] = db
->aDb
[i
];
629 if( db
->nDb
<=2 && db
->aDb
!=db
->aDbStatic
){
630 memcpy(db
->aDbStatic
, db
->aDb
, 2*sizeof(db
->aDb
[0]));
631 sqlite3DbFree(db
, db
->aDb
);
632 db
->aDb
= db
->aDbStatic
;
637 ** Reset the schema for the database at index iDb. Also reset the
638 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
639 ** Deferred resets may be run by calling with iDb<0.
641 void sqlite3ResetOneSchema(sqlite3
*db
, int iDb
){
643 assert( iDb
<db
->nDb
);
646 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
647 DbSetProperty(db
, iDb
, DB_ResetWanted
);
648 DbSetProperty(db
, 1, DB_ResetWanted
);
649 db
->mDbFlags
&= ~DBFLAG_SchemaKnownOk
;
652 if( db
->nSchemaLock
==0 ){
653 for(i
=0; i
<db
->nDb
; i
++){
654 if( DbHasProperty(db
, i
, DB_ResetWanted
) ){
655 sqlite3SchemaClear(db
->aDb
[i
].pSchema
);
662 ** Erase all schema information from all attached databases (including
663 ** "main" and "temp") for a single database connection.
665 void sqlite3ResetAllSchemasOfConnection(sqlite3
*db
){
667 sqlite3BtreeEnterAll(db
);
668 for(i
=0; i
<db
->nDb
; i
++){
669 Db
*pDb
= &db
->aDb
[i
];
671 if( db
->nSchemaLock
==0 ){
672 sqlite3SchemaClear(pDb
->pSchema
);
674 DbSetProperty(db
, i
, DB_ResetWanted
);
678 db
->mDbFlags
&= ~(DBFLAG_SchemaChange
|DBFLAG_SchemaKnownOk
);
679 sqlite3VtabUnlockList(db
);
680 sqlite3BtreeLeaveAll(db
);
681 if( db
->nSchemaLock
==0 ){
682 sqlite3CollapseDatabaseArray(db
);
687 ** This routine is called when a commit occurs.
689 void sqlite3CommitInternalChanges(sqlite3
*db
){
690 db
->mDbFlags
&= ~DBFLAG_SchemaChange
;
694 ** Set the expression associated with a column. This is usually
695 ** the DEFAULT value, but might also be the expression that computes
696 ** the value for a generated column.
698 void sqlite3ColumnSetExpr(
699 Parse
*pParse
, /* Parsing context */
700 Table
*pTab
, /* The table containing the column */
701 Column
*pCol
, /* The column to receive the new DEFAULT expression */
702 Expr
*pExpr
/* The new default expression */
705 assert( IsOrdinaryTable(pTab
) );
706 pList
= pTab
->u
.tab
.pDfltList
;
709 || NEVER(pList
->nExpr
<pCol
->iDflt
)
711 pCol
->iDflt
= pList
==0 ? 1 : pList
->nExpr
+1;
712 pTab
->u
.tab
.pDfltList
= sqlite3ExprListAppend(pParse
, pList
, pExpr
);
714 sqlite3ExprDelete(pParse
->db
, pList
->a
[pCol
->iDflt
-1].pExpr
);
715 pList
->a
[pCol
->iDflt
-1].pExpr
= pExpr
;
720 ** Return the expression associated with a column. The expression might be
721 ** the DEFAULT clause or the AS clause of a generated column.
722 ** Return NULL if the column has no associated expression.
724 Expr
*sqlite3ColumnExpr(Table
*pTab
, Column
*pCol
){
725 if( pCol
->iDflt
==0 ) return 0;
726 if( NEVER(!IsOrdinaryTable(pTab
)) ) return 0;
727 if( NEVER(pTab
->u
.tab
.pDfltList
==0) ) return 0;
728 if( NEVER(pTab
->u
.tab
.pDfltList
->nExpr
<pCol
->iDflt
) ) return 0;
729 return pTab
->u
.tab
.pDfltList
->a
[pCol
->iDflt
-1].pExpr
;
733 ** Set the collating sequence name for a column.
735 void sqlite3ColumnSetColl(
744 n
= sqlite3Strlen30(pCol
->zCnName
) + 1;
745 if( pCol
->colFlags
& COLFLAG_HASTYPE
){
746 n
+= sqlite3Strlen30(pCol
->zCnName
+n
) + 1;
748 nColl
= sqlite3Strlen30(zColl
) + 1;
749 zNew
= sqlite3DbRealloc(db
, pCol
->zCnName
, nColl
+n
);
751 pCol
->zCnName
= zNew
;
752 memcpy(pCol
->zCnName
+ n
, zColl
, nColl
);
753 pCol
->colFlags
|= COLFLAG_HASCOLL
;
758 ** Return the collating squence name for a column
760 const char *sqlite3ColumnColl(Column
*pCol
){
762 if( (pCol
->colFlags
& COLFLAG_HASCOLL
)==0 ) return 0;
765 if( pCol
->colFlags
& COLFLAG_HASTYPE
){
766 do{ z
++; }while( *z
);
772 ** Delete memory allocated for the column names of a table or view (the
773 ** Table.aCol[] array).
775 void sqlite3DeleteColumnNames(sqlite3
*db
, Table
*pTable
){
780 if( (pCol
= pTable
->aCol
)!=0 ){
781 for(i
=0; i
<pTable
->nCol
; i
++, pCol
++){
782 assert( pCol
->zCnName
==0 || pCol
->hName
==sqlite3StrIHash(pCol
->zCnName
) );
783 sqlite3DbFree(db
, pCol
->zCnName
);
785 sqlite3DbNNFreeNN(db
, pTable
->aCol
);
786 if( IsOrdinaryTable(pTable
) ){
787 sqlite3ExprListDelete(db
, pTable
->u
.tab
.pDfltList
);
789 if( db
->pnBytesFreed
==0 ){
792 if( IsOrdinaryTable(pTable
) ){
793 pTable
->u
.tab
.pDfltList
= 0;
800 ** Remove the memory data structures associated with the given
801 ** Table. No changes are made to disk by this routine.
803 ** This routine just deletes the data structure. It does not unlink
804 ** the table data structure from the hash table. But it does destroy
805 ** memory structures of the indices and foreign keys associated with
808 ** The db parameter is optional. It is needed if the Table object
809 ** contains lookaside memory. (Table objects in the schema do not use
810 ** lookaside memory, but some ephemeral Table objects do.) Or the
811 ** db parameter can be used with db->pnBytesFreed to measure the memory
812 ** used by the Table object.
814 static void SQLITE_NOINLINE
deleteTable(sqlite3
*db
, Table
*pTable
){
815 Index
*pIndex
, *pNext
;
818 /* Record the number of outstanding lookaside allocations in schema Tables
819 ** prior to doing any free() operations. Since schema Tables do not use
820 ** lookaside, this number should not change.
822 ** If malloc has already failed, it may be that it failed while allocating
823 ** a Table object that was going to be marked ephemeral. So do not check
824 ** that no lookaside memory is used in this case either. */
827 if( !db
->mallocFailed
&& (pTable
->tabFlags
& TF_Ephemeral
)==0 ){
828 nLookaside
= sqlite3LookasideUsed(db
, 0);
832 /* Delete all indices associated with this table. */
833 for(pIndex
= pTable
->pIndex
; pIndex
; pIndex
=pNext
){
834 pNext
= pIndex
->pNext
;
835 assert( pIndex
->pSchema
==pTable
->pSchema
836 || (IsVirtual(pTable
) && pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
) );
837 if( db
->pnBytesFreed
==0 && !IsVirtual(pTable
) ){
838 char *zName
= pIndex
->zName
;
839 TESTONLY ( Index
*pOld
= ) sqlite3HashInsert(
840 &pIndex
->pSchema
->idxHash
, zName
, 0
842 assert( db
==0 || sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
843 assert( pOld
==pIndex
|| pOld
==0 );
845 sqlite3FreeIndex(db
, pIndex
);
848 if( IsOrdinaryTable(pTable
) ){
849 sqlite3FkDelete(db
, pTable
);
851 #ifndef SQLITE_OMIT_VIRTUAL_TABLE
852 else if( IsVirtual(pTable
) ){
853 sqlite3VtabClear(db
, pTable
);
857 assert( IsView(pTable
) );
858 sqlite3SelectDelete(db
, pTable
->u
.view
.pSelect
);
861 /* Delete the Table structure itself.
863 sqlite3DeleteColumnNames(db
, pTable
);
864 sqlite3DbFree(db
, pTable
->zName
);
865 sqlite3DbFree(db
, pTable
->zColAff
);
866 sqlite3ExprListDelete(db
, pTable
->pCheck
);
867 sqlite3DbFree(db
, pTable
);
869 /* Verify that no lookaside memory was used by schema tables */
870 assert( nLookaside
==0 || nLookaside
==sqlite3LookasideUsed(db
,0) );
872 void sqlite3DeleteTable(sqlite3
*db
, Table
*pTable
){
873 /* Do not delete the table until the reference count reaches zero. */
875 if( !pTable
) return;
876 if( db
->pnBytesFreed
==0 && (--pTable
->nTabRef
)>0 ) return;
877 deleteTable(db
, pTable
);
882 ** Unlink the given table from the hash tables and the delete the
883 ** table structure with all its indices and foreign keys.
885 void sqlite3UnlinkAndDeleteTable(sqlite3
*db
, int iDb
, const char *zTabName
){
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 ** Name of the special TEMP trigger used to implement RETURNING. The
1415 ** name begins with "sqlite_" so that it is guaranteed not to collide
1416 ** with any application-generated triggers.
1418 #define RETURNING_TRIGGER_NAME "sqlite_returning"
1421 ** Clean up the data structures associated with the RETURNING clause.
1423 static void sqlite3DeleteReturning(sqlite3
*db
, Returning
*pRet
){
1425 pHash
= &(db
->aDb
[1].pSchema
->trigHash
);
1426 sqlite3HashInsert(pHash
, RETURNING_TRIGGER_NAME
, 0);
1427 sqlite3ExprListDelete(db
, pRet
->pReturnEL
);
1428 sqlite3DbFree(db
, pRet
);
1432 ** Add the RETURNING clause to the parse currently underway.
1434 ** This routine creates a special TEMP trigger that will fire for each row
1435 ** of the DML statement. That TEMP trigger contains a single SELECT
1436 ** statement with a result set that is the argument of the RETURNING clause.
1437 ** The trigger has the Trigger.bReturning flag and an opcode of
1438 ** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
1439 ** knows to handle it specially. The TEMP trigger is automatically
1440 ** removed at the end of the parse.
1442 ** When this routine is called, we do not yet know if the RETURNING clause
1443 ** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
1444 ** RETURNING trigger instead. It will then be converted into the appropriate
1445 ** type on the first call to sqlite3TriggersExist().
1447 void sqlite3AddReturning(Parse
*pParse
, ExprList
*pList
){
1450 sqlite3
*db
= pParse
->db
;
1451 if( pParse
->pNewTrigger
){
1452 sqlite3ErrorMsg(pParse
, "cannot use RETURNING in a trigger");
1454 assert( pParse
->bReturning
==0 );
1456 pParse
->bReturning
= 1;
1457 pRet
= sqlite3DbMallocZero(db
, sizeof(*pRet
));
1459 sqlite3ExprListDelete(db
, pList
);
1462 pParse
->u1
.pReturning
= pRet
;
1463 pRet
->pParse
= pParse
;
1464 pRet
->pReturnEL
= pList
;
1465 sqlite3ParserAddCleanup(pParse
,
1466 (void(*)(sqlite3
*,void*))sqlite3DeleteReturning
, pRet
);
1467 testcase( pParse
->earlyCleanup
);
1468 if( db
->mallocFailed
) return;
1469 pRet
->retTrig
.zName
= RETURNING_TRIGGER_NAME
;
1470 pRet
->retTrig
.op
= TK_RETURNING
;
1471 pRet
->retTrig
.tr_tm
= TRIGGER_AFTER
;
1472 pRet
->retTrig
.bReturning
= 1;
1473 pRet
->retTrig
.pSchema
= db
->aDb
[1].pSchema
;
1474 pRet
->retTrig
.pTabSchema
= db
->aDb
[1].pSchema
;
1475 pRet
->retTrig
.step_list
= &pRet
->retTStep
;
1476 pRet
->retTStep
.op
= TK_RETURNING
;
1477 pRet
->retTStep
.pTrig
= &pRet
->retTrig
;
1478 pRet
->retTStep
.pExprList
= pList
;
1479 pHash
= &(db
->aDb
[1].pSchema
->trigHash
);
1480 assert( sqlite3HashFind(pHash
, RETURNING_TRIGGER_NAME
)==0 || pParse
->nErr
);
1481 if( sqlite3HashInsert(pHash
, RETURNING_TRIGGER_NAME
, &pRet
->retTrig
)
1483 sqlite3OomFault(db
);
1488 ** Add a new column to the table currently being constructed.
1490 ** The parser calls this routine once for each column declaration
1491 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1492 ** first to get things going. Then this routine is called for each
1495 void sqlite3AddColumn(Parse
*pParse
, Token sName
, Token sType
){
1501 sqlite3
*db
= pParse
->db
;
1504 u8 eType
= COLTYPE_CUSTOM
;
1506 char affinity
= SQLITE_AFF_BLOB
;
1508 if( (p
= pParse
->pNewTable
)==0 ) return;
1509 if( p
->nCol
+1>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1510 sqlite3ErrorMsg(pParse
, "too many columns on %s", p
->zName
);
1513 if( !IN_RENAME_OBJECT
) sqlite3DequoteToken(&sName
);
1515 /* Because keywords GENERATE ALWAYS can be converted into indentifiers
1516 ** by the parser, we can sometimes end up with a typename that ends
1517 ** with "generated always". Check for this case and omit the surplus
1520 && sqlite3_strnicmp(sType
.z
+(sType
.n
-6),"always",6)==0
1523 while( ALWAYS(sType
.n
>0) && sqlite3Isspace(sType
.z
[sType
.n
-1]) ) sType
.n
--;
1525 && sqlite3_strnicmp(sType
.z
+(sType
.n
-9),"generated",9)==0
1528 while( sType
.n
>0 && sqlite3Isspace(sType
.z
[sType
.n
-1]) ) sType
.n
--;
1532 /* Check for standard typenames. For standard typenames we will
1533 ** set the Column.eType field rather than storing the typename after
1534 ** the column name, in order to save space. */
1536 sqlite3DequoteToken(&sType
);
1537 for(i
=0; i
<SQLITE_N_STDTYPE
; i
++){
1538 if( sType
.n
==sqlite3StdTypeLen
[i
]
1539 && sqlite3_strnicmp(sType
.z
, sqlite3StdType
[i
], sType
.n
)==0
1543 affinity
= sqlite3StdTypeAffinity
[i
];
1544 if( affinity
<=SQLITE_AFF_TEXT
) szEst
= 5;
1550 z
= sqlite3DbMallocRaw(db
, (i64
)sName
.n
+ 1 + (i64
)sType
.n
+ (sType
.n
>0) );
1552 if( IN_RENAME_OBJECT
) sqlite3RenameTokenMap(pParse
, (void*)z
, &sName
);
1553 memcpy(z
, sName
.z
, sName
.n
);
1556 hName
= sqlite3StrIHash(z
);
1557 for(i
=0; i
<p
->nCol
; i
++){
1558 if( p
->aCol
[i
].hName
==hName
&& sqlite3StrICmp(z
, p
->aCol
[i
].zCnName
)==0 ){
1559 sqlite3ErrorMsg(pParse
, "duplicate column name: %s", z
);
1560 sqlite3DbFree(db
, z
);
1564 aNew
= sqlite3DbRealloc(db
,p
->aCol
,((i64
)p
->nCol
+1)*sizeof(p
->aCol
[0]));
1566 sqlite3DbFree(db
, z
);
1570 pCol
= &p
->aCol
[p
->nCol
];
1571 memset(pCol
, 0, sizeof(p
->aCol
[0]));
1573 pCol
->hName
= hName
;
1574 sqlite3ColumnPropertiesFromName(p
, pCol
);
1577 /* If there is no type specified, columns have the default affinity
1578 ** 'BLOB' with a default size of 4 bytes. */
1579 pCol
->affinity
= affinity
;
1580 pCol
->eCType
= eType
;
1581 pCol
->szEst
= szEst
;
1582 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1583 if( affinity
==SQLITE_AFF_BLOB
){
1584 if( 4>=sqlite3GlobalConfig
.szSorterRef
){
1585 pCol
->colFlags
|= COLFLAG_SORTERREF
;
1590 zType
= z
+ sqlite3Strlen30(z
) + 1;
1591 memcpy(zType
, sType
.z
, sType
.n
);
1593 sqlite3Dequote(zType
);
1594 pCol
->affinity
= sqlite3AffinityType(zType
, pCol
);
1595 pCol
->colFlags
|= COLFLAG_HASTYPE
;
1599 pParse
->constraintName
.n
= 0;
1603 ** This routine is called by the parser while in the middle of
1604 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1605 ** been seen on a column. This routine sets the notNull flag on
1606 ** the column currently under construction.
1608 void sqlite3AddNotNull(Parse
*pParse
, int onError
){
1611 p
= pParse
->pNewTable
;
1612 if( p
==0 || NEVER(p
->nCol
<1) ) return;
1613 pCol
= &p
->aCol
[p
->nCol
-1];
1614 pCol
->notNull
= (u8
)onError
;
1615 p
->tabFlags
|= TF_HasNotNull
;
1617 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1618 ** on this column. */
1619 if( pCol
->colFlags
& COLFLAG_UNIQUE
){
1621 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1622 assert( pIdx
->nKeyCol
==1 && pIdx
->onError
!=OE_None
);
1623 if( pIdx
->aiColumn
[0]==p
->nCol
-1 ){
1624 pIdx
->uniqNotNull
= 1;
1631 ** Scan the column type name zType (length nType) and return the
1632 ** associated affinity type.
1634 ** This routine does a case-independent search of zType for the
1635 ** substrings in the following table. If one of the substrings is
1636 ** found, the corresponding affinity is returned. If zType contains
1637 ** more than one of the substrings, entries toward the top of
1638 ** the table take priority. For example, if zType is 'BLOBINT',
1639 ** SQLITE_AFF_INTEGER is returned.
1641 ** Substring | Affinity
1642 ** --------------------------------
1643 ** 'INT' | SQLITE_AFF_INTEGER
1644 ** 'CHAR' | SQLITE_AFF_TEXT
1645 ** 'CLOB' | SQLITE_AFF_TEXT
1646 ** 'TEXT' | SQLITE_AFF_TEXT
1647 ** 'BLOB' | SQLITE_AFF_BLOB
1648 ** 'REAL' | SQLITE_AFF_REAL
1649 ** 'FLOA' | SQLITE_AFF_REAL
1650 ** 'DOUB' | SQLITE_AFF_REAL
1652 ** If none of the substrings in the above table are found,
1653 ** SQLITE_AFF_NUMERIC is returned.
1655 char sqlite3AffinityType(const char *zIn
, Column
*pCol
){
1657 char aff
= SQLITE_AFF_NUMERIC
;
1658 const char *zChar
= 0;
1662 h
= (h
<<8) + sqlite3UpperToLower
[(*zIn
)&0xff];
1664 if( h
==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1665 aff
= SQLITE_AFF_TEXT
;
1667 }else if( h
==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1668 aff
= SQLITE_AFF_TEXT
;
1669 }else if( h
==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1670 aff
= SQLITE_AFF_TEXT
;
1671 }else if( h
==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1672 && (aff
==SQLITE_AFF_NUMERIC
|| aff
==SQLITE_AFF_REAL
) ){
1673 aff
= SQLITE_AFF_BLOB
;
1674 if( zIn
[0]=='(' ) zChar
= zIn
;
1675 #ifndef SQLITE_OMIT_FLOATING_POINT
1676 }else if( h
==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1677 && aff
==SQLITE_AFF_NUMERIC
){
1678 aff
= SQLITE_AFF_REAL
;
1679 }else if( h
==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1680 && aff
==SQLITE_AFF_NUMERIC
){
1681 aff
= SQLITE_AFF_REAL
;
1682 }else if( h
==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1683 && aff
==SQLITE_AFF_NUMERIC
){
1684 aff
= SQLITE_AFF_REAL
;
1686 }else if( (h
&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1687 aff
= SQLITE_AFF_INTEGER
;
1692 /* If pCol is not NULL, store an estimate of the field size. The
1693 ** estimate is scaled so that the size of an integer is 1. */
1695 int v
= 0; /* default size is approx 4 bytes */
1696 if( aff
<SQLITE_AFF_NUMERIC
){
1699 if( sqlite3Isdigit(zChar
[0]) ){
1700 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1701 sqlite3GetInt32(zChar
, &v
);
1707 v
= 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1710 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1711 if( v
>=sqlite3GlobalConfig
.szSorterRef
){
1712 pCol
->colFlags
|= COLFLAG_SORTERREF
;
1716 if( v
>255 ) v
= 255;
1723 ** The expression is the default value for the most recently added column
1724 ** of the table currently under construction.
1726 ** Default value expressions must be constant. Raise an exception if this
1729 ** This routine is called by the parser while in the middle of
1730 ** parsing a CREATE TABLE statement.
1732 void sqlite3AddDefaultValue(
1733 Parse
*pParse
, /* Parsing context */
1734 Expr
*pExpr
, /* The parsed expression of the default value */
1735 const char *zStart
, /* Start of the default value text */
1736 const char *zEnd
/* First character past end of defaut value text */
1740 sqlite3
*db
= pParse
->db
;
1741 p
= pParse
->pNewTable
;
1743 int isInit
= db
->init
.busy
&& db
->init
.iDb
!=1;
1744 pCol
= &(p
->aCol
[p
->nCol
-1]);
1745 if( !sqlite3ExprIsConstantOrFunction(pExpr
, isInit
) ){
1746 sqlite3ErrorMsg(pParse
, "default value of column [%s] is not constant",
1748 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1749 }else if( pCol
->colFlags
& COLFLAG_GENERATED
){
1750 testcase( pCol
->colFlags
& COLFLAG_VIRTUAL
);
1751 testcase( pCol
->colFlags
& COLFLAG_STORED
);
1752 sqlite3ErrorMsg(pParse
, "cannot use DEFAULT on a generated column");
1755 /* A copy of pExpr is used instead of the original, as pExpr contains
1756 ** tokens that point to volatile memory.
1759 memset(&x
, 0, sizeof(x
));
1761 x
.u
.zToken
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
1764 pDfltExpr
= sqlite3ExprDup(db
, &x
, EXPRDUP_REDUCE
);
1765 sqlite3DbFree(db
, x
.u
.zToken
);
1766 sqlite3ColumnSetExpr(pParse
, p
, pCol
, pDfltExpr
);
1769 if( IN_RENAME_OBJECT
){
1770 sqlite3RenameExprUnmap(pParse
, pExpr
);
1772 sqlite3ExprDelete(db
, pExpr
);
1776 ** Backwards Compatibility Hack:
1778 ** Historical versions of SQLite accepted strings as column names in
1779 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1781 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1782 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1784 ** This is goofy. But to preserve backwards compatibility we continue to
1785 ** accept it. This routine does the necessary conversion. It converts
1786 ** the expression given in its argument from a TK_STRING into a TK_ID
1787 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1788 ** If the expression is anything other than TK_STRING, the expression is
1791 static void sqlite3StringToId(Expr
*p
){
1792 if( p
->op
==TK_STRING
){
1794 }else if( p
->op
==TK_COLLATE
&& p
->pLeft
->op
==TK_STRING
){
1795 p
->pLeft
->op
= TK_ID
;
1800 ** Tag the given column as being part of the PRIMARY KEY
1802 static void makeColumnPartOfPrimaryKey(Parse
*pParse
, Column
*pCol
){
1803 pCol
->colFlags
|= COLFLAG_PRIMKEY
;
1804 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1805 if( pCol
->colFlags
& COLFLAG_GENERATED
){
1806 testcase( pCol
->colFlags
& COLFLAG_VIRTUAL
);
1807 testcase( pCol
->colFlags
& COLFLAG_STORED
);
1808 sqlite3ErrorMsg(pParse
,
1809 "generated columns cannot be part of the PRIMARY KEY");
1815 ** Designate the PRIMARY KEY for the table. pList is a list of names
1816 ** of columns that form the primary key. If pList is NULL, then the
1817 ** most recently added column of the table is the primary key.
1819 ** A table can have at most one primary key. If the table already has
1820 ** a primary key (and this is the second primary key) then create an
1823 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1824 ** then we will try to use that column as the rowid. Set the Table.iPKey
1825 ** field of the table under construction to be the index of the
1826 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1827 ** no INTEGER PRIMARY KEY.
1829 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1830 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1832 void sqlite3AddPrimaryKey(
1833 Parse
*pParse
, /* Parsing context */
1834 ExprList
*pList
, /* List of field names to be indexed */
1835 int onError
, /* What to do with a uniqueness conflict */
1836 int autoInc
, /* True if the AUTOINCREMENT keyword is present */
1837 int sortOrder
/* SQLITE_SO_ASC or SQLITE_SO_DESC */
1839 Table
*pTab
= pParse
->pNewTable
;
1843 if( pTab
==0 ) goto primary_key_exit
;
1844 if( pTab
->tabFlags
& TF_HasPrimaryKey
){
1845 sqlite3ErrorMsg(pParse
,
1846 "table \"%s\" has more than one primary key", pTab
->zName
);
1847 goto primary_key_exit
;
1849 pTab
->tabFlags
|= TF_HasPrimaryKey
;
1851 iCol
= pTab
->nCol
- 1;
1852 pCol
= &pTab
->aCol
[iCol
];
1853 makeColumnPartOfPrimaryKey(pParse
, pCol
);
1856 nTerm
= pList
->nExpr
;
1857 for(i
=0; i
<nTerm
; i
++){
1858 Expr
*pCExpr
= sqlite3ExprSkipCollate(pList
->a
[i
].pExpr
);
1859 assert( pCExpr
!=0 );
1860 sqlite3StringToId(pCExpr
);
1861 if( pCExpr
->op
==TK_ID
){
1863 assert( !ExprHasProperty(pCExpr
, EP_IntValue
) );
1864 zCName
= pCExpr
->u
.zToken
;
1865 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
1866 if( sqlite3StrICmp(zCName
, pTab
->aCol
[iCol
].zCnName
)==0 ){
1867 pCol
= &pTab
->aCol
[iCol
];
1868 makeColumnPartOfPrimaryKey(pParse
, pCol
);
1877 && pCol
->eCType
==COLTYPE_INTEGER
1878 && sortOrder
!=SQLITE_SO_DESC
1880 if( IN_RENAME_OBJECT
&& pList
){
1881 Expr
*pCExpr
= sqlite3ExprSkipCollate(pList
->a
[0].pExpr
);
1882 sqlite3RenameTokenRemap(pParse
, &pTab
->iPKey
, pCExpr
);
1885 pTab
->keyConf
= (u8
)onError
;
1886 assert( autoInc
==0 || autoInc
==1 );
1887 pTab
->tabFlags
|= autoInc
*TF_Autoincrement
;
1888 if( pList
) pParse
->iPkSortOrder
= pList
->a
[0].fg
.sortFlags
;
1889 (void)sqlite3HasExplicitNulls(pParse
, pList
);
1890 }else if( autoInc
){
1891 #ifndef SQLITE_OMIT_AUTOINCREMENT
1892 sqlite3ErrorMsg(pParse
, "AUTOINCREMENT is only allowed on an "
1893 "INTEGER PRIMARY KEY");
1896 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, onError
, 0,
1897 0, sortOrder
, 0, SQLITE_IDXTYPE_PRIMARYKEY
);
1902 sqlite3ExprListDelete(pParse
->db
, pList
);
1907 ** Add a new CHECK constraint to the table currently under construction.
1909 void sqlite3AddCheckConstraint(
1910 Parse
*pParse
, /* Parsing context */
1911 Expr
*pCheckExpr
, /* The check expression */
1912 const char *zStart
, /* Opening "(" */
1913 const char *zEnd
/* Closing ")" */
1915 #ifndef SQLITE_OMIT_CHECK
1916 Table
*pTab
= pParse
->pNewTable
;
1917 sqlite3
*db
= pParse
->db
;
1918 if( pTab
&& !IN_DECLARE_VTAB
1919 && !sqlite3BtreeIsReadonly(db
->aDb
[db
->init
.iDb
].pBt
)
1921 pTab
->pCheck
= sqlite3ExprListAppend(pParse
, pTab
->pCheck
, pCheckExpr
);
1922 if( pParse
->constraintName
.n
){
1923 sqlite3ExprListSetName(pParse
, pTab
->pCheck
, &pParse
->constraintName
, 1);
1926 for(zStart
++; sqlite3Isspace(zStart
[0]); zStart
++){}
1927 while( sqlite3Isspace(zEnd
[-1]) ){ zEnd
--; }
1929 t
.n
= (int)(zEnd
- t
.z
);
1930 sqlite3ExprListSetName(pParse
, pTab
->pCheck
, &t
, 1);
1935 sqlite3ExprDelete(pParse
->db
, pCheckExpr
);
1940 ** Set the collation function of the most recently parsed table column
1941 ** to the CollSeq given.
1943 void sqlite3AddCollateType(Parse
*pParse
, Token
*pToken
){
1946 char *zColl
; /* Dequoted name of collation sequence */
1949 if( (p
= pParse
->pNewTable
)==0 || IN_RENAME_OBJECT
) return;
1952 zColl
= sqlite3NameFromToken(db
, pToken
);
1953 if( !zColl
) return;
1955 if( sqlite3LocateCollSeq(pParse
, zColl
) ){
1957 sqlite3ColumnSetColl(db
, &p
->aCol
[i
], zColl
);
1959 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1960 ** then an index may have been created on this column before the
1961 ** collation type was added. Correct this if it is the case.
1963 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1964 assert( pIdx
->nKeyCol
==1 );
1965 if( pIdx
->aiColumn
[0]==i
){
1966 pIdx
->azColl
[0] = sqlite3ColumnColl(&p
->aCol
[i
]);
1970 sqlite3DbFree(db
, zColl
);
1973 /* Change the most recently parsed column to be a GENERATED ALWAYS AS
1976 void sqlite3AddGenerated(Parse
*pParse
, Expr
*pExpr
, Token
*pType
){
1977 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1978 u8 eType
= COLFLAG_VIRTUAL
;
1979 Table
*pTab
= pParse
->pNewTable
;
1982 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
1983 goto generated_done
;
1985 pCol
= &(pTab
->aCol
[pTab
->nCol
-1]);
1986 if( IN_DECLARE_VTAB
){
1987 sqlite3ErrorMsg(pParse
, "virtual tables cannot use computed columns");
1988 goto generated_done
;
1990 if( pCol
->iDflt
>0 ) goto generated_error
;
1992 if( pType
->n
==7 && sqlite3StrNICmp("virtual",pType
->z
,7)==0 ){
1994 }else if( pType
->n
==6 && sqlite3StrNICmp("stored",pType
->z
,6)==0 ){
1995 eType
= COLFLAG_STORED
;
1997 goto generated_error
;
2000 if( eType
==COLFLAG_VIRTUAL
) pTab
->nNVCol
--;
2001 pCol
->colFlags
|= eType
;
2002 assert( TF_HasVirtual
==COLFLAG_VIRTUAL
);
2003 assert( TF_HasStored
==COLFLAG_STORED
);
2004 pTab
->tabFlags
|= eType
;
2005 if( pCol
->colFlags
& COLFLAG_PRIMKEY
){
2006 makeColumnPartOfPrimaryKey(pParse
, pCol
); /* For the error message */
2008 if( ALWAYS(pExpr
) && pExpr
->op
==TK_ID
){
2009 /* The value of a generated column needs to be a real expression, not
2010 ** just a reference to another column, in order for covering index
2011 ** optimizations to work correctly. So if the value is not an expression,
2012 ** turn it into one by adding a unary "+" operator. */
2013 pExpr
= sqlite3PExpr(pParse
, TK_UPLUS
, pExpr
, 0);
2015 if( pExpr
&& pExpr
->op
!=TK_RAISE
) pExpr
->affExpr
= pCol
->affinity
;
2016 sqlite3ColumnSetExpr(pParse
, pTab
, pCol
, pExpr
);
2018 goto generated_done
;
2021 sqlite3ErrorMsg(pParse
, "error in generated column \"%s\"",
2024 sqlite3ExprDelete(pParse
->db
, pExpr
);
2026 /* Throw and error for the GENERATED ALWAYS AS clause if the
2027 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
2028 sqlite3ErrorMsg(pParse
, "generated columns not supported");
2029 sqlite3ExprDelete(pParse
->db
, pExpr
);
2034 ** Generate code that will increment the schema cookie.
2036 ** The schema cookie is used to determine when the schema for the
2037 ** database changes. After each schema change, the cookie value
2038 ** changes. When a process first reads the schema it records the
2039 ** cookie. Thereafter, whenever it goes to access the database,
2040 ** it checks the cookie to make sure the schema has not changed
2041 ** since it was last read.
2043 ** This plan is not completely bullet-proof. It is possible for
2044 ** the schema to change multiple times and for the cookie to be
2045 ** set back to prior value. But schema changes are infrequent
2046 ** and the probability of hitting the same cookie value is only
2047 ** 1 chance in 2^32. So we're safe enough.
2049 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
2050 ** the schema-version whenever the schema changes.
2052 void sqlite3ChangeCookie(Parse
*pParse
, int iDb
){
2053 sqlite3
*db
= pParse
->db
;
2054 Vdbe
*v
= pParse
->pVdbe
;
2055 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2056 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_SCHEMA_VERSION
,
2057 (int)(1+(unsigned)db
->aDb
[iDb
].pSchema
->schema_cookie
));
2061 ** Measure the number of characters needed to output the given
2062 ** identifier. The number returned includes any quotes used
2063 ** but does not include the null terminator.
2065 ** The estimate is conservative. It might be larger that what is
2068 static int identLength(const char *z
){
2070 for(n
=0; *z
; n
++, z
++){
2071 if( *z
=='"' ){ n
++; }
2077 ** The first parameter is a pointer to an output buffer. The second
2078 ** parameter is a pointer to an integer that contains the offset at
2079 ** which to write into the output buffer. This function copies the
2080 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
2081 ** to the specified offset in the buffer and updates *pIdx to refer
2082 ** to the first byte after the last byte written before returning.
2084 ** If the string zSignedIdent consists entirely of alpha-numeric
2085 ** characters, does not begin with a digit and is not an SQL keyword,
2086 ** then it is copied to the output buffer exactly as it is. Otherwise,
2087 ** it is quoted using double-quotes.
2089 static void identPut(char *z
, int *pIdx
, char *zSignedIdent
){
2090 unsigned char *zIdent
= (unsigned char*)zSignedIdent
;
2091 int i
, j
, needQuote
;
2094 for(j
=0; zIdent
[j
]; j
++){
2095 if( !sqlite3Isalnum(zIdent
[j
]) && zIdent
[j
]!='_' ) break;
2097 needQuote
= sqlite3Isdigit(zIdent
[0])
2098 || sqlite3KeywordCode(zIdent
, j
)!=TK_ID
2102 if( needQuote
) z
[i
++] = '"';
2103 for(j
=0; zIdent
[j
]; j
++){
2105 if( zIdent
[j
]=='"' ) z
[i
++] = '"';
2107 if( needQuote
) z
[i
++] = '"';
2113 ** Generate a CREATE TABLE statement appropriate for the given
2114 ** table. Memory to hold the text of the statement is obtained
2115 ** from sqliteMalloc() and must be freed by the calling function.
2117 static char *createTableStmt(sqlite3
*db
, Table
*p
){
2120 char *zSep
, *zSep2
, *zEnd
;
2123 for(pCol
= p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
2124 n
+= identLength(pCol
->zCnName
) + 5;
2126 n
+= identLength(p
->zName
);
2136 n
+= 35 + 6*p
->nCol
;
2137 zStmt
= sqlite3DbMallocRaw(0, n
);
2139 sqlite3OomFault(db
);
2142 sqlite3_snprintf(n
, zStmt
, "CREATE TABLE ");
2143 k
= sqlite3Strlen30(zStmt
);
2144 identPut(zStmt
, &k
, p
->zName
);
2146 for(pCol
=p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
2147 static const char * const azType
[] = {
2148 /* SQLITE_AFF_BLOB */ "",
2149 /* SQLITE_AFF_TEXT */ " TEXT",
2150 /* SQLITE_AFF_NUMERIC */ " NUM",
2151 /* SQLITE_AFF_INTEGER */ " INT",
2152 /* SQLITE_AFF_REAL */ " REAL",
2153 /* SQLITE_AFF_FLEXNUM */ " NUM",
2158 sqlite3_snprintf(n
-k
, &zStmt
[k
], zSep
);
2159 k
+= sqlite3Strlen30(&zStmt
[k
]);
2161 identPut(zStmt
, &k
, pCol
->zCnName
);
2162 assert( pCol
->affinity
-SQLITE_AFF_BLOB
>= 0 );
2163 assert( pCol
->affinity
-SQLITE_AFF_BLOB
< ArraySize(azType
) );
2164 testcase( pCol
->affinity
==SQLITE_AFF_BLOB
);
2165 testcase( pCol
->affinity
==SQLITE_AFF_TEXT
);
2166 testcase( pCol
->affinity
==SQLITE_AFF_NUMERIC
);
2167 testcase( pCol
->affinity
==SQLITE_AFF_INTEGER
);
2168 testcase( pCol
->affinity
==SQLITE_AFF_REAL
);
2169 testcase( pCol
->affinity
==SQLITE_AFF_FLEXNUM
);
2171 zType
= azType
[pCol
->affinity
- SQLITE_AFF_BLOB
];
2172 len
= sqlite3Strlen30(zType
);
2173 assert( pCol
->affinity
==SQLITE_AFF_BLOB
2174 || pCol
->affinity
==SQLITE_AFF_FLEXNUM
2175 || pCol
->affinity
==sqlite3AffinityType(zType
, 0) );
2176 memcpy(&zStmt
[k
], zType
, len
);
2180 sqlite3_snprintf(n
-k
, &zStmt
[k
], "%s", zEnd
);
2185 ** Resize an Index object to hold N columns total. Return SQLITE_OK
2186 ** on success and SQLITE_NOMEM on an OOM error.
2188 static int resizeIndexObject(sqlite3
*db
, Index
*pIdx
, int N
){
2191 if( pIdx
->nColumn
>=N
) return SQLITE_OK
;
2192 assert( pIdx
->isResized
==0 );
2193 nByte
= (sizeof(char*) + sizeof(LogEst
) + sizeof(i16
) + 1)*N
;
2194 zExtra
= sqlite3DbMallocZero(db
, nByte
);
2195 if( zExtra
==0 ) return SQLITE_NOMEM_BKPT
;
2196 memcpy(zExtra
, pIdx
->azColl
, sizeof(char*)*pIdx
->nColumn
);
2197 pIdx
->azColl
= (const char**)zExtra
;
2198 zExtra
+= sizeof(char*)*N
;
2199 memcpy(zExtra
, pIdx
->aiRowLogEst
, sizeof(LogEst
)*(pIdx
->nKeyCol
+1));
2200 pIdx
->aiRowLogEst
= (LogEst
*)zExtra
;
2201 zExtra
+= sizeof(LogEst
)*N
;
2202 memcpy(zExtra
, pIdx
->aiColumn
, sizeof(i16
)*pIdx
->nColumn
);
2203 pIdx
->aiColumn
= (i16
*)zExtra
;
2204 zExtra
+= sizeof(i16
)*N
;
2205 memcpy(zExtra
, pIdx
->aSortOrder
, pIdx
->nColumn
);
2206 pIdx
->aSortOrder
= (u8
*)zExtra
;
2208 pIdx
->isResized
= 1;
2213 ** Estimate the total row width for a table.
2215 static void estimateTableWidth(Table
*pTab
){
2216 unsigned wTable
= 0;
2217 const Column
*pTabCol
;
2219 for(i
=pTab
->nCol
, pTabCol
=pTab
->aCol
; i
>0; i
--, pTabCol
++){
2220 wTable
+= pTabCol
->szEst
;
2222 if( pTab
->iPKey
<0 ) wTable
++;
2223 pTab
->szTabRow
= sqlite3LogEst(wTable
*4);
2227 ** Estimate the average size of a row for an index.
2229 static void estimateIndexWidth(Index
*pIdx
){
2230 unsigned wIndex
= 0;
2232 const Column
*aCol
= pIdx
->pTable
->aCol
;
2233 for(i
=0; i
<pIdx
->nColumn
; i
++){
2234 i16 x
= pIdx
->aiColumn
[i
];
2235 assert( x
<pIdx
->pTable
->nCol
);
2236 wIndex
+= x
<0 ? 1 : aCol
[pIdx
->aiColumn
[i
]].szEst
;
2238 pIdx
->szIdxRow
= sqlite3LogEst(wIndex
*4);
2241 /* Return true if column number x is any of the first nCol entries of aiCol[].
2242 ** This is used to determine if the column number x appears in any of the
2243 ** first nCol entries of an index.
2245 static int hasColumn(const i16
*aiCol
, int nCol
, int x
){
2246 while( nCol
-- > 0 ){
2247 if( x
==*(aiCol
++) ){
2255 ** Return true if any of the first nKey entries of index pIdx exactly
2256 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
2257 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
2258 ** or may not be the same index as pPk.
2260 ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2261 ** not a rowid or expression.
2263 ** This routine differs from hasColumn() in that both the column and the
2264 ** collating sequence must match for this routine, but for hasColumn() only
2265 ** the column name must match.
2267 static int isDupColumn(Index
*pIdx
, int nKey
, Index
*pPk
, int iCol
){
2269 assert( nKey
<=pIdx
->nColumn
);
2270 assert( iCol
<MAX(pPk
->nColumn
,pPk
->nKeyCol
) );
2271 assert( pPk
->idxType
==SQLITE_IDXTYPE_PRIMARYKEY
);
2272 assert( pPk
->pTable
->tabFlags
& TF_WithoutRowid
);
2273 assert( pPk
->pTable
==pIdx
->pTable
);
2274 testcase( pPk
==pIdx
);
2275 j
= pPk
->aiColumn
[iCol
];
2276 assert( j
!=XN_ROWID
&& j
!=XN_EXPR
);
2277 for(i
=0; i
<nKey
; i
++){
2278 assert( pIdx
->aiColumn
[i
]>=0 || j
>=0 );
2279 if( pIdx
->aiColumn
[i
]==j
2280 && sqlite3StrICmp(pIdx
->azColl
[i
], pPk
->azColl
[iCol
])==0
2288 /* Recompute the colNotIdxed field of the Index.
2290 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2291 ** columns that are within the first 63 columns of the table and a 1 for
2292 ** all other bits (all columns that are not in the index). The
2293 ** high-order bit of colNotIdxed is always 1. All unindexed columns
2294 ** of the table have a 1.
2296 ** 2019-10-24: For the purpose of this computation, virtual columns are
2297 ** not considered to be covered by the index, even if they are in the
2298 ** index, because we do not trust the logic in whereIndexExprTrans() to be
2299 ** able to find all instances of a reference to the indexed table column
2300 ** and convert them into references to the index. Hence we always want
2301 ** the actual table at hand in order to recompute the virtual column, if
2304 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2305 ** to determine if the index is covering index.
2307 static void recomputeColumnsNotIndexed(Index
*pIdx
){
2310 Table
*pTab
= pIdx
->pTable
;
2311 for(j
=pIdx
->nColumn
-1; j
>=0; j
--){
2312 int x
= pIdx
->aiColumn
[j
];
2313 if( x
>=0 && (pTab
->aCol
[x
].colFlags
& COLFLAG_VIRTUAL
)==0 ){
2314 testcase( x
==BMS
-1 );
2315 testcase( x
==BMS
-2 );
2316 if( x
<BMS
-1 ) m
|= MASKBIT(x
);
2319 pIdx
->colNotIdxed
= ~m
;
2320 assert( (pIdx
->colNotIdxed
>>63)==1 ); /* See note-20221022-a */
2324 ** This routine runs at the end of parsing a CREATE TABLE statement that
2325 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
2326 ** internal schema data structures and the generated VDBE code so that they
2327 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2330 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2331 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2332 ** into BTREE_BLOBKEY.
2333 ** (3) Bypass the creation of the sqlite_schema table entry
2334 ** for the PRIMARY KEY as the primary key index is now
2335 ** identified by the sqlite_schema table entry of the table itself.
2336 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
2337 ** schema to the rootpage from the main table.
2338 ** (5) Add all table columns to the PRIMARY KEY Index object
2339 ** so that the PRIMARY KEY is a covering index. The surplus
2340 ** columns are part of KeyInfo.nAllField and are not used for
2341 ** sorting or lookup or uniqueness checks.
2342 ** (6) Replace the rowid tail on all automatically generated UNIQUE
2343 ** indices with the PRIMARY KEY columns.
2345 ** For virtual tables, only (1) is performed.
2347 static void convertToWithoutRowidTable(Parse
*pParse
, Table
*pTab
){
2353 sqlite3
*db
= pParse
->db
;
2354 Vdbe
*v
= pParse
->pVdbe
;
2356 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2358 if( !db
->init
.imposterTable
){
2359 for(i
=0; i
<pTab
->nCol
; i
++){
2360 if( (pTab
->aCol
[i
].colFlags
& COLFLAG_PRIMKEY
)!=0
2361 && (pTab
->aCol
[i
].notNull
==OE_None
)
2363 pTab
->aCol
[i
].notNull
= OE_Abort
;
2366 pTab
->tabFlags
|= TF_HasNotNull
;
2369 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2370 ** into BTREE_BLOBKEY.
2372 assert( !pParse
->bReturning
);
2373 if( pParse
->u1
.addrCrTab
){
2375 sqlite3VdbeChangeP3(v
, pParse
->u1
.addrCrTab
, BTREE_BLOBKEY
);
2378 /* Locate the PRIMARY KEY index. Or, if this table was originally
2379 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2381 if( pTab
->iPKey
>=0 ){
2384 sqlite3TokenInit(&ipkToken
, pTab
->aCol
[pTab
->iPKey
].zCnName
);
2385 pList
= sqlite3ExprListAppend(pParse
, 0,
2386 sqlite3ExprAlloc(db
, TK_ID
, &ipkToken
, 0));
2388 pTab
->tabFlags
&= ~TF_WithoutRowid
;
2391 if( IN_RENAME_OBJECT
){
2392 sqlite3RenameTokenRemap(pParse
, pList
->a
[0].pExpr
, &pTab
->iPKey
);
2394 pList
->a
[0].fg
.sortFlags
= pParse
->iPkSortOrder
;
2395 assert( pParse
->pNewTable
==pTab
);
2397 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, pTab
->keyConf
, 0, 0, 0, 0,
2398 SQLITE_IDXTYPE_PRIMARYKEY
);
2400 pTab
->tabFlags
&= ~TF_WithoutRowid
;
2403 assert( db
->mallocFailed
==0 );
2404 pPk
= sqlite3PrimaryKeyIndex(pTab
);
2405 assert( pPk
->nKeyCol
==1 );
2407 pPk
= sqlite3PrimaryKeyIndex(pTab
);
2411 ** Remove all redundant columns from the PRIMARY KEY. For example, change
2412 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
2413 ** code assumes the PRIMARY KEY contains no repeated columns.
2415 for(i
=j
=1; i
<pPk
->nKeyCol
; i
++){
2416 if( isDupColumn(pPk
, j
, pPk
, i
) ){
2419 testcase( hasColumn(pPk
->aiColumn
, j
, pPk
->aiColumn
[i
]) );
2420 pPk
->azColl
[j
] = pPk
->azColl
[i
];
2421 pPk
->aSortOrder
[j
] = pPk
->aSortOrder
[i
];
2422 pPk
->aiColumn
[j
++] = pPk
->aiColumn
[i
];
2428 pPk
->isCovering
= 1;
2429 if( !db
->init
.imposterTable
) pPk
->uniqNotNull
= 1;
2430 nPk
= pPk
->nColumn
= pPk
->nKeyCol
;
2432 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2433 ** table entry. This is only required if currently generating VDBE
2434 ** code for a CREATE TABLE (not when parsing one as part of reading
2435 ** a database schema). */
2436 if( v
&& pPk
->tnum
>0 ){
2437 assert( db
->init
.busy
==0 );
2438 sqlite3VdbeChangeOpcode(v
, (int)pPk
->tnum
, OP_Goto
);
2441 /* The root page of the PRIMARY KEY is the table root page */
2442 pPk
->tnum
= pTab
->tnum
;
2444 /* Update the in-memory representation of all UNIQUE indices by converting
2445 ** the final rowid column into one or more columns of the PRIMARY KEY.
2447 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2449 if( IsPrimaryKeyIndex(pIdx
) ) continue;
2450 for(i
=n
=0; i
<nPk
; i
++){
2451 if( !isDupColumn(pIdx
, pIdx
->nKeyCol
, pPk
, i
) ){
2452 testcase( hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) );
2457 /* This index is a superset of the primary key */
2458 pIdx
->nColumn
= pIdx
->nKeyCol
;
2461 if( resizeIndexObject(db
, pIdx
, pIdx
->nKeyCol
+n
) ) return;
2462 for(i
=0, j
=pIdx
->nKeyCol
; i
<nPk
; i
++){
2463 if( !isDupColumn(pIdx
, pIdx
->nKeyCol
, pPk
, i
) ){
2464 testcase( hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) );
2465 pIdx
->aiColumn
[j
] = pPk
->aiColumn
[i
];
2466 pIdx
->azColl
[j
] = pPk
->azColl
[i
];
2467 if( pPk
->aSortOrder
[i
] ){
2468 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
2469 pIdx
->bAscKeyBug
= 1;
2474 assert( pIdx
->nColumn
>=pIdx
->nKeyCol
+n
);
2475 assert( pIdx
->nColumn
>=j
);
2478 /* Add all table columns to the PRIMARY KEY index
2481 for(i
=0; i
<pTab
->nCol
; i
++){
2482 if( !hasColumn(pPk
->aiColumn
, nPk
, i
)
2483 && (pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
)==0 ) nExtra
++;
2485 if( resizeIndexObject(db
, pPk
, nPk
+nExtra
) ) return;
2486 for(i
=0, j
=nPk
; i
<pTab
->nCol
; i
++){
2487 if( !hasColumn(pPk
->aiColumn
, j
, i
)
2488 && (pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
)==0
2490 assert( j
<pPk
->nColumn
);
2491 pPk
->aiColumn
[j
] = i
;
2492 pPk
->azColl
[j
] = sqlite3StrBINARY
;
2496 assert( pPk
->nColumn
==j
);
2497 assert( pTab
->nNVCol
<=j
);
2498 recomputeColumnsNotIndexed(pPk
);
2502 #ifndef SQLITE_OMIT_VIRTUALTABLE
2504 ** Return true if pTab is a virtual table and zName is a shadow table name
2505 ** for that virtual table.
2507 int sqlite3IsShadowTableOf(sqlite3
*db
, Table
*pTab
, const char *zName
){
2508 int nName
; /* Length of zName */
2509 Module
*pMod
; /* Module for the virtual table */
2511 if( !IsVirtual(pTab
) ) return 0;
2512 nName
= sqlite3Strlen30(pTab
->zName
);
2513 if( sqlite3_strnicmp(zName
, pTab
->zName
, nName
)!=0 ) return 0;
2514 if( zName
[nName
]!='_' ) return 0;
2515 pMod
= (Module
*)sqlite3HashFind(&db
->aModule
, pTab
->u
.vtab
.azArg
[0]);
2516 if( pMod
==0 ) return 0;
2517 if( pMod
->pModule
->iVersion
<3 ) return 0;
2518 if( pMod
->pModule
->xShadowName
==0 ) return 0;
2519 return pMod
->pModule
->xShadowName(zName
+nName
+1);
2521 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2523 #ifndef SQLITE_OMIT_VIRTUALTABLE
2525 ** Table pTab is a virtual table. If it the virtual table implementation
2526 ** exists and has an xShadowName method, then loop over all other ordinary
2527 ** tables within the same schema looking for shadow tables of pTab, and mark
2528 ** any shadow tables seen using the TF_Shadow flag.
2530 void sqlite3MarkAllShadowTablesOf(sqlite3
*db
, Table
*pTab
){
2531 int nName
; /* Length of pTab->zName */
2532 Module
*pMod
; /* Module for the virtual table */
2533 HashElem
*k
; /* For looping through the symbol table */
2535 assert( IsVirtual(pTab
) );
2536 pMod
= (Module
*)sqlite3HashFind(&db
->aModule
, pTab
->u
.vtab
.azArg
[0]);
2537 if( pMod
==0 ) return;
2538 if( NEVER(pMod
->pModule
==0) ) return;
2539 if( pMod
->pModule
->iVersion
<3 ) return;
2540 if( pMod
->pModule
->xShadowName
==0 ) return;
2541 assert( pTab
->zName
!=0 );
2542 nName
= sqlite3Strlen30(pTab
->zName
);
2543 for(k
=sqliteHashFirst(&pTab
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
2544 Table
*pOther
= sqliteHashData(k
);
2545 assert( pOther
->zName
!=0 );
2546 if( !IsOrdinaryTable(pOther
) ) continue;
2547 if( pOther
->tabFlags
& TF_Shadow
) continue;
2548 if( sqlite3StrNICmp(pOther
->zName
, pTab
->zName
, nName
)==0
2549 && pOther
->zName
[nName
]=='_'
2550 && pMod
->pModule
->xShadowName(pOther
->zName
+nName
+1)
2552 pOther
->tabFlags
|= TF_Shadow
;
2556 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2558 #ifndef SQLITE_OMIT_VIRTUALTABLE
2560 ** Return true if zName is a shadow table name in the current database
2563 ** zName is temporarily modified while this routine is running, but is
2564 ** restored to its original value prior to this routine returning.
2566 int sqlite3ShadowTableName(sqlite3
*db
, const char *zName
){
2567 char *zTail
; /* Pointer to the last "_" in zName */
2568 Table
*pTab
; /* Table that zName is a shadow of */
2569 zTail
= strrchr(zName
, '_');
2570 if( zTail
==0 ) return 0;
2572 pTab
= sqlite3FindTable(db
, zName
, 0);
2574 if( pTab
==0 ) return 0;
2575 if( !IsVirtual(pTab
) ) return 0;
2576 return sqlite3IsShadowTableOf(db
, pTab
, zName
);
2578 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2583 ** Mark all nodes of an expression as EP_Immutable, indicating that
2584 ** they should not be changed. Expressions attached to a table or
2585 ** index definition are tagged this way to help ensure that we do
2586 ** not pass them into code generator routines by mistake.
2588 static int markImmutableExprStep(Walker
*pWalker
, Expr
*pExpr
){
2590 ExprSetVVAProperty(pExpr
, EP_Immutable
);
2591 return WRC_Continue
;
2593 static void markExprListImmutable(ExprList
*pList
){
2596 memset(&w
, 0, sizeof(w
));
2597 w
.xExprCallback
= markImmutableExprStep
;
2598 w
.xSelectCallback
= sqlite3SelectWalkNoop
;
2599 w
.xSelectCallback2
= 0;
2600 sqlite3WalkExprList(&w
, pList
);
2604 #define markExprListImmutable(X) /* no-op */
2605 #endif /* SQLITE_DEBUG */
2609 ** This routine is called to report the final ")" that terminates
2610 ** a CREATE TABLE statement.
2612 ** The table structure that other action routines have been building
2613 ** is added to the internal hash tables, assuming no errors have
2616 ** An entry for the table is made in the schema table on disk, unless
2617 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
2618 ** it means we are reading the sqlite_schema table because we just
2619 ** connected to the database or because the sqlite_schema table has
2620 ** recently changed, so the entry for this table already exists in
2621 ** the sqlite_schema table. We do not want to create it again.
2623 ** If the pSelect argument is not NULL, it means that this routine
2624 ** was called to create a table generated from a
2625 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2626 ** the new table will match the result set of the SELECT.
2628 void sqlite3EndTable(
2629 Parse
*pParse
, /* Parse context */
2630 Token
*pCons
, /* The ',' token after the last column defn. */
2631 Token
*pEnd
, /* The ')' before options in the CREATE TABLE */
2632 u32 tabOpts
, /* Extra table options. Usually 0. */
2633 Select
*pSelect
/* Select from a "CREATE ... AS SELECT" */
2635 Table
*p
; /* The new table */
2636 sqlite3
*db
= pParse
->db
; /* The database connection */
2637 int iDb
; /* Database in which the table lives */
2638 Index
*pIdx
; /* An implied index of the table */
2640 if( pEnd
==0 && pSelect
==0 ){
2643 p
= pParse
->pNewTable
;
2646 if( pSelect
==0 && sqlite3ShadowTableName(db
, p
->zName
) ){
2647 p
->tabFlags
|= TF_Shadow
;
2650 /* If the db->init.busy is 1 it means we are reading the SQL off the
2651 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2652 ** So do not write to the disk again. Extract the root page number
2653 ** for the table from the db->init.newTnum field. (The page number
2654 ** should have been put there by the sqliteOpenCb routine.)
2656 ** If the root page number is 1, that means this is the sqlite_schema
2657 ** table itself. So mark it read-only.
2659 if( db
->init
.busy
){
2660 if( pSelect
|| (!IsOrdinaryTable(p
) && db
->init
.newTnum
) ){
2661 sqlite3ErrorMsg(pParse
, "");
2664 p
->tnum
= db
->init
.newTnum
;
2665 if( p
->tnum
==1 ) p
->tabFlags
|= TF_Readonly
;
2668 /* Special processing for tables that include the STRICT keyword:
2670 ** * Do not allow custom column datatypes. Every column must have
2671 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
2673 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
2674 ** then all columns of the PRIMARY KEY must have a NOT NULL
2677 if( tabOpts
& TF_Strict
){
2679 p
->tabFlags
|= TF_Strict
;
2680 for(ii
=0; ii
<p
->nCol
; ii
++){
2681 Column
*pCol
= &p
->aCol
[ii
];
2682 if( pCol
->eCType
==COLTYPE_CUSTOM
){
2683 if( pCol
->colFlags
& COLFLAG_HASTYPE
){
2684 sqlite3ErrorMsg(pParse
,
2685 "unknown datatype for %s.%s: \"%s\"",
2686 p
->zName
, pCol
->zCnName
, sqlite3ColumnType(pCol
, "")
2689 sqlite3ErrorMsg(pParse
, "missing datatype for %s.%s",
2690 p
->zName
, pCol
->zCnName
);
2693 }else if( pCol
->eCType
==COLTYPE_ANY
){
2694 pCol
->affinity
= SQLITE_AFF_BLOB
;
2696 if( (pCol
->colFlags
& COLFLAG_PRIMKEY
)!=0
2698 && pCol
->notNull
== OE_None
2700 pCol
->notNull
= OE_Abort
;
2701 p
->tabFlags
|= TF_HasNotNull
;
2706 assert( (p
->tabFlags
& TF_HasPrimaryKey
)==0
2707 || p
->iPKey
>=0 || sqlite3PrimaryKeyIndex(p
)!=0 );
2708 assert( (p
->tabFlags
& TF_HasPrimaryKey
)!=0
2709 || (p
->iPKey
<0 && sqlite3PrimaryKeyIndex(p
)==0) );
2711 /* Special processing for WITHOUT ROWID Tables */
2712 if( tabOpts
& TF_WithoutRowid
){
2713 if( (p
->tabFlags
& TF_Autoincrement
) ){
2714 sqlite3ErrorMsg(pParse
,
2715 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2718 if( (p
->tabFlags
& TF_HasPrimaryKey
)==0 ){
2719 sqlite3ErrorMsg(pParse
, "PRIMARY KEY missing on table %s", p
->zName
);
2722 p
->tabFlags
|= TF_WithoutRowid
| TF_NoVisibleRowid
;
2723 convertToWithoutRowidTable(pParse
, p
);
2725 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
2727 #ifndef SQLITE_OMIT_CHECK
2728 /* Resolve names in all CHECK constraint expressions.
2731 sqlite3ResolveSelfReference(pParse
, p
, NC_IsCheck
, 0, p
->pCheck
);
2733 /* If errors are seen, delete the CHECK constraints now, else they might
2734 ** actually be used if PRAGMA writable_schema=ON is set. */
2735 sqlite3ExprListDelete(db
, p
->pCheck
);
2738 markExprListImmutable(p
->pCheck
);
2741 #endif /* !defined(SQLITE_OMIT_CHECK) */
2742 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
2743 if( p
->tabFlags
& TF_HasGenerated
){
2745 testcase( p
->tabFlags
& TF_HasVirtual
);
2746 testcase( p
->tabFlags
& TF_HasStored
);
2747 for(ii
=0; ii
<p
->nCol
; ii
++){
2748 u32 colFlags
= p
->aCol
[ii
].colFlags
;
2749 if( (colFlags
& COLFLAG_GENERATED
)!=0 ){
2750 Expr
*pX
= sqlite3ColumnExpr(p
, &p
->aCol
[ii
]);
2751 testcase( colFlags
& COLFLAG_VIRTUAL
);
2752 testcase( colFlags
& COLFLAG_STORED
);
2753 if( sqlite3ResolveSelfReference(pParse
, p
, NC_GenCol
, pX
, 0) ){
2754 /* If there are errors in resolving the expression, change the
2755 ** expression to a NULL. This prevents code generators that operate
2756 ** on the expression from inserting extra parts into the expression
2757 ** tree that have been allocated from lookaside memory, which is
2758 ** illegal in a schema and will lead to errors or heap corruption
2759 ** when the database connection closes. */
2760 sqlite3ColumnSetExpr(pParse
, p
, &p
->aCol
[ii
],
2761 sqlite3ExprAlloc(db
, TK_NULL
, 0, 0));
2768 sqlite3ErrorMsg(pParse
, "must have at least one non-generated column");
2774 /* Estimate the average row size for the table and for all implied indices */
2775 estimateTableWidth(p
);
2776 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2777 estimateIndexWidth(pIdx
);
2780 /* If not initializing, then create a record for the new table
2781 ** in the schema table of the database.
2783 ** If this is a TEMPORARY table, write the entry into the auxiliary
2784 ** file instead of into the main database file.
2786 if( !db
->init
.busy
){
2789 char *zType
; /* "view" or "table" */
2790 char *zType2
; /* "VIEW" or "TABLE" */
2791 char *zStmt
; /* Text of the CREATE TABLE or CREATE VIEW statement */
2793 v
= sqlite3GetVdbe(pParse
);
2794 if( NEVER(v
==0) ) return;
2796 sqlite3VdbeAddOp1(v
, OP_Close
, 0);
2799 ** Initialize zType for the new view or table.
2801 if( IsOrdinaryTable(p
) ){
2802 /* A regular table */
2805 #ifndef SQLITE_OMIT_VIEW
2813 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2814 ** statement to populate the new table. The root-page number for the
2815 ** new table is in register pParse->regRoot.
2817 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2818 ** suitable state to query for the column names and types to be used
2819 ** by the new table.
2821 ** A shared-cache write-lock is not required to write to the new table,
2822 ** as a schema-lock must have already been obtained to create it. Since
2823 ** a schema-lock excludes all other database users, the write-lock would
2827 SelectDest dest
; /* Where the SELECT should store results */
2828 int regYield
; /* Register holding co-routine entry-point */
2829 int addrTop
; /* Top of the co-routine */
2830 int regRec
; /* A record to be insert into the new table */
2831 int regRowid
; /* Rowid of the next row to insert */
2832 int addrInsLoop
; /* Top of the loop for inserting rows */
2833 Table
*pSelTab
; /* A table that describes the SELECT results */
2835 if( IN_SPECIAL_PARSE
){
2836 pParse
->rc
= SQLITE_ERROR
;
2840 regYield
= ++pParse
->nMem
;
2841 regRec
= ++pParse
->nMem
;
2842 regRowid
= ++pParse
->nMem
;
2843 assert(pParse
->nTab
==1);
2844 sqlite3MayAbort(pParse
);
2845 sqlite3VdbeAddOp3(v
, OP_OpenWrite
, 1, pParse
->regRoot
, iDb
);
2846 sqlite3VdbeChangeP5(v
, OPFLAG_P2ISREG
);
2848 addrTop
= sqlite3VdbeCurrentAddr(v
) + 1;
2849 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, addrTop
);
2850 if( pParse
->nErr
) return;
2851 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSelect
, SQLITE_AFF_BLOB
);
2852 if( pSelTab
==0 ) return;
2853 assert( p
->aCol
==0 );
2854 p
->nCol
= p
->nNVCol
= pSelTab
->nCol
;
2855 p
->aCol
= pSelTab
->aCol
;
2858 sqlite3DeleteTable(db
, pSelTab
);
2859 sqlite3SelectDestInit(&dest
, SRT_Coroutine
, regYield
);
2860 sqlite3Select(pParse
, pSelect
, &dest
);
2861 if( pParse
->nErr
) return;
2862 sqlite3VdbeEndCoroutine(v
, regYield
);
2863 sqlite3VdbeJumpHere(v
, addrTop
- 1);
2864 addrInsLoop
= sqlite3VdbeAddOp1(v
, OP_Yield
, dest
.iSDParm
);
2866 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, dest
.iSdst
, dest
.nSdst
, regRec
);
2867 sqlite3TableAffinity(v
, p
, 0);
2868 sqlite3VdbeAddOp2(v
, OP_NewRowid
, 1, regRowid
);
2869 sqlite3VdbeAddOp3(v
, OP_Insert
, 1, regRec
, regRowid
);
2870 sqlite3VdbeGoto(v
, addrInsLoop
);
2871 sqlite3VdbeJumpHere(v
, addrInsLoop
);
2872 sqlite3VdbeAddOp1(v
, OP_Close
, 1);
2875 /* Compute the complete text of the CREATE statement */
2877 zStmt
= createTableStmt(db
, p
);
2879 Token
*pEnd2
= tabOpts
? &pParse
->sLastToken
: pEnd
;
2880 n
= (int)(pEnd2
->z
- pParse
->sNameToken
.z
);
2881 if( pEnd2
->z
[0]!=';' ) n
+= pEnd2
->n
;
2882 zStmt
= sqlite3MPrintf(db
,
2883 "CREATE %s %.*s", zType2
, n
, pParse
->sNameToken
.z
2887 /* A slot for the record has already been allocated in the
2888 ** schema table. We just need to update that slot with all
2889 ** the information we've collected.
2891 sqlite3NestedParse(pParse
,
2892 "UPDATE %Q." LEGACY_SCHEMA_TABLE
2893 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
2895 db
->aDb
[iDb
].zDbSName
,
2903 sqlite3DbFree(db
, zStmt
);
2904 sqlite3ChangeCookie(pParse
, iDb
);
2906 #ifndef SQLITE_OMIT_AUTOINCREMENT
2907 /* Check to see if we need to create an sqlite_sequence table for
2908 ** keeping track of autoincrement keys.
2910 if( (p
->tabFlags
& TF_Autoincrement
)!=0 && !IN_SPECIAL_PARSE
){
2911 Db
*pDb
= &db
->aDb
[iDb
];
2912 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2913 if( pDb
->pSchema
->pSeqTab
==0 ){
2914 sqlite3NestedParse(pParse
,
2915 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2922 /* Reparse everything to update our internal data structures */
2923 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
2924 sqlite3MPrintf(db
, "tbl_name='%q' AND type!='trigger'", p
->zName
),0);
2927 /* Add the table to the in-memory representation of the database.
2929 if( db
->init
.busy
){
2931 Schema
*pSchema
= p
->pSchema
;
2932 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2933 assert( HasRowid(p
) || p
->iPKey
<0 );
2934 pOld
= sqlite3HashInsert(&pSchema
->tblHash
, p
->zName
, p
);
2936 assert( p
==pOld
); /* Malloc must have failed inside HashInsert() */
2937 sqlite3OomFault(db
);
2940 pParse
->pNewTable
= 0;
2941 db
->mDbFlags
|= DBFLAG_SchemaChange
;
2943 /* If this is the magic sqlite_sequence table used by autoincrement,
2944 ** then record a pointer to this table in the main database structure
2945 ** so that INSERT can find the table easily. */
2946 assert( !pParse
->nested
);
2947 #ifndef SQLITE_OMIT_AUTOINCREMENT
2948 if( strcmp(p
->zName
, "sqlite_sequence")==0 ){
2949 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2950 p
->pSchema
->pSeqTab
= p
;
2955 #ifndef SQLITE_OMIT_ALTERTABLE
2956 if( !pSelect
&& IsOrdinaryTable(p
) ){
2957 assert( pCons
&& pEnd
);
2961 p
->u
.tab
.addColOffset
= 13 + (int)(pCons
->z
- pParse
->sNameToken
.z
);
2966 #ifndef SQLITE_OMIT_VIEW
2968 ** The parser calls this routine in order to create a new VIEW
2970 void sqlite3CreateView(
2971 Parse
*pParse
, /* The parsing context */
2972 Token
*pBegin
, /* The CREATE token that begins the statement */
2973 Token
*pName1
, /* The token that holds the name of the view */
2974 Token
*pName2
, /* The token that holds the name of the view */
2975 ExprList
*pCNames
, /* Optional list of view column names */
2976 Select
*pSelect
, /* A SELECT statement that will become the new view */
2977 int isTemp
, /* TRUE for a TEMPORARY view */
2978 int noErr
/* Suppress error messages if VIEW already exists */
2987 sqlite3
*db
= pParse
->db
;
2989 if( pParse
->nVar
>0 ){
2990 sqlite3ErrorMsg(pParse
, "parameters are not allowed in views");
2991 goto create_view_fail
;
2993 sqlite3StartTable(pParse
, pName1
, pName2
, isTemp
, 1, 0, noErr
);
2994 p
= pParse
->pNewTable
;
2995 if( p
==0 || pParse
->nErr
) goto create_view_fail
;
2997 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
2998 ** on a view, even though views do not have rowids. The following flag
2999 ** setting fixes this problem. But the fix can be disabled by compiling
3000 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
3001 ** depend upon the old buggy behavior. */
3002 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
3003 p
->tabFlags
|= TF_NoVisibleRowid
;
3006 sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
3007 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
3008 sqlite3FixInit(&sFix
, pParse
, iDb
, "view", pName
);
3009 if( sqlite3FixSelect(&sFix
, pSelect
) ) goto create_view_fail
;
3011 /* Make a copy of the entire SELECT statement that defines the view.
3012 ** This will force all the Expr.token.z values to be dynamically
3013 ** allocated rather than point to the input string - which means that
3014 ** they will persist after the current sqlite3_exec() call returns.
3016 pSelect
->selFlags
|= SF_View
;
3017 if( IN_RENAME_OBJECT
){
3018 p
->u
.view
.pSelect
= pSelect
;
3021 p
->u
.view
.pSelect
= sqlite3SelectDup(db
, pSelect
, EXPRDUP_REDUCE
);
3023 p
->pCheck
= sqlite3ExprListDup(db
, pCNames
, EXPRDUP_REDUCE
);
3024 p
->eTabType
= TABTYP_VIEW
;
3025 if( db
->mallocFailed
) goto create_view_fail
;
3027 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
3030 sEnd
= pParse
->sLastToken
;
3031 assert( sEnd
.z
[0]!=0 || sEnd
.n
==0 );
3032 if( sEnd
.z
[0]!=';' ){
3036 n
= (int)(sEnd
.z
- pBegin
->z
);
3039 while( sqlite3Isspace(z
[n
-1]) ){ n
--; }
3043 /* Use sqlite3EndTable() to add the view to the schema table */
3044 sqlite3EndTable(pParse
, 0, &sEnd
, 0, 0);
3047 sqlite3SelectDelete(db
, pSelect
);
3048 if( IN_RENAME_OBJECT
){
3049 sqlite3RenameExprlistUnmap(pParse
, pCNames
);
3051 sqlite3ExprListDelete(db
, pCNames
);
3054 #endif /* SQLITE_OMIT_VIEW */
3056 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3058 ** The Table structure pTable is really a VIEW. Fill in the names of
3059 ** the columns of the view in the pTable structure. Return the number
3060 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
3062 static SQLITE_NOINLINE
int viewGetColumnNames(Parse
*pParse
, Table
*pTable
){
3063 Table
*pSelTab
; /* A fake table from which we get the result set */
3064 Select
*pSel
; /* Copy of the SELECT that implements the view */
3065 int nErr
= 0; /* Number of errors encountered */
3066 sqlite3
*db
= pParse
->db
; /* Database connection for malloc errors */
3067 #ifndef SQLITE_OMIT_VIRTUALTABLE
3070 #ifndef SQLITE_OMIT_AUTHORIZATION
3071 sqlite3_xauth xAuth
; /* Saved xAuth pointer */
3076 #ifndef SQLITE_OMIT_VIRTUALTABLE
3077 if( IsVirtual(pTable
) ){
3079 rc
= sqlite3VtabCallConnect(pParse
, pTable
);
3085 #ifndef SQLITE_OMIT_VIEW
3086 /* A positive nCol means the columns names for this view are
3087 ** already known. This routine is not called unless either the
3088 ** table is virtual or nCol is zero.
3090 assert( pTable
->nCol
<=0 );
3092 /* A negative nCol is a special marker meaning that we are currently
3093 ** trying to compute the column names. If we enter this routine with
3094 ** a negative nCol, it means two or more views form a loop, like this:
3096 ** CREATE VIEW one AS SELECT * FROM two;
3097 ** CREATE VIEW two AS SELECT * FROM one;
3099 ** Actually, the error above is now caught prior to reaching this point.
3100 ** But the following test is still important as it does come up
3101 ** in the following:
3103 ** CREATE TABLE main.ex1(a);
3104 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3105 ** SELECT * FROM temp.ex1;
3107 if( pTable
->nCol
<0 ){
3108 sqlite3ErrorMsg(pParse
, "view %s is circularly defined", pTable
->zName
);
3111 assert( pTable
->nCol
>=0 );
3113 /* If we get this far, it means we need to compute the table names.
3114 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
3115 ** "*" elements in the results set of the view and will assign cursors
3116 ** to the elements of the FROM clause. But we do not want these changes
3117 ** to be permanent. So the computation is done on a copy of the SELECT
3118 ** statement that defines the view.
3120 assert( IsView(pTable
) );
3121 pSel
= sqlite3SelectDup(db
, pTable
->u
.view
.pSelect
, 0);
3123 u8 eParseMode
= pParse
->eParseMode
;
3124 int nTab
= pParse
->nTab
;
3125 int nSelect
= pParse
->nSelect
;
3126 pParse
->eParseMode
= PARSE_MODE_NORMAL
;
3127 sqlite3SrcListAssignCursors(pParse
, pSel
->pSrc
);
3130 #ifndef SQLITE_OMIT_AUTHORIZATION
3133 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
, SQLITE_AFF_NONE
);
3136 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
, SQLITE_AFF_NONE
);
3138 pParse
->nTab
= nTab
;
3139 pParse
->nSelect
= nSelect
;
3143 }else if( pTable
->pCheck
){
3144 /* CREATE VIEW name(arglist) AS ...
3145 ** The names of the columns in the table are taken from
3146 ** arglist which is stored in pTable->pCheck. The pCheck field
3147 ** normally holds CHECK constraints on an ordinary table, but for
3148 ** a VIEW it holds the list of column names.
3150 sqlite3ColumnsFromExprList(pParse
, pTable
->pCheck
,
3151 &pTable
->nCol
, &pTable
->aCol
);
3153 && pTable
->nCol
==pSel
->pEList
->nExpr
3155 assert( db
->mallocFailed
==0 );
3156 sqlite3SubqueryColumnTypes(pParse
, pTable
, pSel
, SQLITE_AFF_NONE
);
3159 /* CREATE VIEW name AS... without an argument list. Construct
3160 ** the column names from the SELECT statement that defines the view.
3162 assert( pTable
->aCol
==0 );
3163 pTable
->nCol
= pSelTab
->nCol
;
3164 pTable
->aCol
= pSelTab
->aCol
;
3165 pTable
->tabFlags
|= (pSelTab
->tabFlags
& COLFLAG_NOINSERT
);
3168 assert( sqlite3SchemaMutexHeld(db
, 0, pTable
->pSchema
) );
3170 pTable
->nNVCol
= pTable
->nCol
;
3171 sqlite3DeleteTable(db
, pSelTab
);
3172 sqlite3SelectDelete(db
, pSel
);
3174 pParse
->eParseMode
= eParseMode
;
3178 pTable
->pSchema
->schemaFlags
|= DB_UnresetViews
;
3179 if( db
->mallocFailed
){
3180 sqlite3DeleteColumnNames(db
, pTable
);
3182 #endif /* SQLITE_OMIT_VIEW */
3185 int sqlite3ViewGetColumnNames(Parse
*pParse
, Table
*pTable
){
3186 assert( pTable
!=0 );
3187 if( !IsVirtual(pTable
) && pTable
->nCol
>0 ) return 0;
3188 return viewGetColumnNames(pParse
, pTable
);
3190 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3192 #ifndef SQLITE_OMIT_VIEW
3194 ** Clear the column names from every VIEW in database idx.
3196 static void sqliteViewResetAll(sqlite3
*db
, int idx
){
3198 assert( sqlite3SchemaMutexHeld(db
, idx
, 0) );
3199 if( !DbHasProperty(db
, idx
, DB_UnresetViews
) ) return;
3200 for(i
=sqliteHashFirst(&db
->aDb
[idx
].pSchema
->tblHash
); i
;i
=sqliteHashNext(i
)){
3201 Table
*pTab
= sqliteHashData(i
);
3203 sqlite3DeleteColumnNames(db
, pTab
);
3206 DbClearProperty(db
, idx
, DB_UnresetViews
);
3209 # define sqliteViewResetAll(A,B)
3210 #endif /* SQLITE_OMIT_VIEW */
3213 ** This function is called by the VDBE to adjust the internal schema
3214 ** used by SQLite when the btree layer moves a table root page. The
3215 ** root-page of a table or index in database iDb has changed from iFrom
3218 ** Ticket #1728: The symbol table might still contain information
3219 ** on tables and/or indices that are the process of being deleted.
3220 ** If you are unlucky, one of those deleted indices or tables might
3221 ** have the same rootpage number as the real table or index that is
3222 ** being moved. So we cannot stop searching after the first match
3223 ** because the first match might be for one of the deleted indices
3224 ** or tables and not the table/index that is actually being moved.
3225 ** We must continue looping until all tables and indices with
3226 ** rootpage==iFrom have been converted to have a rootpage of iTo
3227 ** in order to be certain that we got the right one.
3229 #ifndef SQLITE_OMIT_AUTOVACUUM
3230 void sqlite3RootPageMoved(sqlite3
*db
, int iDb
, Pgno iFrom
, Pgno iTo
){
3235 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
3236 pDb
= &db
->aDb
[iDb
];
3237 pHash
= &pDb
->pSchema
->tblHash
;
3238 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
3239 Table
*pTab
= sqliteHashData(pElem
);
3240 if( pTab
->tnum
==iFrom
){
3244 pHash
= &pDb
->pSchema
->idxHash
;
3245 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
3246 Index
*pIdx
= sqliteHashData(pElem
);
3247 if( pIdx
->tnum
==iFrom
){
3255 ** Write code to erase the table with root-page iTable from database iDb.
3256 ** Also write code to modify the sqlite_schema table and internal schema
3257 ** if a root-page of another table is moved by the btree-layer whilst
3258 ** erasing iTable (this can happen with an auto-vacuum database).
3260 static void destroyRootPage(Parse
*pParse
, int iTable
, int iDb
){
3261 Vdbe
*v
= sqlite3GetVdbe(pParse
);
3262 int r1
= sqlite3GetTempReg(pParse
);
3263 if( iTable
<2 ) sqlite3ErrorMsg(pParse
, "corrupt schema");
3264 sqlite3VdbeAddOp3(v
, OP_Destroy
, iTable
, r1
, iDb
);
3265 sqlite3MayAbort(pParse
);
3266 #ifndef SQLITE_OMIT_AUTOVACUUM
3267 /* OP_Destroy stores an in integer r1. If this integer
3268 ** is non-zero, then it is the root page number of a table moved to
3269 ** location iTable. The following code modifies the sqlite_schema table to
3272 ** The "#NNN" in the SQL is a special constant that means whatever value
3273 ** is in register NNN. See grammar rules associated with the TK_REGISTER
3274 ** token for additional information.
3276 sqlite3NestedParse(pParse
,
3277 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3278 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3279 pParse
->db
->aDb
[iDb
].zDbSName
, iTable
, r1
, r1
);
3281 sqlite3ReleaseTempReg(pParse
, r1
);
3285 ** Write VDBE code to erase table pTab and all associated indices on disk.
3286 ** Code to update the sqlite_schema tables and internal schema definitions
3287 ** in case a root-page belonging to another table is moved by the btree layer
3288 ** is also added (this can happen with an auto-vacuum database).
3290 static void destroyTable(Parse
*pParse
, Table
*pTab
){
3291 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3292 ** is not defined), then it is important to call OP_Destroy on the
3293 ** table and index root-pages in order, starting with the numerically
3294 ** largest root-page number. This guarantees that none of the root-pages
3295 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3296 ** following were coded:
3302 ** and root page 5 happened to be the largest root-page number in the
3303 ** database, then root page 5 would be moved to page 4 by the
3304 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3305 ** a free-list page.
3307 Pgno iTab
= pTab
->tnum
;
3308 Pgno iDestroyed
= 0;
3314 if( iDestroyed
==0 || iTab
<iDestroyed
){
3317 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
3318 Pgno iIdx
= pIdx
->tnum
;
3319 assert( pIdx
->pSchema
==pTab
->pSchema
);
3320 if( (iDestroyed
==0 || (iIdx
<iDestroyed
)) && iIdx
>iLargest
){
3327 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
3328 assert( iDb
>=0 && iDb
<pParse
->db
->nDb
);
3329 destroyRootPage(pParse
, iLargest
, iDb
);
3330 iDestroyed
= iLargest
;
3336 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3337 ** after a DROP INDEX or DROP TABLE command.
3339 static void sqlite3ClearStatTables(
3340 Parse
*pParse
, /* The parsing context */
3341 int iDb
, /* The database number */
3342 const char *zType
, /* "idx" or "tbl" */
3343 const char *zName
/* Name of index or table */
3346 const char *zDbName
= pParse
->db
->aDb
[iDb
].zDbSName
;
3347 for(i
=1; i
<=4; i
++){
3349 sqlite3_snprintf(sizeof(zTab
),zTab
,"sqlite_stat%d",i
);
3350 if( sqlite3FindTable(pParse
->db
, zTab
, zDbName
) ){
3351 sqlite3NestedParse(pParse
,
3352 "DELETE FROM %Q.%s WHERE %s=%Q",
3353 zDbName
, zTab
, zType
, zName
3360 ** Generate code to drop a table.
3362 void sqlite3CodeDropTable(Parse
*pParse
, Table
*pTab
, int iDb
, int isView
){
3364 sqlite3
*db
= pParse
->db
;
3366 Db
*pDb
= &db
->aDb
[iDb
];
3368 v
= sqlite3GetVdbe(pParse
);
3370 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3372 #ifndef SQLITE_OMIT_VIRTUALTABLE
3373 if( IsVirtual(pTab
) ){
3374 sqlite3VdbeAddOp0(v
, OP_VBegin
);
3378 /* Drop all triggers associated with the table being dropped. Code
3379 ** is generated to remove entries from sqlite_schema and/or
3380 ** sqlite_temp_schema if required.
3382 pTrigger
= sqlite3TriggerList(pParse
, pTab
);
3384 assert( pTrigger
->pSchema
==pTab
->pSchema
||
3385 pTrigger
->pSchema
==db
->aDb
[1].pSchema
);
3386 sqlite3DropTriggerPtr(pParse
, pTrigger
);
3387 pTrigger
= pTrigger
->pNext
;
3390 #ifndef SQLITE_OMIT_AUTOINCREMENT
3391 /* Remove any entries of the sqlite_sequence table associated with
3392 ** the table being dropped. This is done before the table is dropped
3393 ** at the btree level, in case the sqlite_sequence table needs to
3394 ** move as a result of the drop (can happen in auto-vacuum mode).
3396 if( pTab
->tabFlags
& TF_Autoincrement
){
3397 sqlite3NestedParse(pParse
,
3398 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3399 pDb
->zDbSName
, pTab
->zName
3404 /* Drop all entries in the schema table that refer to the
3405 ** table. The program name loops through the schema table and deletes
3406 ** every row that refers to a table of the same name as the one being
3407 ** dropped. Triggers are handled separately because a trigger can be
3408 ** created in the temp database that refers to a table in another
3411 sqlite3NestedParse(pParse
,
3412 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3413 " WHERE tbl_name=%Q and type!='trigger'",
3414 pDb
->zDbSName
, pTab
->zName
);
3415 if( !isView
&& !IsVirtual(pTab
) ){
3416 destroyTable(pParse
, pTab
);
3419 /* Remove the table entry from SQLite's internal schema and modify
3420 ** the schema cookie.
3422 if( IsVirtual(pTab
) ){
3423 sqlite3VdbeAddOp4(v
, OP_VDestroy
, iDb
, 0, 0, pTab
->zName
, 0);
3424 sqlite3MayAbort(pParse
);
3426 sqlite3VdbeAddOp4(v
, OP_DropTable
, iDb
, 0, 0, pTab
->zName
, 0);
3427 sqlite3ChangeCookie(pParse
, iDb
);
3428 sqliteViewResetAll(db
, iDb
);
3432 ** Return TRUE if shadow tables should be read-only in the current
3435 int sqlite3ReadOnlyShadowTables(sqlite3
*db
){
3436 #ifndef SQLITE_OMIT_VIRTUALTABLE
3437 if( (db
->flags
& SQLITE_Defensive
)!=0
3440 && !sqlite3VtabInSync(db
)
3449 ** Return true if it is not allowed to drop the given table
3451 static int tableMayNotBeDropped(sqlite3
*db
, Table
*pTab
){
3452 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0 ){
3453 if( sqlite3StrNICmp(pTab
->zName
+7, "stat", 4)==0 ) return 0;
3454 if( sqlite3StrNICmp(pTab
->zName
+7, "parameters", 10)==0 ) return 0;
3457 if( (pTab
->tabFlags
& TF_Shadow
)!=0 && sqlite3ReadOnlyShadowTables(db
) ){
3460 if( pTab
->tabFlags
& TF_Eponymous
){
3467 ** This routine is called to do the work of a DROP TABLE statement.
3468 ** pName is the name of the table to be dropped.
3470 void sqlite3DropTable(Parse
*pParse
, SrcList
*pName
, int isView
, int noErr
){
3473 sqlite3
*db
= pParse
->db
;
3476 if( db
->mallocFailed
){
3477 goto exit_drop_table
;
3479 assert( pParse
->nErr
==0 );
3480 assert( pName
->nSrc
==1 );
3481 if( sqlite3ReadSchema(pParse
) ) goto exit_drop_table
;
3482 if( noErr
) db
->suppressErr
++;
3483 assert( isView
==0 || isView
==LOCATE_VIEW
);
3484 pTab
= sqlite3LocateTableItem(pParse
, isView
, &pName
->a
[0]);
3485 if( noErr
) db
->suppressErr
--;
3489 sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
3490 sqlite3ForceNotReadOnly(pParse
);
3492 goto exit_drop_table
;
3494 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
3495 assert( iDb
>=0 && iDb
<db
->nDb
);
3497 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3498 ** it is initialized.
3500 if( IsVirtual(pTab
) && sqlite3ViewGetColumnNames(pParse
, pTab
) ){
3501 goto exit_drop_table
;
3503 #ifndef SQLITE_OMIT_AUTHORIZATION
3506 const char *zTab
= SCHEMA_TABLE(iDb
);
3507 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
3508 const char *zArg2
= 0;
3509 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
)){
3510 goto exit_drop_table
;
3513 if( !OMIT_TEMPDB
&& iDb
==1 ){
3514 code
= SQLITE_DROP_TEMP_VIEW
;
3516 code
= SQLITE_DROP_VIEW
;
3518 #ifndef SQLITE_OMIT_VIRTUALTABLE
3519 }else if( IsVirtual(pTab
) ){
3520 code
= SQLITE_DROP_VTABLE
;
3521 zArg2
= sqlite3GetVTable(db
, pTab
)->pMod
->zName
;
3524 if( !OMIT_TEMPDB
&& iDb
==1 ){
3525 code
= SQLITE_DROP_TEMP_TABLE
;
3527 code
= SQLITE_DROP_TABLE
;
3530 if( sqlite3AuthCheck(pParse
, code
, pTab
->zName
, zArg2
, zDb
) ){
3531 goto exit_drop_table
;
3533 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, pTab
->zName
, 0, zDb
) ){
3534 goto exit_drop_table
;
3538 if( tableMayNotBeDropped(db
, pTab
) ){
3539 sqlite3ErrorMsg(pParse
, "table %s may not be dropped", pTab
->zName
);
3540 goto exit_drop_table
;
3543 #ifndef SQLITE_OMIT_VIEW
3544 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3547 if( isView
&& !IsView(pTab
) ){
3548 sqlite3ErrorMsg(pParse
, "use DROP TABLE to delete table %s", pTab
->zName
);
3549 goto exit_drop_table
;
3551 if( !isView
&& IsView(pTab
) ){
3552 sqlite3ErrorMsg(pParse
, "use DROP VIEW to delete view %s", pTab
->zName
);
3553 goto exit_drop_table
;
3557 /* Generate code to remove the table from the schema table
3560 v
= sqlite3GetVdbe(pParse
);
3562 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3564 sqlite3ClearStatTables(pParse
, iDb
, "tbl", pTab
->zName
);
3565 sqlite3FkDropTable(pParse
, pName
, pTab
);
3567 sqlite3CodeDropTable(pParse
, pTab
, iDb
, isView
);
3571 sqlite3SrcListDelete(db
, pName
);
3575 ** This routine is called to create a new foreign key on the table
3576 ** currently under construction. pFromCol determines which columns
3577 ** in the current table point to the foreign key. If pFromCol==0 then
3578 ** connect the key to the last column inserted. pTo is the name of
3579 ** the table referred to (a.k.a the "parent" table). pToCol is a list
3580 ** of tables in the parent pTo table. flags contains all
3581 ** information about the conflict resolution algorithms specified
3582 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3584 ** An FKey structure is created and added to the table currently
3585 ** under construction in the pParse->pNewTable field.
3587 ** The foreign key is set for IMMEDIATE processing. A subsequent call
3588 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
3590 void sqlite3CreateForeignKey(
3591 Parse
*pParse
, /* Parsing context */
3592 ExprList
*pFromCol
, /* Columns in this table that point to other table */
3593 Token
*pTo
, /* Name of the other table */
3594 ExprList
*pToCol
, /* Columns in the other table */
3595 int flags
/* Conflict resolution algorithms. */
3597 sqlite3
*db
= pParse
->db
;
3598 #ifndef SQLITE_OMIT_FOREIGN_KEY
3601 Table
*p
= pParse
->pNewTable
;
3608 if( p
==0 || IN_DECLARE_VTAB
) goto fk_end
;
3610 int iCol
= p
->nCol
-1;
3611 if( NEVER(iCol
<0) ) goto fk_end
;
3612 if( pToCol
&& pToCol
->nExpr
!=1 ){
3613 sqlite3ErrorMsg(pParse
, "foreign key on %s"
3614 " should reference only one column of table %T",
3615 p
->aCol
[iCol
].zCnName
, pTo
);
3619 }else if( pToCol
&& pToCol
->nExpr
!=pFromCol
->nExpr
){
3620 sqlite3ErrorMsg(pParse
,
3621 "number of columns in foreign key does not match the number of "
3622 "columns in the referenced table");
3625 nCol
= pFromCol
->nExpr
;
3627 nByte
= sizeof(*pFKey
) + (nCol
-1)*sizeof(pFKey
->aCol
[0]) + pTo
->n
+ 1;
3629 for(i
=0; i
<pToCol
->nExpr
; i
++){
3630 nByte
+= sqlite3Strlen30(pToCol
->a
[i
].zEName
) + 1;
3633 pFKey
= sqlite3DbMallocZero(db
, nByte
);
3638 assert( IsOrdinaryTable(p
) );
3639 pFKey
->pNextFrom
= p
->u
.tab
.pFKey
;
3640 z
= (char*)&pFKey
->aCol
[nCol
];
3642 if( IN_RENAME_OBJECT
){
3643 sqlite3RenameTokenMap(pParse
, (void*)z
, pTo
);
3645 memcpy(z
, pTo
->z
, pTo
->n
);
3651 pFKey
->aCol
[0].iFrom
= p
->nCol
-1;
3653 for(i
=0; i
<nCol
; i
++){
3655 for(j
=0; j
<p
->nCol
; j
++){
3656 if( sqlite3StrICmp(p
->aCol
[j
].zCnName
, pFromCol
->a
[i
].zEName
)==0 ){
3657 pFKey
->aCol
[i
].iFrom
= j
;
3662 sqlite3ErrorMsg(pParse
,
3663 "unknown column \"%s\" in foreign key definition",
3664 pFromCol
->a
[i
].zEName
);
3667 if( IN_RENAME_OBJECT
){
3668 sqlite3RenameTokenRemap(pParse
, &pFKey
->aCol
[i
], pFromCol
->a
[i
].zEName
);
3673 for(i
=0; i
<nCol
; i
++){
3674 int n
= sqlite3Strlen30(pToCol
->a
[i
].zEName
);
3675 pFKey
->aCol
[i
].zCol
= z
;
3676 if( IN_RENAME_OBJECT
){
3677 sqlite3RenameTokenRemap(pParse
, z
, pToCol
->a
[i
].zEName
);
3679 memcpy(z
, pToCol
->a
[i
].zEName
, n
);
3684 pFKey
->isDeferred
= 0;
3685 pFKey
->aAction
[0] = (u8
)(flags
& 0xff); /* ON DELETE action */
3686 pFKey
->aAction
[1] = (u8
)((flags
>> 8 ) & 0xff); /* ON UPDATE action */
3688 assert( sqlite3SchemaMutexHeld(db
, 0, p
->pSchema
) );
3689 pNextTo
= (FKey
*)sqlite3HashInsert(&p
->pSchema
->fkeyHash
,
3690 pFKey
->zTo
, (void *)pFKey
3692 if( pNextTo
==pFKey
){
3693 sqlite3OomFault(db
);
3697 assert( pNextTo
->pPrevTo
==0 );
3698 pFKey
->pNextTo
= pNextTo
;
3699 pNextTo
->pPrevTo
= pFKey
;
3702 /* Link the foreign key to the table as the last step.
3704 assert( IsOrdinaryTable(p
) );
3705 p
->u
.tab
.pFKey
= pFKey
;
3709 sqlite3DbFree(db
, pFKey
);
3710 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3711 sqlite3ExprListDelete(db
, pFromCol
);
3712 sqlite3ExprListDelete(db
, pToCol
);
3716 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3717 ** clause is seen as part of a foreign key definition. The isDeferred
3718 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3719 ** The behavior of the most recently created foreign key is adjusted
3722 void sqlite3DeferForeignKey(Parse
*pParse
, int isDeferred
){
3723 #ifndef SQLITE_OMIT_FOREIGN_KEY
3726 if( (pTab
= pParse
->pNewTable
)==0 ) return;
3727 if( NEVER(!IsOrdinaryTable(pTab
)) ) return;
3728 if( (pFKey
= pTab
->u
.tab
.pFKey
)==0 ) return;
3729 assert( isDeferred
==0 || isDeferred
==1 ); /* EV: R-30323-21917 */
3730 pFKey
->isDeferred
= (u8
)isDeferred
;
3735 ** Generate code that will erase and refill index *pIdx. This is
3736 ** used to initialize a newly created index or to recompute the
3737 ** content of an index in response to a REINDEX command.
3739 ** if memRootPage is not negative, it means that the index is newly
3740 ** created. The register specified by memRootPage contains the
3741 ** root page number of the index. If memRootPage is negative, then
3742 ** the index already exists and must be cleared before being refilled and
3743 ** the root page number of the index is taken from pIndex->tnum.
3745 static void sqlite3RefillIndex(Parse
*pParse
, Index
*pIndex
, int memRootPage
){
3746 Table
*pTab
= pIndex
->pTable
; /* The table that is indexed */
3747 int iTab
= pParse
->nTab
++; /* Btree cursor used for pTab */
3748 int iIdx
= pParse
->nTab
++; /* Btree cursor used for pIndex */
3749 int iSorter
; /* Cursor opened by OpenSorter (if in use) */
3750 int addr1
; /* Address of top of loop */
3751 int addr2
; /* Address to jump to for next iteration */
3752 Pgno tnum
; /* Root page of index */
3753 int iPartIdxLabel
; /* Jump to this label to skip a row */
3754 Vdbe
*v
; /* Generate code into this virtual machine */
3755 KeyInfo
*pKey
; /* KeyInfo for index */
3756 int regRecord
; /* Register holding assembled index record */
3757 sqlite3
*db
= pParse
->db
; /* The database connection */
3758 int iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
3760 #ifndef SQLITE_OMIT_AUTHORIZATION
3761 if( sqlite3AuthCheck(pParse
, SQLITE_REINDEX
, pIndex
->zName
, 0,
3762 db
->aDb
[iDb
].zDbSName
) ){
3767 /* Require a write-lock on the table to perform this operation */
3768 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 1, pTab
->zName
);
3770 v
= sqlite3GetVdbe(pParse
);
3772 if( memRootPage
>=0 ){
3773 tnum
= (Pgno
)memRootPage
;
3775 tnum
= pIndex
->tnum
;
3777 pKey
= sqlite3KeyInfoOfIndex(pParse
, pIndex
);
3778 assert( pKey
!=0 || pParse
->nErr
);
3780 /* Open the sorter cursor if we are to use one. */
3781 iSorter
= pParse
->nTab
++;
3782 sqlite3VdbeAddOp4(v
, OP_SorterOpen
, iSorter
, 0, pIndex
->nKeyCol
, (char*)
3783 sqlite3KeyInfoRef(pKey
), P4_KEYINFO
);
3785 /* Open the table. Loop through all rows of the table, inserting index
3786 ** records into the sorter. */
3787 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
3788 addr1
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, 0); VdbeCoverage(v
);
3789 regRecord
= sqlite3GetTempReg(pParse
);
3790 sqlite3MultiWrite(pParse
);
3792 sqlite3GenerateIndexKey(pParse
,pIndex
,iTab
,regRecord
,0,&iPartIdxLabel
,0,0);
3793 sqlite3VdbeAddOp2(v
, OP_SorterInsert
, iSorter
, regRecord
);
3794 sqlite3ResolvePartIdxLabel(pParse
, iPartIdxLabel
);
3795 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addr1
+1); VdbeCoverage(v
);
3796 sqlite3VdbeJumpHere(v
, addr1
);
3797 if( memRootPage
<0 ) sqlite3VdbeAddOp2(v
, OP_Clear
, tnum
, iDb
);
3798 sqlite3VdbeAddOp4(v
, OP_OpenWrite
, iIdx
, (int)tnum
, iDb
,
3799 (char *)pKey
, P4_KEYINFO
);
3800 sqlite3VdbeChangeP5(v
, OPFLAG_BULKCSR
|((memRootPage
>=0)?OPFLAG_P2ISREG
:0));
3802 addr1
= sqlite3VdbeAddOp2(v
, OP_SorterSort
, iSorter
, 0); VdbeCoverage(v
);
3803 if( IsUniqueIndex(pIndex
) ){
3804 int j2
= sqlite3VdbeGoto(v
, 1);
3805 addr2
= sqlite3VdbeCurrentAddr(v
);
3806 sqlite3VdbeVerifyAbortable(v
, OE_Abort
);
3807 sqlite3VdbeAddOp4Int(v
, OP_SorterCompare
, iSorter
, j2
, regRecord
,
3808 pIndex
->nKeyCol
); VdbeCoverage(v
);
3809 sqlite3UniqueConstraint(pParse
, OE_Abort
, pIndex
);
3810 sqlite3VdbeJumpHere(v
, j2
);
3812 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3813 ** abort. The exception is if one of the indexed expressions contains a
3814 ** user function that throws an exception when it is evaluated. But the
3815 ** overhead of adding a statement journal to a CREATE INDEX statement is
3816 ** very small (since most of the pages written do not contain content that
3817 ** needs to be restored if the statement aborts), so we call
3818 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3819 sqlite3MayAbort(pParse
);
3820 addr2
= sqlite3VdbeCurrentAddr(v
);
3822 sqlite3VdbeAddOp3(v
, OP_SorterData
, iSorter
, regRecord
, iIdx
);
3823 if( !pIndex
->bAscKeyBug
){
3824 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3825 ** faster by avoiding unnecessary seeks. But the optimization does
3826 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3827 ** with DESC primary keys, since those indexes have there keys in
3828 ** a different order from the main table.
3829 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
3831 sqlite3VdbeAddOp1(v
, OP_SeekEnd
, iIdx
);
3833 sqlite3VdbeAddOp2(v
, OP_IdxInsert
, iIdx
, regRecord
);
3834 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
3835 sqlite3ReleaseTempReg(pParse
, regRecord
);
3836 sqlite3VdbeAddOp2(v
, OP_SorterNext
, iSorter
, addr2
); VdbeCoverage(v
);
3837 sqlite3VdbeJumpHere(v
, addr1
);
3839 sqlite3VdbeAddOp1(v
, OP_Close
, iTab
);
3840 sqlite3VdbeAddOp1(v
, OP_Close
, iIdx
);
3841 sqlite3VdbeAddOp1(v
, OP_Close
, iSorter
);
3845 ** Allocate heap space to hold an Index object with nCol columns.
3847 ** Increase the allocation size to provide an extra nExtra bytes
3848 ** of 8-byte aligned space after the Index object and return a
3849 ** pointer to this extra space in *ppExtra.
3851 Index
*sqlite3AllocateIndexObject(
3852 sqlite3
*db
, /* Database connection */
3853 i16 nCol
, /* Total number of columns in the index */
3854 int nExtra
, /* Number of bytes of extra space to alloc */
3855 char **ppExtra
/* Pointer to the "extra" space */
3857 Index
*p
; /* Allocated index object */
3858 int nByte
; /* Bytes of space for Index object + arrays */
3860 nByte
= ROUND8(sizeof(Index
)) + /* Index structure */
3861 ROUND8(sizeof(char*)*nCol
) + /* Index.azColl */
3862 ROUND8(sizeof(LogEst
)*(nCol
+1) + /* Index.aiRowLogEst */
3863 sizeof(i16
)*nCol
+ /* Index.aiColumn */
3864 sizeof(u8
)*nCol
); /* Index.aSortOrder */
3865 p
= sqlite3DbMallocZero(db
, nByte
+ nExtra
);
3867 char *pExtra
= ((char*)p
)+ROUND8(sizeof(Index
));
3868 p
->azColl
= (const char**)pExtra
; pExtra
+= ROUND8(sizeof(char*)*nCol
);
3869 p
->aiRowLogEst
= (LogEst
*)pExtra
; pExtra
+= sizeof(LogEst
)*(nCol
+1);
3870 p
->aiColumn
= (i16
*)pExtra
; pExtra
+= sizeof(i16
)*nCol
;
3871 p
->aSortOrder
= (u8
*)pExtra
;
3873 p
->nKeyCol
= nCol
- 1;
3874 *ppExtra
= ((char*)p
) + nByte
;
3880 ** If expression list pList contains an expression that was parsed with
3881 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
3882 ** pParse and return non-zero. Otherwise, return zero.
3884 int sqlite3HasExplicitNulls(Parse
*pParse
, ExprList
*pList
){
3887 for(i
=0; i
<pList
->nExpr
; i
++){
3888 if( pList
->a
[i
].fg
.bNulls
){
3889 u8 sf
= pList
->a
[i
].fg
.sortFlags
;
3890 sqlite3ErrorMsg(pParse
, "unsupported use of NULLS %s",
3891 (sf
==0 || sf
==3) ? "FIRST" : "LAST"
3901 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
3902 ** and pTblList is the name of the table that is to be indexed. Both will
3903 ** be NULL for a primary key or an index that is created to satisfy a
3904 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
3905 ** as the table to be indexed. pParse->pNewTable is a table that is
3906 ** currently being constructed by a CREATE TABLE statement.
3908 ** pList is a list of columns to be indexed. pList will be NULL if this
3909 ** is a primary key or unique-constraint on the most recent column added
3910 ** to the table currently under construction.
3912 void sqlite3CreateIndex(
3913 Parse
*pParse
, /* All information about this parse */
3914 Token
*pName1
, /* First part of index name. May be NULL */
3915 Token
*pName2
, /* Second part of index name. May be NULL */
3916 SrcList
*pTblName
, /* Table to index. Use pParse->pNewTable if 0 */
3917 ExprList
*pList
, /* A list of columns to be indexed */
3918 int onError
, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
3919 Token
*pStart
, /* The CREATE token that begins this statement */
3920 Expr
*pPIWhere
, /* WHERE clause for partial indices */
3921 int sortOrder
, /* Sort order of primary key when pList==NULL */
3922 int ifNotExist
, /* Omit error if index already exists */
3923 u8 idxType
/* The index type */
3925 Table
*pTab
= 0; /* Table to be indexed */
3926 Index
*pIndex
= 0; /* The index to be created */
3927 char *zName
= 0; /* Name of the index */
3928 int nName
; /* Number of characters in zName */
3930 DbFixer sFix
; /* For assigning database names to pTable */
3931 int sortOrderMask
; /* 1 to honor DESC in index. 0 to ignore. */
3932 sqlite3
*db
= pParse
->db
;
3933 Db
*pDb
; /* The specific table containing the indexed database */
3934 int iDb
; /* Index of the database that is being written */
3935 Token
*pName
= 0; /* Unqualified name of the index to create */
3936 struct ExprList_item
*pListItem
; /* For looping over pList */
3937 int nExtra
= 0; /* Space allocated for zExtra[] */
3938 int nExtraCol
; /* Number of extra columns needed */
3939 char *zExtra
= 0; /* Extra space after the Index object */
3940 Index
*pPk
= 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
3942 assert( db
->pParse
==pParse
);
3944 goto exit_create_index
;
3946 assert( db
->mallocFailed
==0 );
3947 if( IN_DECLARE_VTAB
&& idxType
!=SQLITE_IDXTYPE_PRIMARYKEY
){
3948 goto exit_create_index
;
3950 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
3951 goto exit_create_index
;
3953 if( sqlite3HasExplicitNulls(pParse
, pList
) ){
3954 goto exit_create_index
;
3958 ** Find the table that is to be indexed. Return early if not found.
3962 /* Use the two-part index name to determine the database
3963 ** to search for the table. 'Fix' the table name to this db
3964 ** before looking up the table.
3966 assert( pName1
&& pName2
);
3967 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
3968 if( iDb
<0 ) goto exit_create_index
;
3969 assert( pName
&& pName
->z
);
3971 #ifndef SQLITE_OMIT_TEMPDB
3972 /* If the index name was unqualified, check if the table
3973 ** is a temp table. If so, set the database to 1. Do not do this
3974 ** if initialising a database schema.
3976 if( !db
->init
.busy
){
3977 pTab
= sqlite3SrcListLookup(pParse
, pTblName
);
3978 if( pName2
->n
==0 && pTab
&& pTab
->pSchema
==db
->aDb
[1].pSchema
){
3984 sqlite3FixInit(&sFix
, pParse
, iDb
, "index", pName
);
3985 if( sqlite3FixSrcList(&sFix
, pTblName
) ){
3986 /* Because the parser constructs pTblName from a single identifier,
3987 ** sqlite3FixSrcList can never fail. */
3990 pTab
= sqlite3LocateTableItem(pParse
, 0, &pTblName
->a
[0]);
3991 assert( db
->mallocFailed
==0 || pTab
==0 );
3992 if( pTab
==0 ) goto exit_create_index
;
3993 if( iDb
==1 && db
->aDb
[iDb
].pSchema
!=pTab
->pSchema
){
3994 sqlite3ErrorMsg(pParse
,
3995 "cannot create a TEMP index on non-TEMP table \"%s\"",
3997 goto exit_create_index
;
3999 if( !HasRowid(pTab
) ) pPk
= sqlite3PrimaryKeyIndex(pTab
);
4002 assert( pStart
==0 );
4003 pTab
= pParse
->pNewTable
;
4004 if( !pTab
) goto exit_create_index
;
4005 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
4007 pDb
= &db
->aDb
[iDb
];
4010 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0
4013 #if SQLITE_USER_AUTHENTICATION
4014 && sqlite3UserAuthTable(pTab
->zName
)==0
4017 sqlite3ErrorMsg(pParse
, "table %s may not be indexed", pTab
->zName
);
4018 goto exit_create_index
;
4020 #ifndef SQLITE_OMIT_VIEW
4022 sqlite3ErrorMsg(pParse
, "views may not be indexed");
4023 goto exit_create_index
;
4026 #ifndef SQLITE_OMIT_VIRTUALTABLE
4027 if( IsVirtual(pTab
) ){
4028 sqlite3ErrorMsg(pParse
, "virtual tables may not be indexed");
4029 goto exit_create_index
;
4034 ** Find the name of the index. Make sure there is not already another
4035 ** index or table with the same name.
4037 ** Exception: If we are reading the names of permanent indices from the
4038 ** sqlite_schema table (because some other process changed the schema) and
4039 ** one of the index names collides with the name of a temporary table or
4040 ** index, then we will continue to process this index.
4042 ** If pName==0 it means that we are
4043 ** dealing with a primary key or UNIQUE constraint. We have to invent our
4047 zName
= sqlite3NameFromToken(db
, pName
);
4048 if( zName
==0 ) goto exit_create_index
;
4049 assert( pName
->z
!=0 );
4050 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
,"index",pTab
->zName
) ){
4051 goto exit_create_index
;
4053 if( !IN_RENAME_OBJECT
){
4054 if( !db
->init
.busy
){
4055 if( sqlite3FindTable(db
, zName
, pDb
->zDbSName
)!=0 ){
4056 sqlite3ErrorMsg(pParse
, "there is already a table named %s", zName
);
4057 goto exit_create_index
;
4060 if( sqlite3FindIndex(db
, zName
, pDb
->zDbSName
)!=0 ){
4062 sqlite3ErrorMsg(pParse
, "index %s already exists", zName
);
4064 assert( !db
->init
.busy
);
4065 sqlite3CodeVerifySchema(pParse
, iDb
);
4066 sqlite3ForceNotReadOnly(pParse
);
4068 goto exit_create_index
;
4074 for(pLoop
=pTab
->pIndex
, n
=1; pLoop
; pLoop
=pLoop
->pNext
, n
++){}
4075 zName
= sqlite3MPrintf(db
, "sqlite_autoindex_%s_%d", pTab
->zName
, n
);
4077 goto exit_create_index
;
4080 /* Automatic index names generated from within sqlite3_declare_vtab()
4081 ** must have names that are distinct from normal automatic index names.
4082 ** The following statement converts "sqlite3_autoindex..." into
4083 ** "sqlite3_butoindex..." in order to make the names distinct.
4084 ** The "vtab_err.test" test demonstrates the need of this statement. */
4085 if( IN_SPECIAL_PARSE
) zName
[7]++;
4088 /* Check for authorization to create an index.
4090 #ifndef SQLITE_OMIT_AUTHORIZATION
4091 if( !IN_RENAME_OBJECT
){
4092 const char *zDb
= pDb
->zDbSName
;
4093 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(iDb
), 0, zDb
) ){
4094 goto exit_create_index
;
4096 i
= SQLITE_CREATE_INDEX
;
4097 if( !OMIT_TEMPDB
&& iDb
==1 ) i
= SQLITE_CREATE_TEMP_INDEX
;
4098 if( sqlite3AuthCheck(pParse
, i
, zName
, pTab
->zName
, zDb
) ){
4099 goto exit_create_index
;
4104 /* If pList==0, it means this routine was called to make a primary
4105 ** key out of the last column added to the table under construction.
4106 ** So create a fake list to simulate this.
4110 Column
*pCol
= &pTab
->aCol
[pTab
->nCol
-1];
4111 pCol
->colFlags
|= COLFLAG_UNIQUE
;
4112 sqlite3TokenInit(&prevCol
, pCol
->zCnName
);
4113 pList
= sqlite3ExprListAppend(pParse
, 0,
4114 sqlite3ExprAlloc(db
, TK_ID
, &prevCol
, 0));
4115 if( pList
==0 ) goto exit_create_index
;
4116 assert( pList
->nExpr
==1 );
4117 sqlite3ExprListSetSortOrder(pList
, sortOrder
, SQLITE_SO_UNDEFINED
);
4119 sqlite3ExprListCheckLength(pParse
, pList
, "index");
4120 if( pParse
->nErr
) goto exit_create_index
;
4123 /* Figure out how many bytes of space are required to store explicitly
4124 ** specified collation sequence names.
4126 for(i
=0; i
<pList
->nExpr
; i
++){
4127 Expr
*pExpr
= pList
->a
[i
].pExpr
;
4129 if( pExpr
->op
==TK_COLLATE
){
4130 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4131 nExtra
+= (1 + sqlite3Strlen30(pExpr
->u
.zToken
));
4136 ** Allocate the index structure.
4138 nName
= sqlite3Strlen30(zName
);
4139 nExtraCol
= pPk
? pPk
->nKeyCol
: 1;
4140 assert( pList
->nExpr
+ nExtraCol
<= 32767 /* Fits in i16 */ );
4141 pIndex
= sqlite3AllocateIndexObject(db
, pList
->nExpr
+ nExtraCol
,
4142 nName
+ nExtra
+ 1, &zExtra
);
4143 if( db
->mallocFailed
){
4144 goto exit_create_index
;
4146 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->aiRowLogEst
) );
4147 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->azColl
) );
4148 pIndex
->zName
= zExtra
;
4149 zExtra
+= nName
+ 1;
4150 memcpy(pIndex
->zName
, zName
, nName
+1);
4151 pIndex
->pTable
= pTab
;
4152 pIndex
->onError
= (u8
)onError
;
4153 pIndex
->uniqNotNull
= onError
!=OE_None
;
4154 pIndex
->idxType
= idxType
;
4155 pIndex
->pSchema
= db
->aDb
[iDb
].pSchema
;
4156 pIndex
->nKeyCol
= pList
->nExpr
;
4158 sqlite3ResolveSelfReference(pParse
, pTab
, NC_PartIdx
, pPIWhere
, 0);
4159 pIndex
->pPartIdxWhere
= pPIWhere
;
4162 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
4164 /* Check to see if we should honor DESC requests on index columns
4166 if( pDb
->pSchema
->file_format
>=4 ){
4167 sortOrderMask
= -1; /* Honor DESC */
4169 sortOrderMask
= 0; /* Ignore DESC */
4172 /* Analyze the list of expressions that form the terms of the index and
4173 ** report any errors. In the common case where the expression is exactly
4174 ** a table column, store that column in aiColumn[]. For general expressions,
4175 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4177 ** TODO: Issue a warning if two or more columns of the index are identical.
4178 ** TODO: Issue a warning if the table primary key is used as part of the
4181 pListItem
= pList
->a
;
4182 if( IN_RENAME_OBJECT
){
4183 pIndex
->aColExpr
= pList
;
4186 for(i
=0; i
<pIndex
->nKeyCol
; i
++, pListItem
++){
4187 Expr
*pCExpr
; /* The i-th index expression */
4188 int requestedSortOrder
; /* ASC or DESC on the i-th expression */
4189 const char *zColl
; /* Collation sequence name */
4191 sqlite3StringToId(pListItem
->pExpr
);
4192 sqlite3ResolveSelfReference(pParse
, pTab
, NC_IdxExpr
, pListItem
->pExpr
, 0);
4193 if( pParse
->nErr
) goto exit_create_index
;
4194 pCExpr
= sqlite3ExprSkipCollate(pListItem
->pExpr
);
4195 if( pCExpr
->op
!=TK_COLUMN
){
4196 if( pTab
==pParse
->pNewTable
){
4197 sqlite3ErrorMsg(pParse
, "expressions prohibited in PRIMARY KEY and "
4198 "UNIQUE constraints");
4199 goto exit_create_index
;
4201 if( pIndex
->aColExpr
==0 ){
4202 pIndex
->aColExpr
= pList
;
4206 pIndex
->aiColumn
[i
] = XN_EXPR
;
4207 pIndex
->uniqNotNull
= 0;
4208 pIndex
->bHasExpr
= 1;
4210 j
= pCExpr
->iColumn
;
4211 assert( j
<=0x7fff );
4215 if( pTab
->aCol
[j
].notNull
==0 ){
4216 pIndex
->uniqNotNull
= 0;
4218 if( pTab
->aCol
[j
].colFlags
& COLFLAG_VIRTUAL
){
4219 pIndex
->bHasVCol
= 1;
4220 pIndex
->bHasExpr
= 1;
4223 pIndex
->aiColumn
[i
] = (i16
)j
;
4226 if( pListItem
->pExpr
->op
==TK_COLLATE
){
4228 assert( !ExprHasProperty(pListItem
->pExpr
, EP_IntValue
) );
4229 zColl
= pListItem
->pExpr
->u
.zToken
;
4230 nColl
= sqlite3Strlen30(zColl
) + 1;
4231 assert( nExtra
>=nColl
);
4232 memcpy(zExtra
, zColl
, nColl
);
4237 zColl
= sqlite3ColumnColl(&pTab
->aCol
[j
]);
4239 if( !zColl
) zColl
= sqlite3StrBINARY
;
4240 if( !db
->init
.busy
&& !sqlite3LocateCollSeq(pParse
, zColl
) ){
4241 goto exit_create_index
;
4243 pIndex
->azColl
[i
] = zColl
;
4244 requestedSortOrder
= pListItem
->fg
.sortFlags
& sortOrderMask
;
4245 pIndex
->aSortOrder
[i
] = (u8
)requestedSortOrder
;
4248 /* Append the table key to the end of the index. For WITHOUT ROWID
4249 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
4250 ** normal tables (when pPk==0) this will be the rowid.
4253 for(j
=0; j
<pPk
->nKeyCol
; j
++){
4254 int x
= pPk
->aiColumn
[j
];
4256 if( isDupColumn(pIndex
, pIndex
->nKeyCol
, pPk
, j
) ){
4259 testcase( hasColumn(pIndex
->aiColumn
,pIndex
->nKeyCol
,x
) );
4260 pIndex
->aiColumn
[i
] = x
;
4261 pIndex
->azColl
[i
] = pPk
->azColl
[j
];
4262 pIndex
->aSortOrder
[i
] = pPk
->aSortOrder
[j
];
4266 assert( i
==pIndex
->nColumn
);
4268 pIndex
->aiColumn
[i
] = XN_ROWID
;
4269 pIndex
->azColl
[i
] = sqlite3StrBINARY
;
4271 sqlite3DefaultRowEst(pIndex
);
4272 if( pParse
->pNewTable
==0 ) estimateIndexWidth(pIndex
);
4274 /* If this index contains every column of its table, then mark
4275 ** it as a covering index */
4276 assert( HasRowid(pTab
)
4277 || pTab
->iPKey
<0 || sqlite3TableColumnToIndex(pIndex
, pTab
->iPKey
)>=0 );
4278 recomputeColumnsNotIndexed(pIndex
);
4279 if( pTblName
!=0 && pIndex
->nColumn
>=pTab
->nCol
){
4280 pIndex
->isCovering
= 1;
4281 for(j
=0; j
<pTab
->nCol
; j
++){
4282 if( j
==pTab
->iPKey
) continue;
4283 if( sqlite3TableColumnToIndex(pIndex
,j
)>=0 ) continue;
4284 pIndex
->isCovering
= 0;
4289 if( pTab
==pParse
->pNewTable
){
4290 /* This routine has been called to create an automatic index as a
4291 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4292 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4295 ** CREATE TABLE t(x PRIMARY KEY, y);
4296 ** CREATE TABLE t(x, y, UNIQUE(x, y));
4298 ** Either way, check to see if the table already has such an index. If
4299 ** so, don't bother creating this one. This only applies to
4300 ** automatically created indices. Users can do as they wish with
4301 ** explicit indices.
4303 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4304 ** (and thus suppressing the second one) even if they have different
4307 ** If there are different collating sequences or if the columns of
4308 ** the constraint occur in different orders, then the constraints are
4309 ** considered distinct and both result in separate indices.
4312 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
4314 assert( IsUniqueIndex(pIdx
) );
4315 assert( pIdx
->idxType
!=SQLITE_IDXTYPE_APPDEF
);
4316 assert( IsUniqueIndex(pIndex
) );
4318 if( pIdx
->nKeyCol
!=pIndex
->nKeyCol
) continue;
4319 for(k
=0; k
<pIdx
->nKeyCol
; k
++){
4322 assert( pIdx
->aiColumn
[k
]>=0 );
4323 if( pIdx
->aiColumn
[k
]!=pIndex
->aiColumn
[k
] ) break;
4324 z1
= pIdx
->azColl
[k
];
4325 z2
= pIndex
->azColl
[k
];
4326 if( sqlite3StrICmp(z1
, z2
) ) break;
4328 if( k
==pIdx
->nKeyCol
){
4329 if( pIdx
->onError
!=pIndex
->onError
){
4330 /* This constraint creates the same index as a previous
4331 ** constraint specified somewhere in the CREATE TABLE statement.
4332 ** However the ON CONFLICT clauses are different. If both this
4333 ** constraint and the previous equivalent constraint have explicit
4334 ** ON CONFLICT clauses this is an error. Otherwise, use the
4335 ** explicitly specified behavior for the index.
4337 if( !(pIdx
->onError
==OE_Default
|| pIndex
->onError
==OE_Default
) ){
4338 sqlite3ErrorMsg(pParse
,
4339 "conflicting ON CONFLICT clauses specified", 0);
4341 if( pIdx
->onError
==OE_Default
){
4342 pIdx
->onError
= pIndex
->onError
;
4345 if( idxType
==SQLITE_IDXTYPE_PRIMARYKEY
) pIdx
->idxType
= idxType
;
4346 if( IN_RENAME_OBJECT
){
4347 pIndex
->pNext
= pParse
->pNewIndex
;
4348 pParse
->pNewIndex
= pIndex
;
4351 goto exit_create_index
;
4356 if( !IN_RENAME_OBJECT
){
4358 /* Link the new Index structure to its table and to the other
4359 ** in-memory database structures.
4361 assert( pParse
->nErr
==0 );
4362 if( db
->init
.busy
){
4364 assert( !IN_SPECIAL_PARSE
);
4365 assert( sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
4367 pIndex
->tnum
= db
->init
.newTnum
;
4368 if( sqlite3IndexHasDuplicateRootPage(pIndex
) ){
4369 sqlite3ErrorMsg(pParse
, "invalid rootpage");
4370 pParse
->rc
= SQLITE_CORRUPT_BKPT
;
4371 goto exit_create_index
;
4374 p
= sqlite3HashInsert(&pIndex
->pSchema
->idxHash
,
4375 pIndex
->zName
, pIndex
);
4377 assert( p
==pIndex
); /* Malloc must have failed */
4378 sqlite3OomFault(db
);
4379 goto exit_create_index
;
4381 db
->mDbFlags
|= DBFLAG_SchemaChange
;
4384 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4385 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4386 ** emit code to allocate the index rootpage on disk and make an entry for
4387 ** the index in the sqlite_schema table and populate the index with
4388 ** content. But, do not do this if we are simply reading the sqlite_schema
4389 ** table to parse the schema, or if this index is the PRIMARY KEY index
4390 ** of a WITHOUT ROWID table.
4392 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4393 ** or UNIQUE index in a CREATE TABLE statement. Since the table
4394 ** has just been created, it contains no data and the index initialization
4395 ** step can be skipped.
4397 else if( HasRowid(pTab
) || pTblName
!=0 ){
4400 int iMem
= ++pParse
->nMem
;
4402 v
= sqlite3GetVdbe(pParse
);
4403 if( v
==0 ) goto exit_create_index
;
4405 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
4407 /* Create the rootpage for the index using CreateIndex. But before
4408 ** doing so, code a Noop instruction and store its address in
4409 ** Index.tnum. This is required in case this index is actually a
4410 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4411 ** that case the convertToWithoutRowidTable() routine will replace
4412 ** the Noop with a Goto to jump over the VDBE code generated below. */
4413 pIndex
->tnum
= (Pgno
)sqlite3VdbeAddOp0(v
, OP_Noop
);
4414 sqlite3VdbeAddOp3(v
, OP_CreateBtree
, iDb
, iMem
, BTREE_BLOBKEY
);
4416 /* Gather the complete text of the CREATE INDEX statement into
4417 ** the zStmt variable
4419 assert( pName
!=0 || pStart
==0 );
4421 int n
= (int)(pParse
->sLastToken
.z
- pName
->z
) + pParse
->sLastToken
.n
;
4422 if( pName
->z
[n
-1]==';' ) n
--;
4423 /* A named index with an explicit CREATE INDEX statement */
4424 zStmt
= sqlite3MPrintf(db
, "CREATE%s INDEX %.*s",
4425 onError
==OE_None
? "" : " UNIQUE", n
, pName
->z
);
4427 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4428 /* zStmt = sqlite3MPrintf(""); */
4432 /* Add an entry in sqlite_schema for this index
4434 sqlite3NestedParse(pParse
,
4435 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
" VALUES('index',%Q,%Q,#%d,%Q);",
4436 db
->aDb
[iDb
].zDbSName
,
4442 sqlite3DbFree(db
, zStmt
);
4444 /* Fill the index with data and reparse the schema. Code an OP_Expire
4445 ** to invalidate all pre-compiled statements.
4448 sqlite3RefillIndex(pParse
, pIndex
, iMem
);
4449 sqlite3ChangeCookie(pParse
, iDb
);
4450 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
4451 sqlite3MPrintf(db
, "name='%q' AND type='index'", pIndex
->zName
), 0);
4452 sqlite3VdbeAddOp2(v
, OP_Expire
, 0, 1);
4455 sqlite3VdbeJumpHere(v
, (int)pIndex
->tnum
);
4458 if( db
->init
.busy
|| pTblName
==0 ){
4459 pIndex
->pNext
= pTab
->pIndex
;
4460 pTab
->pIndex
= pIndex
;
4463 else if( IN_RENAME_OBJECT
){
4464 assert( pParse
->pNewIndex
==0 );
4465 pParse
->pNewIndex
= pIndex
;
4469 /* Clean up before exiting */
4471 if( pIndex
) sqlite3FreeIndex(db
, pIndex
);
4473 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
4474 ** The list was already ordered when this routine was entered, so at this
4475 ** point at most a single index (the newly added index) will be out of
4476 ** order. So we have to reorder at most one index. */
4479 for(ppFrom
=&pTab
->pIndex
; (pThis
= *ppFrom
)!=0; ppFrom
=&pThis
->pNext
){
4481 if( pThis
->onError
!=OE_Replace
) continue;
4482 while( (pNext
= pThis
->pNext
)!=0 && pNext
->onError
!=OE_Replace
){
4484 pThis
->pNext
= pNext
->pNext
;
4485 pNext
->pNext
= pThis
;
4486 ppFrom
= &pNext
->pNext
;
4491 /* Verify that all REPLACE indexes really are now at the end
4492 ** of the index list. In other words, no other index type ever
4493 ** comes after a REPLACE index on the list. */
4494 for(pThis
= pTab
->pIndex
; pThis
; pThis
=pThis
->pNext
){
4495 assert( pThis
->onError
!=OE_Replace
4497 || pThis
->pNext
->onError
==OE_Replace
);
4501 sqlite3ExprDelete(db
, pPIWhere
);
4502 sqlite3ExprListDelete(db
, pList
);
4503 sqlite3SrcListDelete(db
, pTblName
);
4504 sqlite3DbFree(db
, zName
);
4508 ** Fill the Index.aiRowEst[] array with default information - information
4509 ** to be used when we have not run the ANALYZE command.
4511 ** aiRowEst[0] is supposed to contain the number of elements in the index.
4512 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
4513 ** number of rows in the table that match any particular value of the
4514 ** first column of the index. aiRowEst[2] is an estimate of the number
4515 ** of rows that match any particular combination of the first 2 columns
4516 ** of the index. And so forth. It must always be the case that
4518 ** aiRowEst[N]<=aiRowEst[N-1]
4521 ** Apart from that, we have little to go on besides intuition as to
4522 ** how aiRowEst[] should be initialized. The numbers generated here
4523 ** are based on typical values found in actual indices.
4525 void sqlite3DefaultRowEst(Index
*pIdx
){
4526 /* 10, 9, 8, 7, 6 */
4527 static const LogEst aVal
[] = { 33, 32, 30, 28, 26 };
4528 LogEst
*a
= pIdx
->aiRowLogEst
;
4530 int nCopy
= MIN(ArraySize(aVal
), pIdx
->nKeyCol
);
4533 /* Indexes with default row estimates should not have stat1 data */
4534 assert( !pIdx
->hasStat1
);
4536 /* Set the first entry (number of rows in the index) to the estimated
4537 ** number of rows in the table, or half the number of rows in the table
4538 ** for a partial index.
4540 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
4541 ** table but other parts we are having to guess at, then do not let the
4542 ** estimated number of rows in the table be less than 1000 (LogEst 99).
4543 ** Failure to do this can cause the indexes for which we do not have
4544 ** stat1 data to be ignored by the query planner.
4546 x
= pIdx
->pTable
->nRowLogEst
;
4547 assert( 99==sqlite3LogEst(1000) );
4549 pIdx
->pTable
->nRowLogEst
= x
= 99;
4551 if( pIdx
->pPartIdxWhere
!=0 ){ x
-= 10; assert( 10==sqlite3LogEst(2) ); }
4554 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4555 ** 6 and each subsequent value (if any) is 5. */
4556 memcpy(&a
[1], aVal
, nCopy
*sizeof(LogEst
));
4557 for(i
=nCopy
+1; i
<=pIdx
->nKeyCol
; i
++){
4558 a
[i
] = 23; assert( 23==sqlite3LogEst(5) );
4561 assert( 0==sqlite3LogEst(1) );
4562 if( IsUniqueIndex(pIdx
) ) a
[pIdx
->nKeyCol
] = 0;
4566 ** This routine will drop an existing named index. This routine
4567 ** implements the DROP INDEX statement.
4569 void sqlite3DropIndex(Parse
*pParse
, SrcList
*pName
, int ifExists
){
4572 sqlite3
*db
= pParse
->db
;
4575 if( db
->mallocFailed
){
4576 goto exit_drop_index
;
4578 assert( pParse
->nErr
==0 ); /* Never called with prior non-OOM errors */
4579 assert( pName
->nSrc
==1 );
4580 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
4581 goto exit_drop_index
;
4583 pIndex
= sqlite3FindIndex(db
, pName
->a
[0].zName
, pName
->a
[0].zDatabase
);
4586 sqlite3ErrorMsg(pParse
, "no such index: %S", pName
->a
);
4588 sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
4589 sqlite3ForceNotReadOnly(pParse
);
4591 pParse
->checkSchema
= 1;
4592 goto exit_drop_index
;
4594 if( pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
){
4595 sqlite3ErrorMsg(pParse
, "index associated with UNIQUE "
4596 "or PRIMARY KEY constraint cannot be dropped", 0);
4597 goto exit_drop_index
;
4599 iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
4600 #ifndef SQLITE_OMIT_AUTHORIZATION
4602 int code
= SQLITE_DROP_INDEX
;
4603 Table
*pTab
= pIndex
->pTable
;
4604 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
4605 const char *zTab
= SCHEMA_TABLE(iDb
);
4606 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
) ){
4607 goto exit_drop_index
;
4609 if( !OMIT_TEMPDB
&& iDb
==1 ) code
= SQLITE_DROP_TEMP_INDEX
;
4610 if( sqlite3AuthCheck(pParse
, code
, pIndex
->zName
, pTab
->zName
, zDb
) ){
4611 goto exit_drop_index
;
4616 /* Generate code to remove the index and from the schema table */
4617 v
= sqlite3GetVdbe(pParse
);
4619 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
4620 sqlite3NestedParse(pParse
,
4621 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
" WHERE name=%Q AND type='index'",
4622 db
->aDb
[iDb
].zDbSName
, pIndex
->zName
4624 sqlite3ClearStatTables(pParse
, iDb
, "idx", pIndex
->zName
);
4625 sqlite3ChangeCookie(pParse
, iDb
);
4626 destroyRootPage(pParse
, pIndex
->tnum
, iDb
);
4627 sqlite3VdbeAddOp4(v
, OP_DropIndex
, iDb
, 0, 0, pIndex
->zName
, 0);
4631 sqlite3SrcListDelete(db
, pName
);
4635 ** pArray is a pointer to an array of objects. Each object in the
4636 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4637 ** to extend the array so that there is space for a new object at the end.
4639 ** When this function is called, *pnEntry contains the current size of
4640 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4643 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
4644 ** space allocated for the new object is zeroed, *pnEntry updated to
4645 ** reflect the new size of the array and a pointer to the new allocation
4646 ** returned. *pIdx is set to the index of the new array entry in this case.
4648 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4649 ** unchanged and a copy of pArray returned.
4651 void *sqlite3ArrayAllocate(
4652 sqlite3
*db
, /* Connection to notify of malloc failures */
4653 void *pArray
, /* Array of objects. Might be reallocated */
4654 int szEntry
, /* Size of each object in the array */
4655 int *pnEntry
, /* Number of objects currently in use */
4656 int *pIdx
/* Write the index of a new slot here */
4659 sqlite3_int64 n
= *pIdx
= *pnEntry
;
4660 if( (n
& (n
-1))==0 ){
4661 sqlite3_int64 sz
= (n
==0) ? 1 : 2*n
;
4662 void *pNew
= sqlite3DbRealloc(db
, pArray
, sz
*szEntry
);
4670 memset(&z
[n
* szEntry
], 0, szEntry
);
4676 ** Append a new element to the given IdList. Create a new IdList if
4679 ** A new IdList is returned, or NULL if malloc() fails.
4681 IdList
*sqlite3IdListAppend(Parse
*pParse
, IdList
*pList
, Token
*pToken
){
4682 sqlite3
*db
= pParse
->db
;
4685 pList
= sqlite3DbMallocZero(db
, sizeof(IdList
) );
4686 if( pList
==0 ) return 0;
4689 pNew
= sqlite3DbRealloc(db
, pList
,
4690 sizeof(IdList
) + pList
->nId
*sizeof(pList
->a
));
4692 sqlite3IdListDelete(db
, pList
);
4698 pList
->a
[i
].zName
= sqlite3NameFromToken(db
, pToken
);
4699 if( IN_RENAME_OBJECT
&& pList
->a
[i
].zName
){
4700 sqlite3RenameTokenMap(pParse
, (void*)pList
->a
[i
].zName
, pToken
);
4706 ** Delete an IdList.
4708 void sqlite3IdListDelete(sqlite3
*db
, IdList
*pList
){
4711 if( pList
==0 ) return;
4712 assert( pList
->eU4
!=EU4_EXPR
); /* EU4_EXPR mode is not currently used */
4713 for(i
=0; i
<pList
->nId
; i
++){
4714 sqlite3DbFree(db
, pList
->a
[i
].zName
);
4716 sqlite3DbNNFreeNN(db
, pList
);
4720 ** Return the index in pList of the identifier named zId. Return -1
4723 int sqlite3IdListIndex(IdList
*pList
, const char *zName
){
4726 for(i
=0; i
<pList
->nId
; i
++){
4727 if( sqlite3StrICmp(pList
->a
[i
].zName
, zName
)==0 ) return i
;
4733 ** Maximum size of a SrcList object.
4734 ** The SrcList object is used to represent the FROM clause of a
4735 ** SELECT statement, and the query planner cannot deal with more
4736 ** than 64 tables in a join. So any value larger than 64 here
4737 ** is sufficient for most uses. Smaller values, like say 10, are
4738 ** appropriate for small and memory-limited applications.
4740 #ifndef SQLITE_MAX_SRCLIST
4741 # define SQLITE_MAX_SRCLIST 200
4745 ** Expand the space allocated for the given SrcList object by
4746 ** creating nExtra new slots beginning at iStart. iStart is zero based.
4747 ** New slots are zeroed.
4749 ** For example, suppose a SrcList initially contains two entries: A,B.
4750 ** To append 3 new entries onto the end, do this:
4752 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4754 ** After the call above it would contain: A, B, nil, nil, nil.
4755 ** If the iStart argument had been 1 instead of 2, then the result
4756 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
4757 ** the iStart value would be 0. The result then would
4758 ** be: nil, nil, nil, A, B.
4760 ** If a memory allocation fails or the SrcList becomes too large, leave
4761 ** the original SrcList unchanged, return NULL, and leave an error message
4764 SrcList
*sqlite3SrcListEnlarge(
4765 Parse
*pParse
, /* Parsing context into which errors are reported */
4766 SrcList
*pSrc
, /* The SrcList to be enlarged */
4767 int nExtra
, /* Number of new slots to add to pSrc->a[] */
4768 int iStart
/* Index in pSrc->a[] of first new slot */
4772 /* Sanity checking on calling parameters */
4773 assert( iStart
>=0 );
4774 assert( nExtra
>=1 );
4776 assert( iStart
<=pSrc
->nSrc
);
4778 /* Allocate additional space if needed */
4779 if( (u32
)pSrc
->nSrc
+nExtra
>pSrc
->nAlloc
){
4781 sqlite3_int64 nAlloc
= 2*(sqlite3_int64
)pSrc
->nSrc
+nExtra
;
4782 sqlite3
*db
= pParse
->db
;
4784 if( pSrc
->nSrc
+nExtra
>=SQLITE_MAX_SRCLIST
){
4785 sqlite3ErrorMsg(pParse
, "too many FROM clause terms, max: %d",
4786 SQLITE_MAX_SRCLIST
);
4789 if( nAlloc
>SQLITE_MAX_SRCLIST
) nAlloc
= SQLITE_MAX_SRCLIST
;
4790 pNew
= sqlite3DbRealloc(db
, pSrc
,
4791 sizeof(*pSrc
) + (nAlloc
-1)*sizeof(pSrc
->a
[0]) );
4793 assert( db
->mallocFailed
);
4797 pSrc
->nAlloc
= nAlloc
;
4800 /* Move existing slots that come after the newly inserted slots
4801 ** out of the way */
4802 for(i
=pSrc
->nSrc
-1; i
>=iStart
; i
--){
4803 pSrc
->a
[i
+nExtra
] = pSrc
->a
[i
];
4805 pSrc
->nSrc
+= nExtra
;
4807 /* Zero the newly allocated slots */
4808 memset(&pSrc
->a
[iStart
], 0, sizeof(pSrc
->a
[0])*nExtra
);
4809 for(i
=iStart
; i
<iStart
+nExtra
; i
++){
4810 pSrc
->a
[i
].iCursor
= -1;
4813 /* Return a pointer to the enlarged SrcList */
4819 ** Append a new table name to the given SrcList. Create a new SrcList if
4820 ** need be. A new entry is created in the SrcList even if pTable is NULL.
4822 ** A SrcList is returned, or NULL if there is an OOM error or if the
4823 ** SrcList grows to large. The returned
4824 ** SrcList might be the same as the SrcList that was input or it might be
4825 ** a new one. If an OOM error does occurs, then the prior value of pList
4826 ** that is input to this routine is automatically freed.
4828 ** If pDatabase is not null, it means that the table has an optional
4829 ** database name prefix. Like this: "database.table". The pDatabase
4830 ** points to the table name and the pTable points to the database name.
4831 ** The SrcList.a[].zName field is filled with the table name which might
4832 ** come from pTable (if pDatabase is NULL) or from pDatabase.
4833 ** SrcList.a[].zDatabase is filled with the database name from pTable,
4834 ** or with NULL if no database is specified.
4836 ** In other words, if call like this:
4838 ** sqlite3SrcListAppend(D,A,B,0);
4840 ** Then B is a table name and the database name is unspecified. If called
4843 ** sqlite3SrcListAppend(D,A,B,C);
4845 ** Then C is the table name and B is the database name. If C is defined
4846 ** then so is B. In other words, we never have a case where:
4848 ** sqlite3SrcListAppend(D,A,0,C);
4850 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
4851 ** before being added to the SrcList.
4853 SrcList
*sqlite3SrcListAppend(
4854 Parse
*pParse
, /* Parsing context, in which errors are reported */
4855 SrcList
*pList
, /* Append to this SrcList. NULL creates a new SrcList */
4856 Token
*pTable
, /* Table to append */
4857 Token
*pDatabase
/* Database of the table */
4861 assert( pDatabase
==0 || pTable
!=0 ); /* Cannot have C without B */
4862 assert( pParse
!=0 );
4863 assert( pParse
->db
!=0 );
4866 pList
= sqlite3DbMallocRawNN(pParse
->db
, sizeof(SrcList
) );
4867 if( pList
==0 ) return 0;
4870 memset(&pList
->a
[0], 0, sizeof(pList
->a
[0]));
4871 pList
->a
[0].iCursor
= -1;
4873 SrcList
*pNew
= sqlite3SrcListEnlarge(pParse
, pList
, 1, pList
->nSrc
);
4875 sqlite3SrcListDelete(db
, pList
);
4881 pItem
= &pList
->a
[pList
->nSrc
-1];
4882 if( pDatabase
&& pDatabase
->z
==0 ){
4886 pItem
->zName
= sqlite3NameFromToken(db
, pDatabase
);
4887 pItem
->zDatabase
= sqlite3NameFromToken(db
, pTable
);
4889 pItem
->zName
= sqlite3NameFromToken(db
, pTable
);
4890 pItem
->zDatabase
= 0;
4896 ** Assign VdbeCursor index numbers to all tables in a SrcList
4898 void sqlite3SrcListAssignCursors(Parse
*pParse
, SrcList
*pList
){
4901 assert( pList
|| pParse
->db
->mallocFailed
);
4902 if( ALWAYS(pList
) ){
4903 for(i
=0, pItem
=pList
->a
; i
<pList
->nSrc
; i
++, pItem
++){
4904 if( pItem
->iCursor
>=0 ) continue;
4905 pItem
->iCursor
= pParse
->nTab
++;
4906 if( pItem
->pSelect
){
4907 sqlite3SrcListAssignCursors(pParse
, pItem
->pSelect
->pSrc
);
4914 ** Delete an entire SrcList including all its substructure.
4916 void sqlite3SrcListDelete(sqlite3
*db
, SrcList
*pList
){
4920 if( pList
==0 ) return;
4921 for(pItem
=pList
->a
, i
=0; i
<pList
->nSrc
; i
++, pItem
++){
4922 if( pItem
->zDatabase
) sqlite3DbNNFreeNN(db
, pItem
->zDatabase
);
4923 if( pItem
->zName
) sqlite3DbNNFreeNN(db
, pItem
->zName
);
4924 if( pItem
->zAlias
) sqlite3DbNNFreeNN(db
, pItem
->zAlias
);
4925 if( pItem
->fg
.isIndexedBy
) sqlite3DbFree(db
, pItem
->u1
.zIndexedBy
);
4926 if( pItem
->fg
.isTabFunc
) sqlite3ExprListDelete(db
, pItem
->u1
.pFuncArg
);
4927 sqlite3DeleteTable(db
, pItem
->pTab
);
4928 if( pItem
->pSelect
) sqlite3SelectDelete(db
, pItem
->pSelect
);
4929 if( pItem
->fg
.isUsing
){
4930 sqlite3IdListDelete(db
, pItem
->u3
.pUsing
);
4931 }else if( pItem
->u3
.pOn
){
4932 sqlite3ExprDelete(db
, pItem
->u3
.pOn
);
4935 sqlite3DbNNFreeNN(db
, pList
);
4939 ** This routine is called by the parser to add a new term to the
4940 ** end of a growing FROM clause. The "p" parameter is the part of
4941 ** the FROM clause that has already been constructed. "p" is NULL
4942 ** if this is the first term of the FROM clause. pTable and pDatabase
4943 ** are the name of the table and database named in the FROM clause term.
4944 ** pDatabase is NULL if the database name qualifier is missing - the
4945 ** usual case. If the term has an alias, then pAlias points to the
4946 ** alias token. If the term is a subquery, then pSubquery is the
4947 ** SELECT statement that the subquery encodes. The pTable and
4948 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
4949 ** parameters are the content of the ON and USING clauses.
4951 ** Return a new SrcList which encodes is the FROM with the new
4954 SrcList
*sqlite3SrcListAppendFromTerm(
4955 Parse
*pParse
, /* Parsing context */
4956 SrcList
*p
, /* The left part of the FROM clause already seen */
4957 Token
*pTable
, /* Name of the table to add to the FROM clause */
4958 Token
*pDatabase
, /* Name of the database containing pTable */
4959 Token
*pAlias
, /* The right-hand side of the AS subexpression */
4960 Select
*pSubquery
, /* A subquery used in place of a table name */
4961 OnOrUsing
*pOnUsing
/* Either the ON clause or the USING clause */
4964 sqlite3
*db
= pParse
->db
;
4965 if( !p
&& pOnUsing
!=0 && (pOnUsing
->pOn
|| pOnUsing
->pUsing
) ){
4966 sqlite3ErrorMsg(pParse
, "a JOIN clause is required before %s",
4967 (pOnUsing
->pOn
? "ON" : "USING")
4969 goto append_from_error
;
4971 p
= sqlite3SrcListAppend(pParse
, p
, pTable
, pDatabase
);
4973 goto append_from_error
;
4975 assert( p
->nSrc
>0 );
4976 pItem
= &p
->a
[p
->nSrc
-1];
4977 assert( (pTable
==0)==(pDatabase
==0) );
4978 assert( pItem
->zName
==0 || pDatabase
!=0 );
4979 if( IN_RENAME_OBJECT
&& pItem
->zName
){
4980 Token
*pToken
= (ALWAYS(pDatabase
) && pDatabase
->z
) ? pDatabase
: pTable
;
4981 sqlite3RenameTokenMap(pParse
, pItem
->zName
, pToken
);
4983 assert( pAlias
!=0 );
4985 pItem
->zAlias
= sqlite3NameFromToken(db
, pAlias
);
4988 pItem
->pSelect
= pSubquery
;
4989 if( pSubquery
->selFlags
& SF_NestedFrom
){
4990 pItem
->fg
.isNestedFrom
= 1;
4993 assert( pOnUsing
==0 || pOnUsing
->pOn
==0 || pOnUsing
->pUsing
==0 );
4994 assert( pItem
->fg
.isUsing
==0 );
4997 }else if( pOnUsing
->pUsing
){
4998 pItem
->fg
.isUsing
= 1;
4999 pItem
->u3
.pUsing
= pOnUsing
->pUsing
;
5001 pItem
->u3
.pOn
= pOnUsing
->pOn
;
5007 sqlite3ClearOnOrUsing(db
, pOnUsing
);
5008 sqlite3SelectDelete(db
, pSubquery
);
5013 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5014 ** element of the source-list passed as the second argument.
5016 void sqlite3SrcListIndexedBy(Parse
*pParse
, SrcList
*p
, Token
*pIndexedBy
){
5017 assert( pIndexedBy
!=0 );
5018 if( p
&& pIndexedBy
->n
>0 ){
5020 assert( p
->nSrc
>0 );
5021 pItem
= &p
->a
[p
->nSrc
-1];
5022 assert( pItem
->fg
.notIndexed
==0 );
5023 assert( pItem
->fg
.isIndexedBy
==0 );
5024 assert( pItem
->fg
.isTabFunc
==0 );
5025 if( pIndexedBy
->n
==1 && !pIndexedBy
->z
){
5026 /* A "NOT INDEXED" clause was supplied. See parse.y
5027 ** construct "indexed_opt" for details. */
5028 pItem
->fg
.notIndexed
= 1;
5030 pItem
->u1
.zIndexedBy
= sqlite3NameFromToken(pParse
->db
, pIndexedBy
);
5031 pItem
->fg
.isIndexedBy
= 1;
5032 assert( pItem
->fg
.isCte
==0 ); /* No collision on union u2 */
5038 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting
5039 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
5040 ** are deleted by this function.
5042 SrcList
*sqlite3SrcListAppendList(Parse
*pParse
, SrcList
*p1
, SrcList
*p2
){
5043 assert( p1
&& p1
->nSrc
==1 );
5045 SrcList
*pNew
= sqlite3SrcListEnlarge(pParse
, p1
, p2
->nSrc
, 1);
5047 sqlite3SrcListDelete(pParse
->db
, p2
);
5050 memcpy(&p1
->a
[1], p2
->a
, p2
->nSrc
*sizeof(SrcItem
));
5051 sqlite3DbFree(pParse
->db
, p2
);
5052 p1
->a
[0].fg
.jointype
|= (JT_LTORJ
& p1
->a
[1].fg
.jointype
);
5059 ** Add the list of function arguments to the SrcList entry for a
5060 ** table-valued-function.
5062 void sqlite3SrcListFuncArgs(Parse
*pParse
, SrcList
*p
, ExprList
*pList
){
5064 SrcItem
*pItem
= &p
->a
[p
->nSrc
-1];
5065 assert( pItem
->fg
.notIndexed
==0 );
5066 assert( pItem
->fg
.isIndexedBy
==0 );
5067 assert( pItem
->fg
.isTabFunc
==0 );
5068 pItem
->u1
.pFuncArg
= pList
;
5069 pItem
->fg
.isTabFunc
= 1;
5071 sqlite3ExprListDelete(pParse
->db
, pList
);
5076 ** When building up a FROM clause in the parser, the join operator
5077 ** is initially attached to the left operand. But the code generator
5078 ** expects the join operator to be on the right operand. This routine
5079 ** Shifts all join operators from left to right for an entire FROM
5082 ** Example: Suppose the join is like this:
5084 ** A natural cross join B
5086 ** The operator is "natural cross join". The A and B operands are stored
5087 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
5088 ** operator with A. This routine shifts that operator over to B.
5090 ** Additional changes:
5092 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
5093 ** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
5094 ** code generator can easily tell that the table is part of
5095 ** the left operand of at least one RIGHT JOIN.
5097 void sqlite3SrcListShiftJoinType(Parse
*pParse
, SrcList
*p
){
5099 if( p
&& p
->nSrc
>1 ){
5103 allFlags
|= p
->a
[i
].fg
.jointype
= p
->a
[i
-1].fg
.jointype
;
5105 p
->a
[0].fg
.jointype
= 0;
5107 /* All terms to the left of a RIGHT JOIN should be tagged with the
5108 ** JT_LTORJ flags */
5109 if( allFlags
& JT_RIGHT
){
5110 for(i
=p
->nSrc
-1; ALWAYS(i
>0) && (p
->a
[i
].fg
.jointype
&JT_RIGHT
)==0; i
--){}
5114 p
->a
[i
].fg
.jointype
|= JT_LTORJ
;
5121 ** Generate VDBE code for a BEGIN statement.
5123 void sqlite3BeginTransaction(Parse
*pParse
, int type
){
5128 assert( pParse
!=0 );
5131 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
, "BEGIN", 0, 0) ){
5134 v
= sqlite3GetVdbe(pParse
);
5136 if( type
!=TK_DEFERRED
){
5137 for(i
=0; i
<db
->nDb
; i
++){
5139 Btree
*pBt
= db
->aDb
[i
].pBt
;
5140 if( pBt
&& sqlite3BtreeIsReadonly(pBt
) ){
5141 eTxnType
= 0; /* Read txn */
5142 }else if( type
==TK_EXCLUSIVE
){
5143 eTxnType
= 2; /* Exclusive txn */
5145 eTxnType
= 1; /* Write txn */
5147 sqlite3VdbeAddOp2(v
, OP_Transaction
, i
, eTxnType
);
5148 sqlite3VdbeUsesBtree(v
, i
);
5151 sqlite3VdbeAddOp0(v
, OP_AutoCommit
);
5155 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
5156 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
5157 ** code is generated for a COMMIT.
5159 void sqlite3EndTransaction(Parse
*pParse
, int eType
){
5163 assert( pParse
!=0 );
5164 assert( pParse
->db
!=0 );
5165 assert( eType
==TK_COMMIT
|| eType
==TK_END
|| eType
==TK_ROLLBACK
);
5166 isRollback
= eType
==TK_ROLLBACK
;
5167 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
,
5168 isRollback
? "ROLLBACK" : "COMMIT", 0, 0) ){
5171 v
= sqlite3GetVdbe(pParse
);
5173 sqlite3VdbeAddOp2(v
, OP_AutoCommit
, 1, isRollback
);
5178 ** This function is called by the parser when it parses a command to create,
5179 ** release or rollback an SQL savepoint.
5181 void sqlite3Savepoint(Parse
*pParse
, int op
, Token
*pName
){
5182 char *zName
= sqlite3NameFromToken(pParse
->db
, pName
);
5184 Vdbe
*v
= sqlite3GetVdbe(pParse
);
5185 #ifndef SQLITE_OMIT_AUTHORIZATION
5186 static const char * const az
[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5187 assert( !SAVEPOINT_BEGIN
&& SAVEPOINT_RELEASE
==1 && SAVEPOINT_ROLLBACK
==2 );
5189 if( !v
|| sqlite3AuthCheck(pParse
, SQLITE_SAVEPOINT
, az
[op
], zName
, 0) ){
5190 sqlite3DbFree(pParse
->db
, zName
);
5193 sqlite3VdbeAddOp4(v
, OP_Savepoint
, op
, 0, 0, zName
, P4_DYNAMIC
);
5198 ** Make sure the TEMP database is open and available for use. Return
5199 ** the number of errors. Leave any error messages in the pParse structure.
5201 int sqlite3OpenTempDatabase(Parse
*pParse
){
5202 sqlite3
*db
= pParse
->db
;
5203 if( db
->aDb
[1].pBt
==0 && !pParse
->explain
){
5206 static const int flags
=
5207 SQLITE_OPEN_READWRITE
|
5208 SQLITE_OPEN_CREATE
|
5209 SQLITE_OPEN_EXCLUSIVE
|
5210 SQLITE_OPEN_DELETEONCLOSE
|
5211 SQLITE_OPEN_TEMP_DB
;
5213 rc
= sqlite3BtreeOpen(db
->pVfs
, 0, db
, &pBt
, 0, flags
);
5214 if( rc
!=SQLITE_OK
){
5215 sqlite3ErrorMsg(pParse
, "unable to open a temporary database "
5216 "file for storing temporary tables");
5220 db
->aDb
[1].pBt
= pBt
;
5221 assert( db
->aDb
[1].pSchema
);
5222 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
, 0, 0) ){
5223 sqlite3OomFault(db
);
5231 ** Record the fact that the schema cookie will need to be verified
5232 ** for database iDb. The code to actually verify the schema cookie
5233 ** will occur at the end of the top-level VDBE and will be generated
5234 ** later, by sqlite3FinishCoding().
5236 static void sqlite3CodeVerifySchemaAtToplevel(Parse
*pToplevel
, int iDb
){
5237 assert( iDb
>=0 && iDb
<pToplevel
->db
->nDb
);
5238 assert( pToplevel
->db
->aDb
[iDb
].pBt
!=0 || iDb
==1 );
5239 assert( iDb
<SQLITE_MAX_DB
);
5240 assert( sqlite3SchemaMutexHeld(pToplevel
->db
, iDb
, 0) );
5241 if( DbMaskTest(pToplevel
->cookieMask
, iDb
)==0 ){
5242 DbMaskSet(pToplevel
->cookieMask
, iDb
);
5243 if( !OMIT_TEMPDB
&& iDb
==1 ){
5244 sqlite3OpenTempDatabase(pToplevel
);
5248 void sqlite3CodeVerifySchema(Parse
*pParse
, int iDb
){
5249 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse
), iDb
);
5254 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
5255 ** attached database. Otherwise, invoke it for the database named zDb only.
5257 void sqlite3CodeVerifyNamedSchema(Parse
*pParse
, const char *zDb
){
5258 sqlite3
*db
= pParse
->db
;
5260 for(i
=0; i
<db
->nDb
; i
++){
5261 Db
*pDb
= &db
->aDb
[i
];
5262 if( pDb
->pBt
&& (!zDb
|| 0==sqlite3StrICmp(zDb
, pDb
->zDbSName
)) ){
5263 sqlite3CodeVerifySchema(pParse
, i
);
5269 ** Generate VDBE code that prepares for doing an operation that
5270 ** might change the database.
5272 ** This routine starts a new transaction if we are not already within
5273 ** a transaction. If we are already within a transaction, then a checkpoint
5274 ** is set if the setStatement parameter is true. A checkpoint should
5275 ** be set for operations that might fail (due to a constraint) part of
5276 ** the way through and which will need to undo some writes without having to
5277 ** rollback the whole transaction. For operations where all constraints
5278 ** can be checked before any changes are made to the database, it is never
5279 ** necessary to undo a write and the checkpoint should not be set.
5281 void sqlite3BeginWriteOperation(Parse
*pParse
, int setStatement
, int iDb
){
5282 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
5283 sqlite3CodeVerifySchemaAtToplevel(pToplevel
, iDb
);
5284 DbMaskSet(pToplevel
->writeMask
, iDb
);
5285 pToplevel
->isMultiWrite
|= setStatement
;
5289 ** Indicate that the statement currently under construction might write
5290 ** more than one entry (example: deleting one row then inserting another,
5291 ** inserting multiple rows in a table, or inserting a row and index entries.)
5292 ** If an abort occurs after some of these writes have completed, then it will
5293 ** be necessary to undo the completed writes.
5295 void sqlite3MultiWrite(Parse
*pParse
){
5296 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
5297 pToplevel
->isMultiWrite
= 1;
5301 ** The code generator calls this routine if is discovers that it is
5302 ** possible to abort a statement prior to completion. In order to
5303 ** perform this abort without corrupting the database, we need to make
5304 ** sure that the statement is protected by a statement transaction.
5306 ** Technically, we only need to set the mayAbort flag if the
5307 ** isMultiWrite flag was previously set. There is a time dependency
5308 ** such that the abort must occur after the multiwrite. This makes
5309 ** some statements involving the REPLACE conflict resolution algorithm
5310 ** go a little faster. But taking advantage of this time dependency
5311 ** makes it more difficult to prove that the code is correct (in
5312 ** particular, it prevents us from writing an effective
5313 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
5314 ** to take the safe route and skip the optimization.
5316 void sqlite3MayAbort(Parse
*pParse
){
5317 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
5318 pToplevel
->mayAbort
= 1;
5322 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5323 ** error. The onError parameter determines which (if any) of the statement
5324 ** and/or current transaction is rolled back.
5326 void sqlite3HaltConstraint(
5327 Parse
*pParse
, /* Parsing context */
5328 int errCode
, /* extended error code */
5329 int onError
, /* Constraint type */
5330 char *p4
, /* Error message */
5331 i8 p4type
, /* P4_STATIC or P4_TRANSIENT */
5332 u8 p5Errmsg
/* P5_ErrMsg type */
5335 assert( pParse
->pVdbe
!=0 );
5336 v
= sqlite3GetVdbe(pParse
);
5337 assert( (errCode
&0xff)==SQLITE_CONSTRAINT
|| pParse
->nested
);
5338 if( onError
==OE_Abort
){
5339 sqlite3MayAbort(pParse
);
5341 sqlite3VdbeAddOp4(v
, OP_Halt
, errCode
, onError
, 0, p4
, p4type
);
5342 sqlite3VdbeChangeP5(v
, p5Errmsg
);
5346 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5348 void sqlite3UniqueConstraint(
5349 Parse
*pParse
, /* Parsing context */
5350 int onError
, /* Constraint type */
5351 Index
*pIdx
/* The index that triggers the constraint */
5356 Table
*pTab
= pIdx
->pTable
;
5358 sqlite3StrAccumInit(&errMsg
, pParse
->db
, 0, 0,
5359 pParse
->db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
5360 if( pIdx
->aColExpr
){
5361 sqlite3_str_appendf(&errMsg
, "index '%q'", pIdx
->zName
);
5363 for(j
=0; j
<pIdx
->nKeyCol
; j
++){
5365 assert( pIdx
->aiColumn
[j
]>=0 );
5366 zCol
= pTab
->aCol
[pIdx
->aiColumn
[j
]].zCnName
;
5367 if( j
) sqlite3_str_append(&errMsg
, ", ", 2);
5368 sqlite3_str_appendall(&errMsg
, pTab
->zName
);
5369 sqlite3_str_append(&errMsg
, ".", 1);
5370 sqlite3_str_appendall(&errMsg
, zCol
);
5373 zErr
= sqlite3StrAccumFinish(&errMsg
);
5374 sqlite3HaltConstraint(pParse
,
5375 IsPrimaryKeyIndex(pIdx
) ? SQLITE_CONSTRAINT_PRIMARYKEY
5376 : SQLITE_CONSTRAINT_UNIQUE
,
5377 onError
, zErr
, P4_DYNAMIC
, P5_ConstraintUnique
);
5382 ** Code an OP_Halt due to non-unique rowid.
5384 void sqlite3RowidConstraint(
5385 Parse
*pParse
, /* Parsing context */
5386 int onError
, /* Conflict resolution algorithm */
5387 Table
*pTab
/* The table with the non-unique rowid */
5391 if( pTab
->iPKey
>=0 ){
5392 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.%s", pTab
->zName
,
5393 pTab
->aCol
[pTab
->iPKey
].zCnName
);
5394 rc
= SQLITE_CONSTRAINT_PRIMARYKEY
;
5396 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.rowid", pTab
->zName
);
5397 rc
= SQLITE_CONSTRAINT_ROWID
;
5399 sqlite3HaltConstraint(pParse
, rc
, onError
, zMsg
, P4_DYNAMIC
,
5400 P5_ConstraintUnique
);
5404 ** Check to see if pIndex uses the collating sequence pColl. Return
5405 ** true if it does and false if it does not.
5407 #ifndef SQLITE_OMIT_REINDEX
5408 static int collationMatch(const char *zColl
, Index
*pIndex
){
5411 for(i
=0; i
<pIndex
->nColumn
; i
++){
5412 const char *z
= pIndex
->azColl
[i
];
5413 assert( z
!=0 || pIndex
->aiColumn
[i
]<0 );
5414 if( pIndex
->aiColumn
[i
]>=0 && 0==sqlite3StrICmp(z
, zColl
) ){
5423 ** Recompute all indices of pTab that use the collating sequence pColl.
5424 ** If pColl==0 then recompute all indices of pTab.
5426 #ifndef SQLITE_OMIT_REINDEX
5427 static void reindexTable(Parse
*pParse
, Table
*pTab
, char const *zColl
){
5428 if( !IsVirtual(pTab
) ){
5429 Index
*pIndex
; /* An index associated with pTab */
5431 for(pIndex
=pTab
->pIndex
; pIndex
; pIndex
=pIndex
->pNext
){
5432 if( zColl
==0 || collationMatch(zColl
, pIndex
) ){
5433 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
5434 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
5435 sqlite3RefillIndex(pParse
, pIndex
, -1);
5443 ** Recompute all indices of all tables in all databases where the
5444 ** indices use the collating sequence pColl. If pColl==0 then recompute
5445 ** all indices everywhere.
5447 #ifndef SQLITE_OMIT_REINDEX
5448 static void reindexDatabases(Parse
*pParse
, char const *zColl
){
5449 Db
*pDb
; /* A single database */
5450 int iDb
; /* The database index number */
5451 sqlite3
*db
= pParse
->db
; /* The database connection */
5452 HashElem
*k
; /* For looping over tables in pDb */
5453 Table
*pTab
; /* A table in the database */
5455 assert( sqlite3BtreeHoldsAllMutexes(db
) ); /* Needed for schema access */
5456 for(iDb
=0, pDb
=db
->aDb
; iDb
<db
->nDb
; iDb
++, pDb
++){
5458 for(k
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
5459 pTab
= (Table
*)sqliteHashData(k
);
5460 reindexTable(pParse
, pTab
, zColl
);
5467 ** Generate code for the REINDEX command.
5470 ** REINDEX <collation> -- 2
5471 ** REINDEX ?<database>.?<tablename> -- 3
5472 ** REINDEX ?<database>.?<indexname> -- 4
5474 ** Form 1 causes all indices in all attached databases to be rebuilt.
5475 ** Form 2 rebuilds all indices in all databases that use the named
5476 ** collating function. Forms 3 and 4 rebuild the named index or all
5477 ** indices associated with the named table.
5479 #ifndef SQLITE_OMIT_REINDEX
5480 void sqlite3Reindex(Parse
*pParse
, Token
*pName1
, Token
*pName2
){
5481 CollSeq
*pColl
; /* Collating sequence to be reindexed, or NULL */
5482 char *z
; /* Name of a table or index */
5483 const char *zDb
; /* Name of the database */
5484 Table
*pTab
; /* A table in the database */
5485 Index
*pIndex
; /* An index associated with pTab */
5486 int iDb
; /* The database index number */
5487 sqlite3
*db
= pParse
->db
; /* The database connection */
5488 Token
*pObjName
; /* Name of the table or index to be reindexed */
5490 /* Read the database schema. If an error occurs, leave an error message
5491 ** and code in pParse and return NULL. */
5492 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
5497 reindexDatabases(pParse
, 0);
5499 }else if( NEVER(pName2
==0) || pName2
->z
==0 ){
5501 assert( pName1
->z
);
5502 zColl
= sqlite3NameFromToken(pParse
->db
, pName1
);
5503 if( !zColl
) return;
5504 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
5506 reindexDatabases(pParse
, zColl
);
5507 sqlite3DbFree(db
, zColl
);
5510 sqlite3DbFree(db
, zColl
);
5512 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pObjName
);
5514 z
= sqlite3NameFromToken(db
, pObjName
);
5516 zDb
= db
->aDb
[iDb
].zDbSName
;
5517 pTab
= sqlite3FindTable(db
, z
, zDb
);
5519 reindexTable(pParse
, pTab
, 0);
5520 sqlite3DbFree(db
, z
);
5523 pIndex
= sqlite3FindIndex(db
, z
, zDb
);
5524 sqlite3DbFree(db
, z
);
5526 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
5527 sqlite3RefillIndex(pParse
, pIndex
, -1);
5530 sqlite3ErrorMsg(pParse
, "unable to identify the object to be reindexed");
5535 ** Return a KeyInfo structure that is appropriate for the given Index.
5537 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5538 ** when it has finished using it.
5540 KeyInfo
*sqlite3KeyInfoOfIndex(Parse
*pParse
, Index
*pIdx
){
5542 int nCol
= pIdx
->nColumn
;
5543 int nKey
= pIdx
->nKeyCol
;
5545 if( pParse
->nErr
) return 0;
5546 if( pIdx
->uniqNotNull
){
5547 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nKey
, nCol
-nKey
);
5549 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nCol
, 0);
5552 assert( sqlite3KeyInfoIsWriteable(pKey
) );
5553 for(i
=0; i
<nCol
; i
++){
5554 const char *zColl
= pIdx
->azColl
[i
];
5555 pKey
->aColl
[i
] = zColl
==sqlite3StrBINARY
? 0 :
5556 sqlite3LocateCollSeq(pParse
, zColl
);
5557 pKey
->aSortFlags
[i
] = pIdx
->aSortOrder
[i
];
5558 assert( 0==(pKey
->aSortFlags
[i
] & KEYINFO_ORDER_BIGNULL
) );
5561 assert( pParse
->rc
==SQLITE_ERROR_MISSING_COLLSEQ
);
5562 if( pIdx
->bNoQuery
==0 ){
5563 /* Deactivate the index because it contains an unknown collating
5564 ** sequence. The only way to reactive the index is to reload the
5565 ** schema. Adding the missing collating sequence later does not
5566 ** reactive the index. The application had the chance to register
5567 ** the missing index using the collation-needed callback. For
5568 ** simplicity, SQLite will not give the application a second chance.
5571 pParse
->rc
= SQLITE_ERROR_RETRY
;
5573 sqlite3KeyInfoUnref(pKey
);
5580 #ifndef SQLITE_OMIT_CTE
5582 ** Create a new CTE object
5585 Parse
*pParse
, /* Parsing context */
5586 Token
*pName
, /* Name of the common-table */
5587 ExprList
*pArglist
, /* Optional column name list for the table */
5588 Select
*pQuery
, /* Query used to initialize the table */
5589 u8 eM10d
/* The MATERIALIZED flag */
5592 sqlite3
*db
= pParse
->db
;
5594 pNew
= sqlite3DbMallocZero(db
, sizeof(*pNew
));
5595 assert( pNew
!=0 || db
->mallocFailed
);
5597 if( db
->mallocFailed
){
5598 sqlite3ExprListDelete(db
, pArglist
);
5599 sqlite3SelectDelete(db
, pQuery
);
5601 pNew
->pSelect
= pQuery
;
5602 pNew
->pCols
= pArglist
;
5603 pNew
->zName
= sqlite3NameFromToken(pParse
->db
, pName
);
5604 pNew
->eM10d
= eM10d
;
5610 ** Clear information from a Cte object, but do not deallocate storage
5611 ** for the object itself.
5613 static void cteClear(sqlite3
*db
, Cte
*pCte
){
5615 sqlite3ExprListDelete(db
, pCte
->pCols
);
5616 sqlite3SelectDelete(db
, pCte
->pSelect
);
5617 sqlite3DbFree(db
, pCte
->zName
);
5621 ** Free the contents of the CTE object passed as the second argument.
5623 void sqlite3CteDelete(sqlite3
*db
, Cte
*pCte
){
5626 sqlite3DbFree(db
, pCte
);
5630 ** This routine is invoked once per CTE by the parser while parsing a
5631 ** WITH clause. The CTE described by teh third argument is added to
5632 ** the WITH clause of the second argument. If the second argument is
5633 ** NULL, then a new WITH argument is created.
5635 With
*sqlite3WithAdd(
5636 Parse
*pParse
, /* Parsing context */
5637 With
*pWith
, /* Existing WITH clause, or NULL */
5638 Cte
*pCte
/* CTE to add to the WITH clause */
5640 sqlite3
*db
= pParse
->db
;
5648 /* Check that the CTE name is unique within this WITH clause. If
5649 ** not, store an error in the Parse structure. */
5650 zName
= pCte
->zName
;
5651 if( zName
&& pWith
){
5653 for(i
=0; i
<pWith
->nCte
; i
++){
5654 if( sqlite3StrICmp(zName
, pWith
->a
[i
].zName
)==0 ){
5655 sqlite3ErrorMsg(pParse
, "duplicate WITH table name: %s", zName
);
5661 sqlite3_int64 nByte
= sizeof(*pWith
) + (sizeof(pWith
->a
[1]) * pWith
->nCte
);
5662 pNew
= sqlite3DbRealloc(db
, pWith
, nByte
);
5664 pNew
= sqlite3DbMallocZero(db
, sizeof(*pWith
));
5666 assert( (pNew
!=0 && zName
!=0) || db
->mallocFailed
);
5668 if( db
->mallocFailed
){
5669 sqlite3CteDelete(db
, pCte
);
5672 pNew
->a
[pNew
->nCte
++] = *pCte
;
5673 sqlite3DbFree(db
, pCte
);
5680 ** Free the contents of the With object passed as the second argument.
5682 void sqlite3WithDelete(sqlite3
*db
, With
*pWith
){
5685 for(i
=0; i
<pWith
->nCte
; i
++){
5686 cteClear(db
, &pWith
->a
[i
]);
5688 sqlite3DbFree(db
, pWith
);
5691 #endif /* !defined(SQLITE_OMIT_CTE) */