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 int 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 *zName
; /* 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 void sqlite3TableLock(
50 Parse
*pParse
, /* Parsing context */
51 int iDb
, /* Index of the database containing the table to lock */
52 int iTab
, /* Root page number of the table to be locked */
53 u8 isWriteLock
, /* True for a write lock */
54 const char *zName
/* Name of the table to be locked */
56 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
62 for(i
=0; i
<pToplevel
->nTableLock
; i
++){
63 p
= &pToplevel
->aTableLock
[i
];
64 if( p
->iDb
==iDb
&& p
->iTab
==iTab
){
65 p
->isWriteLock
= (p
->isWriteLock
|| isWriteLock
);
70 nBytes
= sizeof(TableLock
) * (pToplevel
->nTableLock
+1);
71 pToplevel
->aTableLock
=
72 sqlite3DbReallocOrFree(pToplevel
->db
, pToplevel
->aTableLock
, nBytes
);
73 if( pToplevel
->aTableLock
){
74 p
= &pToplevel
->aTableLock
[pToplevel
->nTableLock
++];
77 p
->isWriteLock
= isWriteLock
;
80 pToplevel
->nTableLock
= 0;
81 sqlite3OomFault(pToplevel
->db
);
86 ** Code an OP_TableLock instruction for each table locked by the
87 ** statement (configured by calls to sqlite3TableLock()).
89 static void codeTableLocks(Parse
*pParse
){
93 pVdbe
= sqlite3GetVdbe(pParse
);
94 assert( pVdbe
!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
96 for(i
=0; i
<pParse
->nTableLock
; i
++){
97 TableLock
*p
= &pParse
->aTableLock
[i
];
99 sqlite3VdbeAddOp4(pVdbe
, OP_TableLock
, p1
, p
->iTab
, p
->isWriteLock
,
100 p
->zName
, P4_STATIC
);
104 #define codeTableLocks(x)
108 ** Return TRUE if the given yDbMask object is empty - if it contains no
109 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
110 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
112 #if SQLITE_MAX_ATTACHED>30
113 int sqlite3DbMaskAllZero(yDbMask m
){
115 for(i
=0; i
<sizeof(yDbMask
); i
++) if( m
[i
] ) return 0;
121 ** This routine is called after a single SQL statement has been
122 ** parsed and a VDBE program to execute that statement has been
123 ** prepared. This routine puts the finishing touches on the
124 ** VDBE program and resets the pParse structure for the next
127 ** Note that if an error occurred, it might be the case that
128 ** no VDBE code was generated.
130 void sqlite3FinishCoding(Parse
*pParse
){
134 assert( pParse
->pToplevel
==0 );
136 if( pParse
->nested
) return;
137 if( db
->mallocFailed
|| pParse
->nErr
){
138 if( pParse
->rc
==SQLITE_OK
) pParse
->rc
= SQLITE_ERROR
;
142 /* Begin by generating some termination code at the end of the
145 v
= sqlite3GetVdbe(pParse
);
146 assert( !pParse
->isMultiWrite
147 || sqlite3VdbeAssertMayAbort(v
, pParse
->mayAbort
));
149 while( sqlite3VdbeDeletePriorOpcode(v
, OP_Close
) ){}
150 sqlite3VdbeAddOp0(v
, OP_Halt
);
152 #if SQLITE_USER_AUTHENTICATION
153 if( pParse
->nTableLock
>0 && db
->init
.busy
==0 ){
154 sqlite3UserAuthInit(db
);
155 if( db
->auth
.authLevel
<UAUTH_User
){
156 pParse
->rc
= SQLITE_AUTH_USER
;
157 sqlite3ErrorMsg(pParse
, "user not authenticated");
163 /* The cookie mask contains one bit for each database file open.
164 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
165 ** set for each database that is used. Generate code to start a
166 ** transaction on each used database and to verify the schema cookie
167 ** on each used database.
169 if( db
->mallocFailed
==0
170 && (DbMaskNonZero(pParse
->cookieMask
) || pParse
->pConstExpr
)
173 assert( sqlite3VdbeGetOp(v
, 0)->opcode
==OP_Init
);
174 sqlite3VdbeJumpHere(v
, 0);
175 for(iDb
=0; iDb
<db
->nDb
; iDb
++){
176 if( DbMaskTest(pParse
->cookieMask
, iDb
)==0 ) continue;
177 sqlite3VdbeUsesBtree(v
, iDb
);
178 sqlite3VdbeAddOp4Int(v
,
179 OP_Transaction
, /* Opcode */
181 DbMaskTest(pParse
->writeMask
,iDb
), /* P2 */
182 pParse
->cookieValue
[iDb
], /* P3 */
183 db
->aDb
[iDb
].pSchema
->iGeneration
/* P4 */
185 if( db
->init
.busy
==0 ) sqlite3VdbeChangeP5(v
, 1);
187 "usesStmtJournal=%d", pParse
->mayAbort
&& pParse
->isMultiWrite
));
189 #ifndef SQLITE_OMIT_VIRTUALTABLE
190 for(i
=0; i
<pParse
->nVtabLock
; i
++){
191 char *vtab
= (char *)sqlite3GetVTable(db
, pParse
->apVtabLock
[i
]);
192 sqlite3VdbeAddOp4(v
, OP_VBegin
, 0, 0, 0, vtab
, P4_VTAB
);
194 pParse
->nVtabLock
= 0;
197 /* Once all the cookies have been verified and transactions opened,
198 ** obtain the required table-locks. This is a no-op unless the
199 ** shared-cache feature is enabled.
201 codeTableLocks(pParse
);
203 /* Initialize any AUTOINCREMENT data structures required.
205 sqlite3AutoincrementBegin(pParse
);
207 /* Code constant expressions that where factored out of inner loops */
208 if( pParse
->pConstExpr
){
209 ExprList
*pEL
= pParse
->pConstExpr
;
210 pParse
->okConstFactor
= 0;
211 for(i
=0; i
<pEL
->nExpr
; i
++){
212 sqlite3ExprCode(pParse
, pEL
->a
[i
].pExpr
, pEL
->a
[i
].u
.iConstExprReg
);
216 /* Finally, jump back to the beginning of the executable code. */
217 sqlite3VdbeGoto(v
, 1);
222 /* Get the VDBE program ready for execution
224 if( v
&& pParse
->nErr
==0 && !db
->mallocFailed
){
225 assert( pParse
->iCacheLevel
==0 ); /* Disables and re-enables match */
226 /* A minimum of one cursor is required if autoincrement is used
227 * See ticket [a696379c1f08866] */
228 if( pParse
->pAinc
!=0 && pParse
->nTab
==0 ) pParse
->nTab
= 1;
229 sqlite3VdbeMakeReady(v
, pParse
);
230 pParse
->rc
= SQLITE_DONE
;
232 pParse
->rc
= SQLITE_ERROR
;
235 /* We are done with this Parse object. There is no need to de-initialize it */
237 pParse
->colNamesSet
= 0;
242 DbMaskZero(pParse
->cookieMask
);
247 ** Run the parser and code generator recursively in order to generate
248 ** code for the SQL statement given onto the end of the pParse context
249 ** currently under construction. When the parser is run recursively
250 ** this way, the final OP_Halt is not appended and other initialization
251 ** and finalization steps are omitted because those are handling by the
254 ** Not everything is nestable. This facility is designed to permit
255 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
256 ** care if you decide to try to use this routine for some other purposes.
258 void sqlite3NestedParse(Parse
*pParse
, const char *zFormat
, ...){
262 sqlite3
*db
= pParse
->db
;
263 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
264 char saveBuf
[SAVE_SZ
];
266 if( pParse
->nErr
) return;
267 assert( pParse
->nested
<10 ); /* Nesting should only be of limited depth */
268 va_start(ap
, zFormat
);
269 zSql
= sqlite3VMPrintf(db
, zFormat
, ap
);
272 return; /* A malloc must have failed */
275 memcpy(saveBuf
, &pParse
->nVar
, SAVE_SZ
);
276 memset(&pParse
->nVar
, 0, SAVE_SZ
);
277 sqlite3RunParser(pParse
, zSql
, &zErrMsg
);
278 sqlite3DbFree(db
, zErrMsg
);
279 sqlite3DbFree(db
, zSql
);
280 memcpy(&pParse
->nVar
, saveBuf
, SAVE_SZ
);
284 #if SQLITE_USER_AUTHENTICATION
286 ** Return TRUE if zTable is the name of the system table that stores the
287 ** list of users and their access credentials.
289 int sqlite3UserAuthTable(const char *zTable
){
290 return sqlite3_stricmp(zTable
, "sqlite_user")==0;
295 ** Locate the in-memory structure that describes a particular database
296 ** table given the name of that table and (optionally) the name of the
297 ** database containing the table. Return NULL if not found.
299 ** If zDatabase is 0, all databases are searched for the table and the
300 ** first matching table is returned. (No checking for duplicate table
301 ** names is done.) The search order is TEMP first, then MAIN, then any
302 ** auxiliary databases added using the ATTACH command.
304 ** See also sqlite3LocateTable().
306 Table
*sqlite3FindTable(sqlite3
*db
, const char *zName
, const char *zDatabase
){
310 /* All mutexes are required for schema access. Make sure we hold them. */
311 assert( zDatabase
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
312 #if SQLITE_USER_AUTHENTICATION
313 /* Only the admin user is allowed to know that the sqlite_user table
315 if( db
->auth
.authLevel
<UAUTH_Admin
&& sqlite3UserAuthTable(zName
)!=0 ){
319 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
320 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
321 if( zDatabase
!=0 && sqlite3StrICmp(zDatabase
, db
->aDb
[j
].zName
) ) continue;
322 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
323 p
= sqlite3HashFind(&db
->aDb
[j
].pSchema
->tblHash
, zName
);
330 ** Locate the in-memory structure that describes a particular database
331 ** table given the name of that table and (optionally) the name of the
332 ** database containing the table. Return NULL if not found. Also leave an
333 ** error message in pParse->zErrMsg.
335 ** The difference between this routine and sqlite3FindTable() is that this
336 ** routine leaves an error message in pParse->zErrMsg where
337 ** sqlite3FindTable() does not.
339 Table
*sqlite3LocateTable(
340 Parse
*pParse
, /* context in which to report errors */
341 u32 flags
, /* LOCATE_VIEW or LOCATE_NOERR */
342 const char *zName
, /* Name of the table we are looking for */
343 const char *zDbase
/* Name of the database. Might be NULL */
347 /* Read the database schema. If an error occurs, leave an error message
348 ** and code in pParse and return NULL. */
349 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
353 p
= sqlite3FindTable(pParse
->db
, zName
, zDbase
);
355 const char *zMsg
= flags
& LOCATE_VIEW
? "no such view" : "no such table";
356 #ifndef SQLITE_OMIT_VIRTUALTABLE
357 if( sqlite3FindDbName(pParse
->db
, zDbase
)<1 ){
358 /* If zName is the not the name of a table in the schema created using
359 ** CREATE, then check to see if it is the name of an virtual table that
360 ** can be an eponymous virtual table. */
361 Module
*pMod
= (Module
*)sqlite3HashFind(&pParse
->db
->aModule
, zName
);
362 if( pMod
&& sqlite3VtabEponymousTableInit(pParse
, pMod
) ){
363 return pMod
->pEpoTab
;
367 if( (flags
& LOCATE_NOERR
)==0 ){
369 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zMsg
, zDbase
, zName
);
371 sqlite3ErrorMsg(pParse
, "%s: %s", zMsg
, zName
);
373 pParse
->checkSchema
= 1;
381 ** Locate the table identified by *p.
383 ** This is a wrapper around sqlite3LocateTable(). The difference between
384 ** sqlite3LocateTable() and this function is that this function restricts
385 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
386 ** non-NULL if it is part of a view or trigger program definition. See
387 ** sqlite3FixSrcList() for details.
389 Table
*sqlite3LocateTableItem(
392 struct SrcList_item
*p
395 assert( p
->pSchema
==0 || p
->zDatabase
==0 );
397 int iDb
= sqlite3SchemaToIndex(pParse
->db
, p
->pSchema
);
398 zDb
= pParse
->db
->aDb
[iDb
].zName
;
402 return sqlite3LocateTable(pParse
, flags
, p
->zName
, zDb
);
406 ** Locate the in-memory structure that describes
407 ** a particular index given the name of that index
408 ** and the name of the database that contains the index.
409 ** Return NULL if not found.
411 ** If zDatabase is 0, all databases are searched for the
412 ** table and the first matching index is returned. (No checking
413 ** for duplicate index names is done.) The search order is
414 ** TEMP first, then MAIN, then any auxiliary databases added
415 ** using the ATTACH command.
417 Index
*sqlite3FindIndex(sqlite3
*db
, const char *zName
, const char *zDb
){
420 /* All mutexes are required for schema access. Make sure we hold them. */
421 assert( zDb
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
422 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
423 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
424 Schema
*pSchema
= db
->aDb
[j
].pSchema
;
426 if( zDb
&& sqlite3StrICmp(zDb
, db
->aDb
[j
].zName
) ) continue;
427 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
428 p
= sqlite3HashFind(&pSchema
->idxHash
, zName
);
435 ** Reclaim the memory used by an index
437 static void freeIndex(sqlite3
*db
, Index
*p
){
438 #ifndef SQLITE_OMIT_ANALYZE
439 sqlite3DeleteIndexSamples(db
, p
);
441 sqlite3ExprDelete(db
, p
->pPartIdxWhere
);
442 sqlite3ExprListDelete(db
, p
->aColExpr
);
443 sqlite3DbFree(db
, p
->zColAff
);
444 if( p
->isResized
) sqlite3DbFree(db
, (void *)p
->azColl
);
445 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
446 sqlite3_free(p
->aiRowEst
);
448 sqlite3DbFree(db
, p
);
452 ** For the index called zIdxName which is found in the database iDb,
453 ** unlike that index from its Table then remove the index from
454 ** the index hash table and free all memory structures associated
457 void sqlite3UnlinkAndDeleteIndex(sqlite3
*db
, int iDb
, const char *zIdxName
){
461 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
462 pHash
= &db
->aDb
[iDb
].pSchema
->idxHash
;
463 pIndex
= sqlite3HashInsert(pHash
, zIdxName
, 0);
464 if( ALWAYS(pIndex
) ){
465 if( pIndex
->pTable
->pIndex
==pIndex
){
466 pIndex
->pTable
->pIndex
= pIndex
->pNext
;
469 /* Justification of ALWAYS(); The index must be on the list of
471 p
= pIndex
->pTable
->pIndex
;
472 while( ALWAYS(p
) && p
->pNext
!=pIndex
){ p
= p
->pNext
; }
473 if( ALWAYS(p
&& p
->pNext
==pIndex
) ){
474 p
->pNext
= pIndex
->pNext
;
477 freeIndex(db
, pIndex
);
479 db
->flags
|= SQLITE_InternChanges
;
483 ** Look through the list of open database files in db->aDb[] and if
484 ** any have been closed, remove them from the list. Reallocate the
485 ** db->aDb[] structure to a smaller size, if possible.
487 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
488 ** are never candidates for being collapsed.
490 void sqlite3CollapseDatabaseArray(sqlite3
*db
){
492 for(i
=j
=2; i
<db
->nDb
; i
++){
493 struct Db
*pDb
= &db
->aDb
[i
];
495 sqlite3DbFree(db
, pDb
->zName
);
500 db
->aDb
[j
] = db
->aDb
[i
];
505 if( db
->nDb
<=2 && db
->aDb
!=db
->aDbStatic
){
506 memcpy(db
->aDbStatic
, db
->aDb
, 2*sizeof(db
->aDb
[0]));
507 sqlite3DbFree(db
, db
->aDb
);
508 db
->aDb
= db
->aDbStatic
;
513 ** Reset the schema for the database at index iDb. Also reset the
516 void sqlite3ResetOneSchema(sqlite3
*db
, int iDb
){
518 assert( iDb
<db
->nDb
);
520 /* Case 1: Reset the single schema identified by iDb */
522 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
523 assert( pDb
->pSchema
!=0 );
524 sqlite3SchemaClear(pDb
->pSchema
);
526 /* If any database other than TEMP is reset, then also reset TEMP
527 ** since TEMP might be holding triggers that reference tables in the
532 assert( pDb
->pSchema
!=0 );
533 sqlite3SchemaClear(pDb
->pSchema
);
539 ** Erase all schema information from all attached databases (including
540 ** "main" and "temp") for a single database connection.
542 void sqlite3ResetAllSchemasOfConnection(sqlite3
*db
){
544 sqlite3BtreeEnterAll(db
);
545 for(i
=0; i
<db
->nDb
; i
++){
546 Db
*pDb
= &db
->aDb
[i
];
548 sqlite3SchemaClear(pDb
->pSchema
);
551 db
->flags
&= ~SQLITE_InternChanges
;
552 sqlite3VtabUnlockList(db
);
553 sqlite3BtreeLeaveAll(db
);
554 sqlite3CollapseDatabaseArray(db
);
558 ** This routine is called when a commit occurs.
560 void sqlite3CommitInternalChanges(sqlite3
*db
){
561 db
->flags
&= ~SQLITE_InternChanges
;
565 ** Delete memory allocated for the column names of a table or view (the
566 ** Table.aCol[] array).
568 void sqlite3DeleteColumnNames(sqlite3
*db
, Table
*pTable
){
572 if( (pCol
= pTable
->aCol
)!=0 ){
573 for(i
=0; i
<pTable
->nCol
; i
++, pCol
++){
574 sqlite3DbFree(db
, pCol
->zName
);
575 sqlite3ExprDelete(db
, pCol
->pDflt
);
576 sqlite3DbFree(db
, pCol
->zColl
);
578 sqlite3DbFree(db
, pTable
->aCol
);
583 ** Remove the memory data structures associated with the given
584 ** Table. No changes are made to disk by this routine.
586 ** This routine just deletes the data structure. It does not unlink
587 ** the table data structure from the hash table. But it does destroy
588 ** memory structures of the indices and foreign keys associated with
591 ** The db parameter is optional. It is needed if the Table object
592 ** contains lookaside memory. (Table objects in the schema do not use
593 ** lookaside memory, but some ephemeral Table objects do.) Or the
594 ** db parameter can be used with db->pnBytesFreed to measure the memory
595 ** used by the Table object.
597 static void SQLITE_NOINLINE
deleteTable(sqlite3
*db
, Table
*pTable
){
598 Index
*pIndex
, *pNext
;
599 TESTONLY( int nLookaside
; ) /* Used to verify lookaside not used for schema */
601 /* Record the number of outstanding lookaside allocations in schema Tables
602 ** prior to doing any free() operations. Since schema Tables do not use
603 ** lookaside, this number should not change. */
604 TESTONLY( nLookaside
= (db
&& (pTable
->tabFlags
& TF_Ephemeral
)==0) ?
605 db
->lookaside
.nOut
: 0 );
607 /* Delete all indices associated with this table. */
608 for(pIndex
= pTable
->pIndex
; pIndex
; pIndex
=pNext
){
609 pNext
= pIndex
->pNext
;
610 assert( pIndex
->pSchema
==pTable
->pSchema
611 || (IsVirtual(pTable
) && pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
) );
612 if( (db
==0 || db
->pnBytesFreed
==0) && !IsVirtual(pTable
) ){
613 char *zName
= pIndex
->zName
;
614 TESTONLY ( Index
*pOld
= ) sqlite3HashInsert(
615 &pIndex
->pSchema
->idxHash
, zName
, 0
617 assert( db
==0 || sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
618 assert( pOld
==pIndex
|| pOld
==0 );
620 freeIndex(db
, pIndex
);
623 /* Delete any foreign keys attached to this table. */
624 sqlite3FkDelete(db
, pTable
);
626 /* Delete the Table structure itself.
628 sqlite3DeleteColumnNames(db
, pTable
);
629 sqlite3DbFree(db
, pTable
->zName
);
630 sqlite3DbFree(db
, pTable
->zColAff
);
631 sqlite3SelectDelete(db
, pTable
->pSelect
);
632 sqlite3ExprListDelete(db
, pTable
->pCheck
);
633 #ifndef SQLITE_OMIT_VIRTUALTABLE
634 sqlite3VtabClear(db
, pTable
);
636 sqlite3DbFree(db
, pTable
);
638 /* Verify that no lookaside memory was used by schema tables */
639 assert( nLookaside
==0 || nLookaside
==db
->lookaside
.nOut
);
641 void sqlite3DeleteTable(sqlite3
*db
, Table
*pTable
){
642 /* Do not delete the table until the reference count reaches zero. */
643 if( !pTable
) return;
644 if( ((!db
|| db
->pnBytesFreed
==0) && (--pTable
->nRef
)>0) ) return;
645 deleteTable(db
, pTable
);
650 ** Unlink the given table from the hash tables and the delete the
651 ** table structure with all its indices and foreign keys.
653 void sqlite3UnlinkAndDeleteTable(sqlite3
*db
, int iDb
, const char *zTabName
){
658 assert( iDb
>=0 && iDb
<db
->nDb
);
660 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
661 testcase( zTabName
[0]==0 ); /* Zero-length table names are allowed */
663 p
= sqlite3HashInsert(&pDb
->pSchema
->tblHash
, zTabName
, 0);
664 sqlite3DeleteTable(db
, p
);
665 db
->flags
|= SQLITE_InternChanges
;
669 ** Given a token, return a string that consists of the text of that
670 ** token. Space to hold the returned string
671 ** is obtained from sqliteMalloc() and must be freed by the calling
674 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
675 ** surround the body of the token are removed.
677 ** Tokens are often just pointers into the original SQL text and so
678 ** are not \000 terminated and are not persistent. The returned string
679 ** is \000 terminated and is persistent.
681 char *sqlite3NameFromToken(sqlite3
*db
, Token
*pName
){
684 zName
= sqlite3DbStrNDup(db
, (char*)pName
->z
, pName
->n
);
685 sqlite3Dequote(zName
);
693 ** Open the sqlite_master table stored in database number iDb for
694 ** writing. The table is opened using cursor 0.
696 void sqlite3OpenMasterTable(Parse
*p
, int iDb
){
697 Vdbe
*v
= sqlite3GetVdbe(p
);
698 sqlite3TableLock(p
, iDb
, MASTER_ROOT
, 1, SCHEMA_TABLE(iDb
));
699 sqlite3VdbeAddOp4Int(v
, OP_OpenWrite
, 0, MASTER_ROOT
, iDb
, 5);
706 ** Parameter zName points to a nul-terminated buffer containing the name
707 ** of a database ("main", "temp" or the name of an attached db). This
708 ** function returns the index of the named database in db->aDb[], or
709 ** -1 if the named db cannot be found.
711 int sqlite3FindDbName(sqlite3
*db
, const char *zName
){
712 int i
= -1; /* Database number */
715 for(i
=(db
->nDb
-1), pDb
=&db
->aDb
[i
]; i
>=0; i
--, pDb
--){
716 if( 0==sqlite3StrICmp(pDb
->zName
, zName
) ) break;
723 ** The token *pName contains the name of a database (either "main" or
724 ** "temp" or the name of an attached db). This routine returns the
725 ** index of the named database in db->aDb[], or -1 if the named db
728 int sqlite3FindDb(sqlite3
*db
, Token
*pName
){
729 int i
; /* Database number */
730 char *zName
; /* Name we are searching for */
731 zName
= sqlite3NameFromToken(db
, pName
);
732 i
= sqlite3FindDbName(db
, zName
);
733 sqlite3DbFree(db
, zName
);
737 /* The table or view or trigger name is passed to this routine via tokens
738 ** pName1 and pName2. If the table name was fully qualified, for example:
740 ** CREATE TABLE xxx.yyy (...);
742 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
743 ** the table name is not fully qualified, i.e.:
745 ** CREATE TABLE yyy(...);
747 ** Then pName1 is set to "yyy" and pName2 is "".
749 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
750 ** pName2) that stores the unqualified table name. The index of the
751 ** database "xxx" is returned.
753 int sqlite3TwoPartName(
754 Parse
*pParse
, /* Parsing and code generating context */
755 Token
*pName1
, /* The "xxx" in the name "xxx.yyy" or "xxx" */
756 Token
*pName2
, /* The "yyy" in the name "xxx.yyy" */
757 Token
**pUnqual
/* Write the unqualified object name here */
759 int iDb
; /* Database holding the object */
760 sqlite3
*db
= pParse
->db
;
764 if( db
->init
.busy
) {
765 sqlite3ErrorMsg(pParse
, "corrupt database");
769 iDb
= sqlite3FindDb(db
, pName1
);
771 sqlite3ErrorMsg(pParse
, "unknown database %T", pName1
);
775 assert( db
->init
.iDb
==0 || db
->init
.busy
);
783 ** This routine is used to check if the UTF-8 string zName is a legal
784 ** unqualified name for a new schema object (table, index, view or
785 ** trigger). All names are legal except those that begin with the string
786 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
787 ** is reserved for internal use.
789 int sqlite3CheckObjectName(Parse
*pParse
, const char *zName
){
790 if( !pParse
->db
->init
.busy
&& pParse
->nested
==0
791 && (pParse
->db
->flags
& SQLITE_WriteSchema
)==0
792 && 0==sqlite3StrNICmp(zName
, "sqlite_", 7) ){
793 sqlite3ErrorMsg(pParse
, "object name reserved for internal use: %s", zName
);
800 ** Return the PRIMARY KEY index of a table
802 Index
*sqlite3PrimaryKeyIndex(Table
*pTab
){
804 for(p
=pTab
->pIndex
; p
&& !IsPrimaryKeyIndex(p
); p
=p
->pNext
){}
809 ** Return the column of index pIdx that corresponds to table
810 ** column iCol. Return -1 if not found.
812 i16
sqlite3ColumnOfIndex(Index
*pIdx
, i16 iCol
){
814 for(i
=0; i
<pIdx
->nColumn
; i
++){
815 if( iCol
==pIdx
->aiColumn
[i
] ) return i
;
821 ** Begin constructing a new table representation in memory. This is
822 ** the first of several action routines that get called in response
823 ** to a CREATE TABLE statement. In particular, this routine is called
824 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
825 ** flag is true if the table should be stored in the auxiliary database
826 ** file instead of in the main database file. This is normally the case
827 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
830 ** The new table record is initialized and put in pParse->pNewTable.
831 ** As more of the CREATE TABLE statement is parsed, additional action
832 ** routines will be called to add more information to this record.
833 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
834 ** is called to complete the construction of the new table record.
836 void sqlite3StartTable(
837 Parse
*pParse
, /* Parser context */
838 Token
*pName1
, /* First part of the name of the table or view */
839 Token
*pName2
, /* Second part of the name of the table or view */
840 int isTemp
, /* True if this is a TEMP table */
841 int isView
, /* True if this is a VIEW */
842 int isVirtual
, /* True if this is a VIRTUAL table */
843 int noErr
/* Do nothing if table already exists */
846 char *zName
= 0; /* The name of the new table */
847 sqlite3
*db
= pParse
->db
;
849 int iDb
; /* Database number to create the table in */
850 Token
*pName
; /* Unqualified name of the table to create */
852 if( db
->init
.busy
&& db
->init
.newTnum
==1 ){
853 /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
855 zName
= sqlite3DbStrDup(db
, SCHEMA_TABLE(iDb
));
858 /* The common case */
859 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
861 if( !OMIT_TEMPDB
&& isTemp
&& pName2
->n
>0 && iDb
!=1 ){
862 /* If creating a temp table, the name may not be qualified. Unless
863 ** the database name is "temp" anyway. */
864 sqlite3ErrorMsg(pParse
, "temporary table name must be unqualified");
867 if( !OMIT_TEMPDB
&& isTemp
) iDb
= 1;
868 zName
= sqlite3NameFromToken(db
, pName
);
870 pParse
->sNameToken
= *pName
;
871 if( zName
==0 ) return;
872 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
) ){
873 goto begin_table_error
;
875 if( db
->init
.iDb
==1 ) isTemp
= 1;
876 #ifndef SQLITE_OMIT_AUTHORIZATION
877 assert( isTemp
==0 || isTemp
==1 );
878 assert( isView
==0 || isView
==1 );
880 static const u8 aCode
[] = {
882 SQLITE_CREATE_TEMP_TABLE
,
884 SQLITE_CREATE_TEMP_VIEW
886 char *zDb
= db
->aDb
[iDb
].zName
;
887 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(isTemp
), 0, zDb
) ){
888 goto begin_table_error
;
890 if( !isVirtual
&& sqlite3AuthCheck(pParse
, (int)aCode
[isTemp
+2*isView
],
892 goto begin_table_error
;
897 /* Make sure the new table name does not collide with an existing
898 ** index or table name in the same database. Issue an error message if
899 ** it does. The exception is if the statement being parsed was passed
900 ** to an sqlite3_declare_vtab() call. In that case only the column names
901 ** and types will be used, so there is no need to test for namespace
904 if( !IN_DECLARE_VTAB
){
905 char *zDb
= db
->aDb
[iDb
].zName
;
906 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
907 goto begin_table_error
;
909 pTable
= sqlite3FindTable(db
, zName
, zDb
);
912 sqlite3ErrorMsg(pParse
, "table %T already exists", pName
);
914 assert( !db
->init
.busy
|| CORRUPT_DB
);
915 sqlite3CodeVerifySchema(pParse
, iDb
);
917 goto begin_table_error
;
919 if( sqlite3FindIndex(db
, zName
, zDb
)!=0 ){
920 sqlite3ErrorMsg(pParse
, "there is already an index named %s", zName
);
921 goto begin_table_error
;
925 pTable
= sqlite3DbMallocZero(db
, sizeof(Table
));
927 assert( db
->mallocFailed
);
928 pParse
->rc
= SQLITE_NOMEM_BKPT
;
930 goto begin_table_error
;
932 pTable
->zName
= zName
;
934 pTable
->pSchema
= db
->aDb
[iDb
].pSchema
;
936 pTable
->nRowLogEst
= 200; assert( 200==sqlite3LogEst(1048576) );
937 assert( pParse
->pNewTable
==0 );
938 pParse
->pNewTable
= pTable
;
940 /* If this is the magic sqlite_sequence table used by autoincrement,
941 ** then record a pointer to this table in the main database structure
942 ** so that INSERT can find the table easily.
944 #ifndef SQLITE_OMIT_AUTOINCREMENT
945 if( !pParse
->nested
&& strcmp(zName
, "sqlite_sequence")==0 ){
946 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
947 pTable
->pSchema
->pSeqTab
= pTable
;
951 /* Begin generating the code that will insert the table record into
952 ** the SQLITE_MASTER table. Note in particular that we must go ahead
953 ** and allocate the record number for the table entry now. Before any
954 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
955 ** indices to be created and the table record must come before the
956 ** indices. Hence, the record number for the table must be allocated
959 if( !db
->init
.busy
&& (v
= sqlite3GetVdbe(pParse
))!=0 ){
962 int reg1
, reg2
, reg3
;
963 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
964 static const char nullRow
[] = { 6, 0, 0, 0, 0, 0 };
965 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
967 #ifndef SQLITE_OMIT_VIRTUALTABLE
969 sqlite3VdbeAddOp0(v
, OP_VBegin
);
973 /* If the file format and encoding in the database have not been set,
976 reg1
= pParse
->regRowid
= ++pParse
->nMem
;
977 reg2
= pParse
->regRoot
= ++pParse
->nMem
;
978 reg3
= ++pParse
->nMem
;
979 sqlite3VdbeAddOp3(v
, OP_ReadCookie
, iDb
, reg3
, BTREE_FILE_FORMAT
);
980 sqlite3VdbeUsesBtree(v
, iDb
);
981 addr1
= sqlite3VdbeAddOp1(v
, OP_If
, reg3
); VdbeCoverage(v
);
982 fileFormat
= (db
->flags
& SQLITE_LegacyFileFmt
)!=0 ?
983 1 : SQLITE_MAX_FILE_FORMAT
;
984 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_FILE_FORMAT
, fileFormat
);
985 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_TEXT_ENCODING
, ENC(db
));
986 sqlite3VdbeJumpHere(v
, addr1
);
988 /* This just creates a place-holder record in the sqlite_master table.
989 ** The record created does not contain anything yet. It will be replaced
990 ** by the real entry in code generated at sqlite3EndTable().
992 ** The rowid for the new entry is left in register pParse->regRowid.
993 ** The root page number of the new table is left in reg pParse->regRoot.
994 ** The rowid and root page number values are needed by the code that
995 ** sqlite3EndTable will generate.
997 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
998 if( isView
|| isVirtual
){
999 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, reg2
);
1003 pParse
->addrCrTab
= sqlite3VdbeAddOp2(v
, OP_CreateTable
, iDb
, reg2
);
1005 sqlite3OpenMasterTable(pParse
, iDb
);
1006 sqlite3VdbeAddOp2(v
, OP_NewRowid
, 0, reg1
);
1007 sqlite3VdbeAddOp4(v
, OP_Blob
, 6, reg3
, 0, nullRow
, P4_STATIC
);
1008 sqlite3VdbeAddOp3(v
, OP_Insert
, 0, reg3
, reg1
);
1009 sqlite3VdbeChangeP5(v
, OPFLAG_APPEND
);
1010 sqlite3VdbeAddOp0(v
, OP_Close
);
1013 /* Normal (non-error) return. */
1016 /* If an error occurs, we jump here */
1018 sqlite3DbFree(db
, zName
);
1022 /* Set properties of a table column based on the (magical)
1023 ** name of the column.
1025 #if SQLITE_ENABLE_HIDDEN_COLUMNS
1026 void sqlite3ColumnPropertiesFromName(Table
*pTab
, Column
*pCol
){
1027 if( sqlite3_strnicmp(pCol
->zName
, "__hidden__", 10)==0 ){
1028 pCol
->colFlags
|= COLFLAG_HIDDEN
;
1029 }else if( pTab
&& pCol
!=pTab
->aCol
&& (pCol
[-1].colFlags
& COLFLAG_HIDDEN
) ){
1030 pTab
->tabFlags
|= TF_OOOHidden
;
1037 ** Add a new column to the table currently being constructed.
1039 ** The parser calls this routine once for each column declaration
1040 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1041 ** first to get things going. Then this routine is called for each
1044 void sqlite3AddColumn(Parse
*pParse
, Token
*pName
, Token
*pType
){
1050 sqlite3
*db
= pParse
->db
;
1051 if( (p
= pParse
->pNewTable
)==0 ) return;
1052 #if SQLITE_MAX_COLUMN
1053 if( p
->nCol
+1>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1054 sqlite3ErrorMsg(pParse
, "too many columns on %s", p
->zName
);
1058 z
= sqlite3DbMallocRaw(db
, pName
->n
+ pType
->n
+ 2);
1060 memcpy(z
, pName
->z
, pName
->n
);
1063 for(i
=0; i
<p
->nCol
; i
++){
1064 if( sqlite3_stricmp(z
, p
->aCol
[i
].zName
)==0 ){
1065 sqlite3ErrorMsg(pParse
, "duplicate column name: %s", z
);
1066 sqlite3DbFree(db
, z
);
1070 if( (p
->nCol
& 0x7)==0 ){
1072 aNew
= sqlite3DbRealloc(db
,p
->aCol
,(p
->nCol
+8)*sizeof(p
->aCol
[0]));
1074 sqlite3DbFree(db
, z
);
1079 pCol
= &p
->aCol
[p
->nCol
];
1080 memset(pCol
, 0, sizeof(p
->aCol
[0]));
1082 sqlite3ColumnPropertiesFromName(p
, pCol
);
1085 /* If there is no type specified, columns have the default affinity
1087 pCol
->affinity
= SQLITE_AFF_BLOB
;
1090 zType
= z
+ sqlite3Strlen30(z
) + 1;
1091 memcpy(zType
, pType
->z
, pType
->n
);
1092 zType
[pType
->n
] = 0;
1093 sqlite3Dequote(zType
);
1094 pCol
->affinity
= sqlite3AffinityType(zType
, &pCol
->szEst
);
1095 pCol
->colFlags
|= COLFLAG_HASTYPE
;
1098 pParse
->constraintName
.n
= 0;
1102 ** This routine is called by the parser while in the middle of
1103 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1104 ** been seen on a column. This routine sets the notNull flag on
1105 ** the column currently under construction.
1107 void sqlite3AddNotNull(Parse
*pParse
, int onError
){
1109 p
= pParse
->pNewTable
;
1110 if( p
==0 || NEVER(p
->nCol
<1) ) return;
1111 p
->aCol
[p
->nCol
-1].notNull
= (u8
)onError
;
1115 ** Scan the column type name zType (length nType) and return the
1116 ** associated affinity type.
1118 ** This routine does a case-independent search of zType for the
1119 ** substrings in the following table. If one of the substrings is
1120 ** found, the corresponding affinity is returned. If zType contains
1121 ** more than one of the substrings, entries toward the top of
1122 ** the table take priority. For example, if zType is 'BLOBINT',
1123 ** SQLITE_AFF_INTEGER is returned.
1125 ** Substring | Affinity
1126 ** --------------------------------
1127 ** 'INT' | SQLITE_AFF_INTEGER
1128 ** 'CHAR' | SQLITE_AFF_TEXT
1129 ** 'CLOB' | SQLITE_AFF_TEXT
1130 ** 'TEXT' | SQLITE_AFF_TEXT
1131 ** 'BLOB' | SQLITE_AFF_BLOB
1132 ** 'REAL' | SQLITE_AFF_REAL
1133 ** 'FLOA' | SQLITE_AFF_REAL
1134 ** 'DOUB' | SQLITE_AFF_REAL
1136 ** If none of the substrings in the above table are found,
1137 ** SQLITE_AFF_NUMERIC is returned.
1139 char sqlite3AffinityType(const char *zIn
, u8
*pszEst
){
1141 char aff
= SQLITE_AFF_NUMERIC
;
1142 const char *zChar
= 0;
1146 h
= (h
<<8) + sqlite3UpperToLower
[(*zIn
)&0xff];
1148 if( h
==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1149 aff
= SQLITE_AFF_TEXT
;
1151 }else if( h
==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1152 aff
= SQLITE_AFF_TEXT
;
1153 }else if( h
==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1154 aff
= SQLITE_AFF_TEXT
;
1155 }else if( h
==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1156 && (aff
==SQLITE_AFF_NUMERIC
|| aff
==SQLITE_AFF_REAL
) ){
1157 aff
= SQLITE_AFF_BLOB
;
1158 if( zIn
[0]=='(' ) zChar
= zIn
;
1159 #ifndef SQLITE_OMIT_FLOATING_POINT
1160 }else if( h
==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1161 && aff
==SQLITE_AFF_NUMERIC
){
1162 aff
= SQLITE_AFF_REAL
;
1163 }else if( h
==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1164 && aff
==SQLITE_AFF_NUMERIC
){
1165 aff
= SQLITE_AFF_REAL
;
1166 }else if( h
==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1167 && aff
==SQLITE_AFF_NUMERIC
){
1168 aff
= SQLITE_AFF_REAL
;
1170 }else if( (h
&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1171 aff
= SQLITE_AFF_INTEGER
;
1176 /* If pszEst is not NULL, store an estimate of the field size. The
1177 ** estimate is scaled so that the size of an integer is 1. */
1179 *pszEst
= 1; /* default size is approx 4 bytes */
1180 if( aff
<SQLITE_AFF_NUMERIC
){
1183 if( sqlite3Isdigit(zChar
[0]) ){
1185 sqlite3GetInt32(zChar
, &v
);
1187 if( v
>255 ) v
= 255;
1188 *pszEst
= v
; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1194 *pszEst
= 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1202 ** The expression is the default value for the most recently added column
1203 ** of the table currently under construction.
1205 ** Default value expressions must be constant. Raise an exception if this
1208 ** This routine is called by the parser while in the middle of
1209 ** parsing a CREATE TABLE statement.
1211 void sqlite3AddDefaultValue(Parse
*pParse
, ExprSpan
*pSpan
){
1214 sqlite3
*db
= pParse
->db
;
1215 p
= pParse
->pNewTable
;
1217 pCol
= &(p
->aCol
[p
->nCol
-1]);
1218 if( !sqlite3ExprIsConstantOrFunction(pSpan
->pExpr
, db
->init
.busy
) ){
1219 sqlite3ErrorMsg(pParse
, "default value of column [%s] is not constant",
1222 /* A copy of pExpr is used instead of the original, as pExpr contains
1223 ** tokens that point to volatile memory. The 'span' of the expression
1224 ** is required by pragma table_info.
1227 sqlite3ExprDelete(db
, pCol
->pDflt
);
1228 memset(&x
, 0, sizeof(x
));
1230 x
.u
.zToken
= sqlite3DbStrNDup(db
, (char*)pSpan
->zStart
,
1231 (int)(pSpan
->zEnd
- pSpan
->zStart
));
1232 x
.pLeft
= pSpan
->pExpr
;
1234 pCol
->pDflt
= sqlite3ExprDup(db
, &x
, EXPRDUP_REDUCE
);
1235 sqlite3DbFree(db
, x
.u
.zToken
);
1238 sqlite3ExprDelete(db
, pSpan
->pExpr
);
1242 ** Backwards Compatibility Hack:
1244 ** Historical versions of SQLite accepted strings as column names in
1245 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1247 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1248 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1250 ** This is goofy. But to preserve backwards compatibility we continue to
1251 ** accept it. This routine does the necessary conversion. It converts
1252 ** the expression given in its argument from a TK_STRING into a TK_ID
1253 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1254 ** If the epxression is anything other than TK_STRING, the expression is
1257 static void sqlite3StringToId(Expr
*p
){
1258 if( p
->op
==TK_STRING
){
1260 }else if( p
->op
==TK_COLLATE
&& p
->pLeft
->op
==TK_STRING
){
1261 p
->pLeft
->op
= TK_ID
;
1266 ** Designate the PRIMARY KEY for the table. pList is a list of names
1267 ** of columns that form the primary key. If pList is NULL, then the
1268 ** most recently added column of the table is the primary key.
1270 ** A table can have at most one primary key. If the table already has
1271 ** a primary key (and this is the second primary key) then create an
1274 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1275 ** then we will try to use that column as the rowid. Set the Table.iPKey
1276 ** field of the table under construction to be the index of the
1277 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1278 ** no INTEGER PRIMARY KEY.
1280 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1281 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1283 void sqlite3AddPrimaryKey(
1284 Parse
*pParse
, /* Parsing context */
1285 ExprList
*pList
, /* List of field names to be indexed */
1286 int onError
, /* What to do with a uniqueness conflict */
1287 int autoInc
, /* True if the AUTOINCREMENT keyword is present */
1288 int sortOrder
/* SQLITE_SO_ASC or SQLITE_SO_DESC */
1290 Table
*pTab
= pParse
->pNewTable
;
1294 if( pTab
==0 ) goto primary_key_exit
;
1295 if( pTab
->tabFlags
& TF_HasPrimaryKey
){
1296 sqlite3ErrorMsg(pParse
,
1297 "table \"%s\" has more than one primary key", pTab
->zName
);
1298 goto primary_key_exit
;
1300 pTab
->tabFlags
|= TF_HasPrimaryKey
;
1302 iCol
= pTab
->nCol
- 1;
1303 pCol
= &pTab
->aCol
[iCol
];
1304 pCol
->colFlags
|= COLFLAG_PRIMKEY
;
1307 nTerm
= pList
->nExpr
;
1308 for(i
=0; i
<nTerm
; i
++){
1309 Expr
*pCExpr
= sqlite3ExprSkipCollate(pList
->a
[i
].pExpr
);
1310 assert( pCExpr
!=0 );
1311 sqlite3StringToId(pCExpr
);
1312 if( pCExpr
->op
==TK_ID
){
1313 const char *zCName
= pCExpr
->u
.zToken
;
1314 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
1315 if( sqlite3StrICmp(zCName
, pTab
->aCol
[iCol
].zName
)==0 ){
1316 pCol
= &pTab
->aCol
[iCol
];
1317 pCol
->colFlags
|= COLFLAG_PRIMKEY
;
1326 && sqlite3StrICmp(sqlite3ColumnType(pCol
,""), "INTEGER")==0
1327 && sortOrder
!=SQLITE_SO_DESC
1330 pTab
->keyConf
= (u8
)onError
;
1331 assert( autoInc
==0 || autoInc
==1 );
1332 pTab
->tabFlags
|= autoInc
*TF_Autoincrement
;
1333 if( pList
) pParse
->iPkSortOrder
= pList
->a
[0].sortOrder
;
1334 }else if( autoInc
){
1335 #ifndef SQLITE_OMIT_AUTOINCREMENT
1336 sqlite3ErrorMsg(pParse
, "AUTOINCREMENT is only allowed on an "
1337 "INTEGER PRIMARY KEY");
1340 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, onError
, 0,
1341 0, sortOrder
, 0, SQLITE_IDXTYPE_PRIMARYKEY
);
1346 sqlite3ExprListDelete(pParse
->db
, pList
);
1351 ** Add a new CHECK constraint to the table currently under construction.
1353 void sqlite3AddCheckConstraint(
1354 Parse
*pParse
, /* Parsing context */
1355 Expr
*pCheckExpr
/* The check expression */
1357 #ifndef SQLITE_OMIT_CHECK
1358 Table
*pTab
= pParse
->pNewTable
;
1359 sqlite3
*db
= pParse
->db
;
1360 if( pTab
&& !IN_DECLARE_VTAB
1361 && !sqlite3BtreeIsReadonly(db
->aDb
[db
->init
.iDb
].pBt
)
1363 pTab
->pCheck
= sqlite3ExprListAppend(pParse
, pTab
->pCheck
, pCheckExpr
);
1364 if( pParse
->constraintName
.n
){
1365 sqlite3ExprListSetName(pParse
, pTab
->pCheck
, &pParse
->constraintName
, 1);
1370 sqlite3ExprDelete(pParse
->db
, pCheckExpr
);
1375 ** Set the collation function of the most recently parsed table column
1376 ** to the CollSeq given.
1378 void sqlite3AddCollateType(Parse
*pParse
, Token
*pToken
){
1381 char *zColl
; /* Dequoted name of collation sequence */
1384 if( (p
= pParse
->pNewTable
)==0 ) return;
1387 zColl
= sqlite3NameFromToken(db
, pToken
);
1388 if( !zColl
) return;
1390 if( sqlite3LocateCollSeq(pParse
, zColl
) ){
1392 sqlite3DbFree(db
, p
->aCol
[i
].zColl
);
1393 p
->aCol
[i
].zColl
= zColl
;
1395 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1396 ** then an index may have been created on this column before the
1397 ** collation type was added. Correct this if it is the case.
1399 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1400 assert( pIdx
->nKeyCol
==1 );
1401 if( pIdx
->aiColumn
[0]==i
){
1402 pIdx
->azColl
[0] = p
->aCol
[i
].zColl
;
1406 sqlite3DbFree(db
, zColl
);
1411 ** This function returns the collation sequence for database native text
1412 ** encoding identified by the string zName, length nName.
1414 ** If the requested collation sequence is not available, or not available
1415 ** in the database native encoding, the collation factory is invoked to
1416 ** request it. If the collation factory does not supply such a sequence,
1417 ** and the sequence is available in another text encoding, then that is
1418 ** returned instead.
1420 ** If no versions of the requested collations sequence are available, or
1421 ** another error occurs, NULL is returned and an error message written into
1424 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1425 ** invokes the collation factory if the named collation cannot be found
1426 ** and generates an error message.
1428 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1430 CollSeq
*sqlite3LocateCollSeq(Parse
*pParse
, const char *zName
){
1431 sqlite3
*db
= pParse
->db
;
1433 u8 initbusy
= db
->init
.busy
;
1436 pColl
= sqlite3FindCollSeq(db
, enc
, zName
, initbusy
);
1437 if( !initbusy
&& (!pColl
|| !pColl
->xCmp
) ){
1438 pColl
= sqlite3GetCollSeq(pParse
, enc
, pColl
, zName
);
1446 ** Generate code that will increment the schema cookie.
1448 ** The schema cookie is used to determine when the schema for the
1449 ** database changes. After each schema change, the cookie value
1450 ** changes. When a process first reads the schema it records the
1451 ** cookie. Thereafter, whenever it goes to access the database,
1452 ** it checks the cookie to make sure the schema has not changed
1453 ** since it was last read.
1455 ** This plan is not completely bullet-proof. It is possible for
1456 ** the schema to change multiple times and for the cookie to be
1457 ** set back to prior value. But schema changes are infrequent
1458 ** and the probability of hitting the same cookie value is only
1459 ** 1 chance in 2^32. So we're safe enough.
1461 void sqlite3ChangeCookie(Parse
*pParse
, int iDb
){
1462 sqlite3
*db
= pParse
->db
;
1463 Vdbe
*v
= pParse
->pVdbe
;
1464 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
1465 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_SCHEMA_VERSION
,
1466 db
->aDb
[iDb
].pSchema
->schema_cookie
+1);
1470 ** Measure the number of characters needed to output the given
1471 ** identifier. The number returned includes any quotes used
1472 ** but does not include the null terminator.
1474 ** The estimate is conservative. It might be larger that what is
1477 static int identLength(const char *z
){
1479 for(n
=0; *z
; n
++, z
++){
1480 if( *z
=='"' ){ n
++; }
1486 ** The first parameter is a pointer to an output buffer. The second
1487 ** parameter is a pointer to an integer that contains the offset at
1488 ** which to write into the output buffer. This function copies the
1489 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1490 ** to the specified offset in the buffer and updates *pIdx to refer
1491 ** to the first byte after the last byte written before returning.
1493 ** If the string zSignedIdent consists entirely of alpha-numeric
1494 ** characters, does not begin with a digit and is not an SQL keyword,
1495 ** then it is copied to the output buffer exactly as it is. Otherwise,
1496 ** it is quoted using double-quotes.
1498 static void identPut(char *z
, int *pIdx
, char *zSignedIdent
){
1499 unsigned char *zIdent
= (unsigned char*)zSignedIdent
;
1500 int i
, j
, needQuote
;
1503 for(j
=0; zIdent
[j
]; j
++){
1504 if( !sqlite3Isalnum(zIdent
[j
]) && zIdent
[j
]!='_' ) break;
1506 needQuote
= sqlite3Isdigit(zIdent
[0])
1507 || sqlite3KeywordCode(zIdent
, j
)!=TK_ID
1511 if( needQuote
) z
[i
++] = '"';
1512 for(j
=0; zIdent
[j
]; j
++){
1514 if( zIdent
[j
]=='"' ) z
[i
++] = '"';
1516 if( needQuote
) z
[i
++] = '"';
1522 ** Generate a CREATE TABLE statement appropriate for the given
1523 ** table. Memory to hold the text of the statement is obtained
1524 ** from sqliteMalloc() and must be freed by the calling function.
1526 static char *createTableStmt(sqlite3
*db
, Table
*p
){
1529 char *zSep
, *zSep2
, *zEnd
;
1532 for(pCol
= p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
1533 n
+= identLength(pCol
->zName
) + 5;
1535 n
+= identLength(p
->zName
);
1545 n
+= 35 + 6*p
->nCol
;
1546 zStmt
= sqlite3DbMallocRaw(0, n
);
1548 sqlite3OomFault(db
);
1551 sqlite3_snprintf(n
, zStmt
, "CREATE TABLE ");
1552 k
= sqlite3Strlen30(zStmt
);
1553 identPut(zStmt
, &k
, p
->zName
);
1555 for(pCol
=p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
1556 static const char * const azType
[] = {
1557 /* SQLITE_AFF_BLOB */ "",
1558 /* SQLITE_AFF_TEXT */ " TEXT",
1559 /* SQLITE_AFF_NUMERIC */ " NUM",
1560 /* SQLITE_AFF_INTEGER */ " INT",
1561 /* SQLITE_AFF_REAL */ " REAL"
1566 sqlite3_snprintf(n
-k
, &zStmt
[k
], zSep
);
1567 k
+= sqlite3Strlen30(&zStmt
[k
]);
1569 identPut(zStmt
, &k
, pCol
->zName
);
1570 assert( pCol
->affinity
-SQLITE_AFF_BLOB
>= 0 );
1571 assert( pCol
->affinity
-SQLITE_AFF_BLOB
< ArraySize(azType
) );
1572 testcase( pCol
->affinity
==SQLITE_AFF_BLOB
);
1573 testcase( pCol
->affinity
==SQLITE_AFF_TEXT
);
1574 testcase( pCol
->affinity
==SQLITE_AFF_NUMERIC
);
1575 testcase( pCol
->affinity
==SQLITE_AFF_INTEGER
);
1576 testcase( pCol
->affinity
==SQLITE_AFF_REAL
);
1578 zType
= azType
[pCol
->affinity
- SQLITE_AFF_BLOB
];
1579 len
= sqlite3Strlen30(zType
);
1580 assert( pCol
->affinity
==SQLITE_AFF_BLOB
1581 || pCol
->affinity
==sqlite3AffinityType(zType
, 0) );
1582 memcpy(&zStmt
[k
], zType
, len
);
1586 sqlite3_snprintf(n
-k
, &zStmt
[k
], "%s", zEnd
);
1591 ** Resize an Index object to hold N columns total. Return SQLITE_OK
1592 ** on success and SQLITE_NOMEM on an OOM error.
1594 static int resizeIndexObject(sqlite3
*db
, Index
*pIdx
, int N
){
1597 if( pIdx
->nColumn
>=N
) return SQLITE_OK
;
1598 assert( pIdx
->isResized
==0 );
1599 nByte
= (sizeof(char*) + sizeof(i16
) + 1)*N
;
1600 zExtra
= sqlite3DbMallocZero(db
, nByte
);
1601 if( zExtra
==0 ) return SQLITE_NOMEM_BKPT
;
1602 memcpy(zExtra
, pIdx
->azColl
, sizeof(char*)*pIdx
->nColumn
);
1603 pIdx
->azColl
= (const char**)zExtra
;
1604 zExtra
+= sizeof(char*)*N
;
1605 memcpy(zExtra
, pIdx
->aiColumn
, sizeof(i16
)*pIdx
->nColumn
);
1606 pIdx
->aiColumn
= (i16
*)zExtra
;
1607 zExtra
+= sizeof(i16
)*N
;
1608 memcpy(zExtra
, pIdx
->aSortOrder
, pIdx
->nColumn
);
1609 pIdx
->aSortOrder
= (u8
*)zExtra
;
1611 pIdx
->isResized
= 1;
1616 ** Estimate the total row width for a table.
1618 static void estimateTableWidth(Table
*pTab
){
1619 unsigned wTable
= 0;
1620 const Column
*pTabCol
;
1622 for(i
=pTab
->nCol
, pTabCol
=pTab
->aCol
; i
>0; i
--, pTabCol
++){
1623 wTable
+= pTabCol
->szEst
;
1625 if( pTab
->iPKey
<0 ) wTable
++;
1626 pTab
->szTabRow
= sqlite3LogEst(wTable
*4);
1630 ** Estimate the average size of a row for an index.
1632 static void estimateIndexWidth(Index
*pIdx
){
1633 unsigned wIndex
= 0;
1635 const Column
*aCol
= pIdx
->pTable
->aCol
;
1636 for(i
=0; i
<pIdx
->nColumn
; i
++){
1637 i16 x
= pIdx
->aiColumn
[i
];
1638 assert( x
<pIdx
->pTable
->nCol
);
1639 wIndex
+= x
<0 ? 1 : aCol
[pIdx
->aiColumn
[i
]].szEst
;
1641 pIdx
->szIdxRow
= sqlite3LogEst(wIndex
*4);
1644 /* Return true if value x is found any of the first nCol entries of aiCol[]
1646 static int hasColumn(const i16
*aiCol
, int nCol
, int x
){
1647 while( nCol
-- > 0 ) if( x
==*(aiCol
++) ) return 1;
1652 ** This routine runs at the end of parsing a CREATE TABLE statement that
1653 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
1654 ** internal schema data structures and the generated VDBE code so that they
1655 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1658 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1659 ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is
1660 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1661 ** data storage is a covering index btree.
1662 ** (3) Bypass the creation of the sqlite_master table entry
1663 ** for the PRIMARY KEY as the primary key index is now
1664 ** identified by the sqlite_master table entry of the table itself.
1665 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
1666 ** schema to the rootpage from the main table.
1667 ** (5) Add all table columns to the PRIMARY KEY Index object
1668 ** so that the PRIMARY KEY is a covering index. The surplus
1669 ** columns are part of KeyInfo.nXField and are not used for
1670 ** sorting or lookup or uniqueness checks.
1671 ** (6) Replace the rowid tail on all automatically generated UNIQUE
1672 ** indices with the PRIMARY KEY columns.
1674 ** For virtual tables, only (1) is performed.
1676 static void convertToWithoutRowidTable(Parse
*pParse
, Table
*pTab
){
1681 sqlite3
*db
= pParse
->db
;
1682 Vdbe
*v
= pParse
->pVdbe
;
1684 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
1686 if( !db
->init
.imposterTable
){
1687 for(i
=0; i
<pTab
->nCol
; i
++){
1688 if( (pTab
->aCol
[i
].colFlags
& COLFLAG_PRIMKEY
)!=0 ){
1689 pTab
->aCol
[i
].notNull
= OE_Abort
;
1694 /* The remaining transformations only apply to b-tree tables, not to
1695 ** virtual tables */
1696 if( IN_DECLARE_VTAB
) return;
1698 /* Convert the OP_CreateTable opcode that would normally create the
1699 ** root-page for the table into an OP_CreateIndex opcode. The index
1700 ** created will become the PRIMARY KEY index.
1702 if( pParse
->addrCrTab
){
1704 sqlite3VdbeChangeOpcode(v
, pParse
->addrCrTab
, OP_CreateIndex
);
1707 /* Locate the PRIMARY KEY index. Or, if this table was originally
1708 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1710 if( pTab
->iPKey
>=0 ){
1713 sqlite3TokenInit(&ipkToken
, pTab
->aCol
[pTab
->iPKey
].zName
);
1714 pList
= sqlite3ExprListAppend(pParse
, 0,
1715 sqlite3ExprAlloc(db
, TK_ID
, &ipkToken
, 0));
1716 if( pList
==0 ) return;
1717 pList
->a
[0].sortOrder
= pParse
->iPkSortOrder
;
1718 assert( pParse
->pNewTable
==pTab
);
1719 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, pTab
->keyConf
, 0, 0, 0, 0,
1720 SQLITE_IDXTYPE_PRIMARYKEY
);
1721 if( db
->mallocFailed
) return;
1722 pPk
= sqlite3PrimaryKeyIndex(pTab
);
1725 pPk
= sqlite3PrimaryKeyIndex(pTab
);
1727 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1728 ** table entry. This is only required if currently generating VDBE
1729 ** code for a CREATE TABLE (not when parsing one as part of reading
1730 ** a database schema). */
1732 assert( db
->init
.busy
==0 );
1733 sqlite3VdbeChangeOpcode(v
, pPk
->tnum
, OP_Goto
);
1737 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1738 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1739 ** code assumes the PRIMARY KEY contains no repeated columns.
1741 for(i
=j
=1; i
<pPk
->nKeyCol
; i
++){
1742 if( hasColumn(pPk
->aiColumn
, j
, pPk
->aiColumn
[i
]) ){
1745 pPk
->aiColumn
[j
++] = pPk
->aiColumn
[i
];
1751 pPk
->isCovering
= 1;
1752 if( !db
->init
.imposterTable
) pPk
->uniqNotNull
= 1;
1755 /* The root page of the PRIMARY KEY is the table root page */
1756 pPk
->tnum
= pTab
->tnum
;
1758 /* Update the in-memory representation of all UNIQUE indices by converting
1759 ** the final rowid column into one or more columns of the PRIMARY KEY.
1761 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1763 if( IsPrimaryKeyIndex(pIdx
) ) continue;
1764 for(i
=n
=0; i
<nPk
; i
++){
1765 if( !hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) ) n
++;
1768 /* This index is a superset of the primary key */
1769 pIdx
->nColumn
= pIdx
->nKeyCol
;
1772 if( resizeIndexObject(db
, pIdx
, pIdx
->nKeyCol
+n
) ) return;
1773 for(i
=0, j
=pIdx
->nKeyCol
; i
<nPk
; i
++){
1774 if( !hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) ){
1775 pIdx
->aiColumn
[j
] = pPk
->aiColumn
[i
];
1776 pIdx
->azColl
[j
] = pPk
->azColl
[i
];
1780 assert( pIdx
->nColumn
>=pIdx
->nKeyCol
+n
);
1781 assert( pIdx
->nColumn
>=j
);
1784 /* Add all table columns to the PRIMARY KEY index
1786 if( nPk
<pTab
->nCol
){
1787 if( resizeIndexObject(db
, pPk
, pTab
->nCol
) ) return;
1788 for(i
=0, j
=nPk
; i
<pTab
->nCol
; i
++){
1789 if( !hasColumn(pPk
->aiColumn
, j
, i
) ){
1790 assert( j
<pPk
->nColumn
);
1791 pPk
->aiColumn
[j
] = i
;
1792 pPk
->azColl
[j
] = sqlite3StrBINARY
;
1796 assert( pPk
->nColumn
==j
);
1797 assert( pTab
->nCol
==j
);
1799 pPk
->nColumn
= pTab
->nCol
;
1804 ** This routine is called to report the final ")" that terminates
1805 ** a CREATE TABLE statement.
1807 ** The table structure that other action routines have been building
1808 ** is added to the internal hash tables, assuming no errors have
1811 ** An entry for the table is made in the master table on disk, unless
1812 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1813 ** it means we are reading the sqlite_master table because we just
1814 ** connected to the database or because the sqlite_master table has
1815 ** recently changed, so the entry for this table already exists in
1816 ** the sqlite_master table. We do not want to create it again.
1818 ** If the pSelect argument is not NULL, it means that this routine
1819 ** was called to create a table generated from a
1820 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1821 ** the new table will match the result set of the SELECT.
1823 void sqlite3EndTable(
1824 Parse
*pParse
, /* Parse context */
1825 Token
*pCons
, /* The ',' token after the last column defn. */
1826 Token
*pEnd
, /* The ')' before options in the CREATE TABLE */
1827 u8 tabOpts
, /* Extra table options. Usually 0. */
1828 Select
*pSelect
/* Select from a "CREATE ... AS SELECT" */
1830 Table
*p
; /* The new table */
1831 sqlite3
*db
= pParse
->db
; /* The database connection */
1832 int iDb
; /* Database in which the table lives */
1833 Index
*pIdx
; /* An implied index of the table */
1835 if( pEnd
==0 && pSelect
==0 ){
1838 assert( !db
->mallocFailed
);
1839 p
= pParse
->pNewTable
;
1842 assert( !db
->init
.busy
|| !pSelect
);
1844 /* If the db->init.busy is 1 it means we are reading the SQL off the
1845 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1846 ** So do not write to the disk again. Extract the root page number
1847 ** for the table from the db->init.newTnum field. (The page number
1848 ** should have been put there by the sqliteOpenCb routine.)
1850 ** If the root page number is 1, that means this is the sqlite_master
1851 ** table itself. So mark it read-only.
1853 if( db
->init
.busy
){
1854 p
->tnum
= db
->init
.newTnum
;
1855 if( p
->tnum
==1 ) p
->tabFlags
|= TF_Readonly
;
1858 /* Special processing for WITHOUT ROWID Tables */
1859 if( tabOpts
& TF_WithoutRowid
){
1860 if( (p
->tabFlags
& TF_Autoincrement
) ){
1861 sqlite3ErrorMsg(pParse
,
1862 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1865 if( (p
->tabFlags
& TF_HasPrimaryKey
)==0 ){
1866 sqlite3ErrorMsg(pParse
, "PRIMARY KEY missing on table %s", p
->zName
);
1868 p
->tabFlags
|= TF_WithoutRowid
| TF_NoVisibleRowid
;
1869 convertToWithoutRowidTable(pParse
, p
);
1873 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
1875 #ifndef SQLITE_OMIT_CHECK
1876 /* Resolve names in all CHECK constraint expressions.
1879 sqlite3ResolveSelfReference(pParse
, p
, NC_IsCheck
, 0, p
->pCheck
);
1881 #endif /* !defined(SQLITE_OMIT_CHECK) */
1883 /* Estimate the average row size for the table and for all implied indices */
1884 estimateTableWidth(p
);
1885 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1886 estimateIndexWidth(pIdx
);
1889 /* If not initializing, then create a record for the new table
1890 ** in the SQLITE_MASTER table of the database.
1892 ** If this is a TEMPORARY table, write the entry into the auxiliary
1893 ** file instead of into the main database file.
1895 if( !db
->init
.busy
){
1898 char *zType
; /* "view" or "table" */
1899 char *zType2
; /* "VIEW" or "TABLE" */
1900 char *zStmt
; /* Text of the CREATE TABLE or CREATE VIEW statement */
1902 v
= sqlite3GetVdbe(pParse
);
1903 if( NEVER(v
==0) ) return;
1905 sqlite3VdbeAddOp1(v
, OP_Close
, 0);
1908 ** Initialize zType for the new view or table.
1910 if( p
->pSelect
==0 ){
1911 /* A regular table */
1914 #ifndef SQLITE_OMIT_VIEW
1922 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1923 ** statement to populate the new table. The root-page number for the
1924 ** new table is in register pParse->regRoot.
1926 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1927 ** suitable state to query for the column names and types to be used
1928 ** by the new table.
1930 ** A shared-cache write-lock is not required to write to the new table,
1931 ** as a schema-lock must have already been obtained to create it. Since
1932 ** a schema-lock excludes all other database users, the write-lock would
1936 SelectDest dest
; /* Where the SELECT should store results */
1937 int regYield
; /* Register holding co-routine entry-point */
1938 int addrTop
; /* Top of the co-routine */
1939 int regRec
; /* A record to be insert into the new table */
1940 int regRowid
; /* Rowid of the next row to insert */
1941 int addrInsLoop
; /* Top of the loop for inserting rows */
1942 Table
*pSelTab
; /* A table that describes the SELECT results */
1944 regYield
= ++pParse
->nMem
;
1945 regRec
= ++pParse
->nMem
;
1946 regRowid
= ++pParse
->nMem
;
1947 assert(pParse
->nTab
==1);
1948 sqlite3MayAbort(pParse
);
1949 sqlite3VdbeAddOp3(v
, OP_OpenWrite
, 1, pParse
->regRoot
, iDb
);
1950 sqlite3VdbeChangeP5(v
, OPFLAG_P2ISREG
);
1952 addrTop
= sqlite3VdbeCurrentAddr(v
) + 1;
1953 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, addrTop
);
1954 sqlite3SelectDestInit(&dest
, SRT_Coroutine
, regYield
);
1955 sqlite3Select(pParse
, pSelect
, &dest
);
1956 sqlite3VdbeEndCoroutine(v
, regYield
);
1957 sqlite3VdbeJumpHere(v
, addrTop
- 1);
1958 if( pParse
->nErr
) return;
1959 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSelect
);
1960 if( pSelTab
==0 ) return;
1961 assert( p
->aCol
==0 );
1962 p
->nCol
= pSelTab
->nCol
;
1963 p
->aCol
= pSelTab
->aCol
;
1966 sqlite3DeleteTable(db
, pSelTab
);
1967 addrInsLoop
= sqlite3VdbeAddOp1(v
, OP_Yield
, dest
.iSDParm
);
1969 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, dest
.iSdst
, dest
.nSdst
, regRec
);
1970 sqlite3TableAffinity(v
, p
, 0);
1971 sqlite3VdbeAddOp2(v
, OP_NewRowid
, 1, regRowid
);
1972 sqlite3VdbeAddOp3(v
, OP_Insert
, 1, regRec
, regRowid
);
1973 sqlite3VdbeGoto(v
, addrInsLoop
);
1974 sqlite3VdbeJumpHere(v
, addrInsLoop
);
1975 sqlite3VdbeAddOp1(v
, OP_Close
, 1);
1978 /* Compute the complete text of the CREATE statement */
1980 zStmt
= createTableStmt(db
, p
);
1982 Token
*pEnd2
= tabOpts
? &pParse
->sLastToken
: pEnd
;
1983 n
= (int)(pEnd2
->z
- pParse
->sNameToken
.z
);
1984 if( pEnd2
->z
[0]!=';' ) n
+= pEnd2
->n
;
1985 zStmt
= sqlite3MPrintf(db
,
1986 "CREATE %s %.*s", zType2
, n
, pParse
->sNameToken
.z
1990 /* A slot for the record has already been allocated in the
1991 ** SQLITE_MASTER table. We just need to update that slot with all
1992 ** the information we've collected.
1994 sqlite3NestedParse(pParse
,
1996 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1998 db
->aDb
[iDb
].zName
, SCHEMA_TABLE(iDb
),
2006 sqlite3DbFree(db
, zStmt
);
2007 sqlite3ChangeCookie(pParse
, iDb
);
2009 #ifndef SQLITE_OMIT_AUTOINCREMENT
2010 /* Check to see if we need to create an sqlite_sequence table for
2011 ** keeping track of autoincrement keys.
2013 if( p
->tabFlags
& TF_Autoincrement
){
2014 Db
*pDb
= &db
->aDb
[iDb
];
2015 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2016 if( pDb
->pSchema
->pSeqTab
==0 ){
2017 sqlite3NestedParse(pParse
,
2018 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2025 /* Reparse everything to update our internal data structures */
2026 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
2027 sqlite3MPrintf(db
, "tbl_name='%q' AND type!='trigger'", p
->zName
));
2031 /* Add the table to the in-memory representation of the database.
2033 if( db
->init
.busy
){
2035 Schema
*pSchema
= p
->pSchema
;
2036 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2037 pOld
= sqlite3HashInsert(&pSchema
->tblHash
, p
->zName
, p
);
2039 assert( p
==pOld
); /* Malloc must have failed inside HashInsert() */
2040 sqlite3OomFault(db
);
2043 pParse
->pNewTable
= 0;
2044 db
->flags
|= SQLITE_InternChanges
;
2046 #ifndef SQLITE_OMIT_ALTERTABLE
2048 const char *zName
= (const char *)pParse
->sNameToken
.z
;
2050 assert( !pSelect
&& pCons
&& pEnd
);
2054 nName
= (int)((const char *)pCons
->z
- zName
);
2055 p
->addColOffset
= 13 + sqlite3Utf8CharLen(zName
, nName
);
2061 #ifndef SQLITE_OMIT_VIEW
2063 ** The parser calls this routine in order to create a new VIEW
2065 void sqlite3CreateView(
2066 Parse
*pParse
, /* The parsing context */
2067 Token
*pBegin
, /* The CREATE token that begins the statement */
2068 Token
*pName1
, /* The token that holds the name of the view */
2069 Token
*pName2
, /* The token that holds the name of the view */
2070 ExprList
*pCNames
, /* Optional list of view column names */
2071 Select
*pSelect
, /* A SELECT statement that will become the new view */
2072 int isTemp
, /* TRUE for a TEMPORARY view */
2073 int noErr
/* Suppress error messages if VIEW already exists */
2082 sqlite3
*db
= pParse
->db
;
2084 if( pParse
->nVar
>0 ){
2085 sqlite3ErrorMsg(pParse
, "parameters are not allowed in views");
2086 goto create_view_fail
;
2088 sqlite3StartTable(pParse
, pName1
, pName2
, isTemp
, 1, 0, noErr
);
2089 p
= pParse
->pNewTable
;
2090 if( p
==0 || pParse
->nErr
) goto create_view_fail
;
2091 sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
2092 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
2093 sqlite3FixInit(&sFix
, pParse
, iDb
, "view", pName
);
2094 if( sqlite3FixSelect(&sFix
, pSelect
) ) goto create_view_fail
;
2096 /* Make a copy of the entire SELECT statement that defines the view.
2097 ** This will force all the Expr.token.z values to be dynamically
2098 ** allocated rather than point to the input string - which means that
2099 ** they will persist after the current sqlite3_exec() call returns.
2101 p
->pSelect
= sqlite3SelectDup(db
, pSelect
, EXPRDUP_REDUCE
);
2102 p
->pCheck
= sqlite3ExprListDup(db
, pCNames
, EXPRDUP_REDUCE
);
2103 if( db
->mallocFailed
) goto create_view_fail
;
2105 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2108 sEnd
= pParse
->sLastToken
;
2109 assert( sEnd
.z
[0]!=0 );
2110 if( sEnd
.z
[0]!=';' ){
2114 n
= (int)(sEnd
.z
- pBegin
->z
);
2117 while( sqlite3Isspace(z
[n
-1]) ){ n
--; }
2121 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
2122 sqlite3EndTable(pParse
, 0, &sEnd
, 0, 0);
2125 sqlite3SelectDelete(db
, pSelect
);
2126 sqlite3ExprListDelete(db
, pCNames
);
2129 #endif /* SQLITE_OMIT_VIEW */
2131 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2133 ** The Table structure pTable is really a VIEW. Fill in the names of
2134 ** the columns of the view in the pTable structure. Return the number
2135 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
2137 int sqlite3ViewGetColumnNames(Parse
*pParse
, Table
*pTable
){
2138 Table
*pSelTab
; /* A fake table from which we get the result set */
2139 Select
*pSel
; /* Copy of the SELECT that implements the view */
2140 int nErr
= 0; /* Number of errors encountered */
2141 int n
; /* Temporarily holds the number of cursors assigned */
2142 sqlite3
*db
= pParse
->db
; /* Database connection for malloc errors */
2143 sqlite3_xauth xAuth
; /* Saved xAuth pointer */
2147 #ifndef SQLITE_OMIT_VIRTUALTABLE
2148 if( sqlite3VtabCallConnect(pParse
, pTable
) ){
2149 return SQLITE_ERROR
;
2151 if( IsVirtual(pTable
) ) return 0;
2154 #ifndef SQLITE_OMIT_VIEW
2155 /* A positive nCol means the columns names for this view are
2158 if( pTable
->nCol
>0 ) return 0;
2160 /* A negative nCol is a special marker meaning that we are currently
2161 ** trying to compute the column names. If we enter this routine with
2162 ** a negative nCol, it means two or more views form a loop, like this:
2164 ** CREATE VIEW one AS SELECT * FROM two;
2165 ** CREATE VIEW two AS SELECT * FROM one;
2167 ** Actually, the error above is now caught prior to reaching this point.
2168 ** But the following test is still important as it does come up
2169 ** in the following:
2171 ** CREATE TABLE main.ex1(a);
2172 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2173 ** SELECT * FROM temp.ex1;
2175 if( pTable
->nCol
<0 ){
2176 sqlite3ErrorMsg(pParse
, "view %s is circularly defined", pTable
->zName
);
2179 assert( pTable
->nCol
>=0 );
2181 /* If we get this far, it means we need to compute the table names.
2182 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2183 ** "*" elements in the results set of the view and will assign cursors
2184 ** to the elements of the FROM clause. But we do not want these changes
2185 ** to be permanent. So the computation is done on a copy of the SELECT
2186 ** statement that defines the view.
2188 assert( pTable
->pSelect
);
2189 pSel
= sqlite3SelectDup(db
, pTable
->pSelect
, 0);
2192 sqlite3SrcListAssignCursors(pParse
, pSel
->pSrc
);
2194 db
->lookaside
.bDisable
++;
2195 #ifndef SQLITE_OMIT_AUTHORIZATION
2198 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
);
2201 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
);
2204 if( pTable
->pCheck
){
2205 /* CREATE VIEW name(arglist) AS ...
2206 ** The names of the columns in the table are taken from
2207 ** arglist which is stored in pTable->pCheck. The pCheck field
2208 ** normally holds CHECK constraints on an ordinary table, but for
2209 ** a VIEW it holds the list of column names.
2211 sqlite3ColumnsFromExprList(pParse
, pTable
->pCheck
,
2212 &pTable
->nCol
, &pTable
->aCol
);
2213 if( db
->mallocFailed
==0
2215 && pTable
->nCol
==pSel
->pEList
->nExpr
2217 sqlite3SelectAddColumnTypeAndCollation(pParse
, pTable
, pSel
);
2219 }else if( pSelTab
){
2220 /* CREATE VIEW name AS... without an argument list. Construct
2221 ** the column names from the SELECT statement that defines the view.
2223 assert( pTable
->aCol
==0 );
2224 pTable
->nCol
= pSelTab
->nCol
;
2225 pTable
->aCol
= pSelTab
->aCol
;
2228 assert( sqlite3SchemaMutexHeld(db
, 0, pTable
->pSchema
) );
2233 sqlite3DeleteTable(db
, pSelTab
);
2234 sqlite3SelectDelete(db
, pSel
);
2235 db
->lookaside
.bDisable
--;
2239 pTable
->pSchema
->schemaFlags
|= DB_UnresetViews
;
2240 #endif /* SQLITE_OMIT_VIEW */
2243 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2245 #ifndef SQLITE_OMIT_VIEW
2247 ** Clear the column names from every VIEW in database idx.
2249 static void sqliteViewResetAll(sqlite3
*db
, int idx
){
2251 assert( sqlite3SchemaMutexHeld(db
, idx
, 0) );
2252 if( !DbHasProperty(db
, idx
, DB_UnresetViews
) ) return;
2253 for(i
=sqliteHashFirst(&db
->aDb
[idx
].pSchema
->tblHash
); i
;i
=sqliteHashNext(i
)){
2254 Table
*pTab
= sqliteHashData(i
);
2255 if( pTab
->pSelect
){
2256 sqlite3DeleteColumnNames(db
, pTab
);
2261 DbClearProperty(db
, idx
, DB_UnresetViews
);
2264 # define sqliteViewResetAll(A,B)
2265 #endif /* SQLITE_OMIT_VIEW */
2268 ** This function is called by the VDBE to adjust the internal schema
2269 ** used by SQLite when the btree layer moves a table root page. The
2270 ** root-page of a table or index in database iDb has changed from iFrom
2273 ** Ticket #1728: The symbol table might still contain information
2274 ** on tables and/or indices that are the process of being deleted.
2275 ** If you are unlucky, one of those deleted indices or tables might
2276 ** have the same rootpage number as the real table or index that is
2277 ** being moved. So we cannot stop searching after the first match
2278 ** because the first match might be for one of the deleted indices
2279 ** or tables and not the table/index that is actually being moved.
2280 ** We must continue looping until all tables and indices with
2281 ** rootpage==iFrom have been converted to have a rootpage of iTo
2282 ** in order to be certain that we got the right one.
2284 #ifndef SQLITE_OMIT_AUTOVACUUM
2285 void sqlite3RootPageMoved(sqlite3
*db
, int iDb
, int iFrom
, int iTo
){
2290 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2291 pDb
= &db
->aDb
[iDb
];
2292 pHash
= &pDb
->pSchema
->tblHash
;
2293 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
2294 Table
*pTab
= sqliteHashData(pElem
);
2295 if( pTab
->tnum
==iFrom
){
2299 pHash
= &pDb
->pSchema
->idxHash
;
2300 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
2301 Index
*pIdx
= sqliteHashData(pElem
);
2302 if( pIdx
->tnum
==iFrom
){
2310 ** Write code to erase the table with root-page iTable from database iDb.
2311 ** Also write code to modify the sqlite_master table and internal schema
2312 ** if a root-page of another table is moved by the btree-layer whilst
2313 ** erasing iTable (this can happen with an auto-vacuum database).
2315 static void destroyRootPage(Parse
*pParse
, int iTable
, int iDb
){
2316 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2317 int r1
= sqlite3GetTempReg(pParse
);
2319 sqlite3VdbeAddOp3(v
, OP_Destroy
, iTable
, r1
, iDb
);
2320 sqlite3MayAbort(pParse
);
2321 #ifndef SQLITE_OMIT_AUTOVACUUM
2322 /* OP_Destroy stores an in integer r1. If this integer
2323 ** is non-zero, then it is the root page number of a table moved to
2324 ** location iTable. The following code modifies the sqlite_master table to
2327 ** The "#NNN" in the SQL is a special constant that means whatever value
2328 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2329 ** token for additional information.
2331 sqlite3NestedParse(pParse
,
2332 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2333 pParse
->db
->aDb
[iDb
].zName
, SCHEMA_TABLE(iDb
), iTable
, r1
, r1
);
2335 sqlite3ReleaseTempReg(pParse
, r1
);
2339 ** Write VDBE code to erase table pTab and all associated indices on disk.
2340 ** Code to update the sqlite_master tables and internal schema definitions
2341 ** in case a root-page belonging to another table is moved by the btree layer
2342 ** is also added (this can happen with an auto-vacuum database).
2344 static void destroyTable(Parse
*pParse
, Table
*pTab
){
2345 #ifdef SQLITE_OMIT_AUTOVACUUM
2347 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
2348 destroyRootPage(pParse
, pTab
->tnum
, iDb
);
2349 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2350 destroyRootPage(pParse
, pIdx
->tnum
, iDb
);
2353 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2354 ** is not defined), then it is important to call OP_Destroy on the
2355 ** table and index root-pages in order, starting with the numerically
2356 ** largest root-page number. This guarantees that none of the root-pages
2357 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2358 ** following were coded:
2364 ** and root page 5 happened to be the largest root-page number in the
2365 ** database, then root page 5 would be moved to page 4 by the
2366 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2367 ** a free-list page.
2369 int iTab
= pTab
->tnum
;
2376 if( iDestroyed
==0 || iTab
<iDestroyed
){
2379 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2380 int iIdx
= pIdx
->tnum
;
2381 assert( pIdx
->pSchema
==pTab
->pSchema
);
2382 if( (iDestroyed
==0 || (iIdx
<iDestroyed
)) && iIdx
>iLargest
){
2389 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
2390 assert( iDb
>=0 && iDb
<pParse
->db
->nDb
);
2391 destroyRootPage(pParse
, iLargest
, iDb
);
2392 iDestroyed
= iLargest
;
2399 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2400 ** after a DROP INDEX or DROP TABLE command.
2402 static void sqlite3ClearStatTables(
2403 Parse
*pParse
, /* The parsing context */
2404 int iDb
, /* The database number */
2405 const char *zType
, /* "idx" or "tbl" */
2406 const char *zName
/* Name of index or table */
2409 const char *zDbName
= pParse
->db
->aDb
[iDb
].zName
;
2410 for(i
=1; i
<=4; i
++){
2412 sqlite3_snprintf(sizeof(zTab
),zTab
,"sqlite_stat%d",i
);
2413 if( sqlite3FindTable(pParse
->db
, zTab
, zDbName
) ){
2414 sqlite3NestedParse(pParse
,
2415 "DELETE FROM %Q.%s WHERE %s=%Q",
2416 zDbName
, zTab
, zType
, zName
2423 ** Generate code to drop a table.
2425 void sqlite3CodeDropTable(Parse
*pParse
, Table
*pTab
, int iDb
, int isView
){
2427 sqlite3
*db
= pParse
->db
;
2429 Db
*pDb
= &db
->aDb
[iDb
];
2431 v
= sqlite3GetVdbe(pParse
);
2433 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
2435 #ifndef SQLITE_OMIT_VIRTUALTABLE
2436 if( IsVirtual(pTab
) ){
2437 sqlite3VdbeAddOp0(v
, OP_VBegin
);
2441 /* Drop all triggers associated with the table being dropped. Code
2442 ** is generated to remove entries from sqlite_master and/or
2443 ** sqlite_temp_master if required.
2445 pTrigger
= sqlite3TriggerList(pParse
, pTab
);
2447 assert( pTrigger
->pSchema
==pTab
->pSchema
||
2448 pTrigger
->pSchema
==db
->aDb
[1].pSchema
);
2449 sqlite3DropTriggerPtr(pParse
, pTrigger
);
2450 pTrigger
= pTrigger
->pNext
;
2453 #ifndef SQLITE_OMIT_AUTOINCREMENT
2454 /* Remove any entries of the sqlite_sequence table associated with
2455 ** the table being dropped. This is done before the table is dropped
2456 ** at the btree level, in case the sqlite_sequence table needs to
2457 ** move as a result of the drop (can happen in auto-vacuum mode).
2459 if( pTab
->tabFlags
& TF_Autoincrement
){
2460 sqlite3NestedParse(pParse
,
2461 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2462 pDb
->zName
, pTab
->zName
2467 /* Drop all SQLITE_MASTER table and index entries that refer to the
2468 ** table. The program name loops through the master table and deletes
2469 ** every row that refers to a table of the same name as the one being
2470 ** dropped. Triggers are handled separately because a trigger can be
2471 ** created in the temp database that refers to a table in another
2474 sqlite3NestedParse(pParse
,
2475 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2476 pDb
->zName
, SCHEMA_TABLE(iDb
), pTab
->zName
);
2477 if( !isView
&& !IsVirtual(pTab
) ){
2478 destroyTable(pParse
, pTab
);
2481 /* Remove the table entry from SQLite's internal schema and modify
2482 ** the schema cookie.
2484 if( IsVirtual(pTab
) ){
2485 sqlite3VdbeAddOp4(v
, OP_VDestroy
, iDb
, 0, 0, pTab
->zName
, 0);
2487 sqlite3VdbeAddOp4(v
, OP_DropTable
, iDb
, 0, 0, pTab
->zName
, 0);
2488 sqlite3ChangeCookie(pParse
, iDb
);
2489 sqliteViewResetAll(db
, iDb
);
2493 ** This routine is called to do the work of a DROP TABLE statement.
2494 ** pName is the name of the table to be dropped.
2496 void sqlite3DropTable(Parse
*pParse
, SrcList
*pName
, int isView
, int noErr
){
2499 sqlite3
*db
= pParse
->db
;
2502 if( db
->mallocFailed
){
2503 goto exit_drop_table
;
2505 assert( pParse
->nErr
==0 );
2506 assert( pName
->nSrc
==1 );
2507 if( sqlite3ReadSchema(pParse
) ) goto exit_drop_table
;
2508 if( noErr
) db
->suppressErr
++;
2509 assert( isView
==0 || isView
==LOCATE_VIEW
);
2510 pTab
= sqlite3LocateTableItem(pParse
, isView
, &pName
->a
[0]);
2511 if( noErr
) db
->suppressErr
--;
2514 if( noErr
) sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
2515 goto exit_drop_table
;
2517 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
2518 assert( iDb
>=0 && iDb
<db
->nDb
);
2520 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2521 ** it is initialized.
2523 if( IsVirtual(pTab
) && sqlite3ViewGetColumnNames(pParse
, pTab
) ){
2524 goto exit_drop_table
;
2526 #ifndef SQLITE_OMIT_AUTHORIZATION
2529 const char *zTab
= SCHEMA_TABLE(iDb
);
2530 const char *zDb
= db
->aDb
[iDb
].zName
;
2531 const char *zArg2
= 0;
2532 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
)){
2533 goto exit_drop_table
;
2536 if( !OMIT_TEMPDB
&& iDb
==1 ){
2537 code
= SQLITE_DROP_TEMP_VIEW
;
2539 code
= SQLITE_DROP_VIEW
;
2541 #ifndef SQLITE_OMIT_VIRTUALTABLE
2542 }else if( IsVirtual(pTab
) ){
2543 code
= SQLITE_DROP_VTABLE
;
2544 zArg2
= sqlite3GetVTable(db
, pTab
)->pMod
->zName
;
2547 if( !OMIT_TEMPDB
&& iDb
==1 ){
2548 code
= SQLITE_DROP_TEMP_TABLE
;
2550 code
= SQLITE_DROP_TABLE
;
2553 if( sqlite3AuthCheck(pParse
, code
, pTab
->zName
, zArg2
, zDb
) ){
2554 goto exit_drop_table
;
2556 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, pTab
->zName
, 0, zDb
) ){
2557 goto exit_drop_table
;
2561 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0
2562 && sqlite3StrNICmp(pTab
->zName
, "sqlite_stat", 11)!=0 ){
2563 sqlite3ErrorMsg(pParse
, "table %s may not be dropped", pTab
->zName
);
2564 goto exit_drop_table
;
2567 #ifndef SQLITE_OMIT_VIEW
2568 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2571 if( isView
&& pTab
->pSelect
==0 ){
2572 sqlite3ErrorMsg(pParse
, "use DROP TABLE to delete table %s", pTab
->zName
);
2573 goto exit_drop_table
;
2575 if( !isView
&& pTab
->pSelect
){
2576 sqlite3ErrorMsg(pParse
, "use DROP VIEW to delete view %s", pTab
->zName
);
2577 goto exit_drop_table
;
2581 /* Generate code to remove the table from the master table
2584 v
= sqlite3GetVdbe(pParse
);
2586 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
2587 sqlite3ClearStatTables(pParse
, iDb
, "tbl", pTab
->zName
);
2588 sqlite3FkDropTable(pParse
, pName
, pTab
);
2589 sqlite3CodeDropTable(pParse
, pTab
, iDb
, isView
);
2593 sqlite3SrcListDelete(db
, pName
);
2597 ** This routine is called to create a new foreign key on the table
2598 ** currently under construction. pFromCol determines which columns
2599 ** in the current table point to the foreign key. If pFromCol==0 then
2600 ** connect the key to the last column inserted. pTo is the name of
2601 ** the table referred to (a.k.a the "parent" table). pToCol is a list
2602 ** of tables in the parent pTo table. flags contains all
2603 ** information about the conflict resolution algorithms specified
2604 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2606 ** An FKey structure is created and added to the table currently
2607 ** under construction in the pParse->pNewTable field.
2609 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2610 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2612 void sqlite3CreateForeignKey(
2613 Parse
*pParse
, /* Parsing context */
2614 ExprList
*pFromCol
, /* Columns in this table that point to other table */
2615 Token
*pTo
, /* Name of the other table */
2616 ExprList
*pToCol
, /* Columns in the other table */
2617 int flags
/* Conflict resolution algorithms. */
2619 sqlite3
*db
= pParse
->db
;
2620 #ifndef SQLITE_OMIT_FOREIGN_KEY
2623 Table
*p
= pParse
->pNewTable
;
2630 if( p
==0 || IN_DECLARE_VTAB
) goto fk_end
;
2632 int iCol
= p
->nCol
-1;
2633 if( NEVER(iCol
<0) ) goto fk_end
;
2634 if( pToCol
&& pToCol
->nExpr
!=1 ){
2635 sqlite3ErrorMsg(pParse
, "foreign key on %s"
2636 " should reference only one column of table %T",
2637 p
->aCol
[iCol
].zName
, pTo
);
2641 }else if( pToCol
&& pToCol
->nExpr
!=pFromCol
->nExpr
){
2642 sqlite3ErrorMsg(pParse
,
2643 "number of columns in foreign key does not match the number of "
2644 "columns in the referenced table");
2647 nCol
= pFromCol
->nExpr
;
2649 nByte
= sizeof(*pFKey
) + (nCol
-1)*sizeof(pFKey
->aCol
[0]) + pTo
->n
+ 1;
2651 for(i
=0; i
<pToCol
->nExpr
; i
++){
2652 nByte
+= sqlite3Strlen30(pToCol
->a
[i
].zName
) + 1;
2655 pFKey
= sqlite3DbMallocZero(db
, nByte
);
2660 pFKey
->pNextFrom
= p
->pFKey
;
2661 z
= (char*)&pFKey
->aCol
[nCol
];
2663 memcpy(z
, pTo
->z
, pTo
->n
);
2669 pFKey
->aCol
[0].iFrom
= p
->nCol
-1;
2671 for(i
=0; i
<nCol
; i
++){
2673 for(j
=0; j
<p
->nCol
; j
++){
2674 if( sqlite3StrICmp(p
->aCol
[j
].zName
, pFromCol
->a
[i
].zName
)==0 ){
2675 pFKey
->aCol
[i
].iFrom
= j
;
2680 sqlite3ErrorMsg(pParse
,
2681 "unknown column \"%s\" in foreign key definition",
2682 pFromCol
->a
[i
].zName
);
2688 for(i
=0; i
<nCol
; i
++){
2689 int n
= sqlite3Strlen30(pToCol
->a
[i
].zName
);
2690 pFKey
->aCol
[i
].zCol
= z
;
2691 memcpy(z
, pToCol
->a
[i
].zName
, n
);
2696 pFKey
->isDeferred
= 0;
2697 pFKey
->aAction
[0] = (u8
)(flags
& 0xff); /* ON DELETE action */
2698 pFKey
->aAction
[1] = (u8
)((flags
>> 8 ) & 0xff); /* ON UPDATE action */
2700 assert( sqlite3SchemaMutexHeld(db
, 0, p
->pSchema
) );
2701 pNextTo
= (FKey
*)sqlite3HashInsert(&p
->pSchema
->fkeyHash
,
2702 pFKey
->zTo
, (void *)pFKey
2704 if( pNextTo
==pFKey
){
2705 sqlite3OomFault(db
);
2709 assert( pNextTo
->pPrevTo
==0 );
2710 pFKey
->pNextTo
= pNextTo
;
2711 pNextTo
->pPrevTo
= pFKey
;
2714 /* Link the foreign key to the table as the last step.
2720 sqlite3DbFree(db
, pFKey
);
2721 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2722 sqlite3ExprListDelete(db
, pFromCol
);
2723 sqlite3ExprListDelete(db
, pToCol
);
2727 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2728 ** clause is seen as part of a foreign key definition. The isDeferred
2729 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2730 ** The behavior of the most recently created foreign key is adjusted
2733 void sqlite3DeferForeignKey(Parse
*pParse
, int isDeferred
){
2734 #ifndef SQLITE_OMIT_FOREIGN_KEY
2737 if( (pTab
= pParse
->pNewTable
)==0 || (pFKey
= pTab
->pFKey
)==0 ) return;
2738 assert( isDeferred
==0 || isDeferred
==1 ); /* EV: R-30323-21917 */
2739 pFKey
->isDeferred
= (u8
)isDeferred
;
2744 ** Generate code that will erase and refill index *pIdx. This is
2745 ** used to initialize a newly created index or to recompute the
2746 ** content of an index in response to a REINDEX command.
2748 ** if memRootPage is not negative, it means that the index is newly
2749 ** created. The register specified by memRootPage contains the
2750 ** root page number of the index. If memRootPage is negative, then
2751 ** the index already exists and must be cleared before being refilled and
2752 ** the root page number of the index is taken from pIndex->tnum.
2754 static void sqlite3RefillIndex(Parse
*pParse
, Index
*pIndex
, int memRootPage
){
2755 Table
*pTab
= pIndex
->pTable
; /* The table that is indexed */
2756 int iTab
= pParse
->nTab
++; /* Btree cursor used for pTab */
2757 int iIdx
= pParse
->nTab
++; /* Btree cursor used for pIndex */
2758 int iSorter
; /* Cursor opened by OpenSorter (if in use) */
2759 int addr1
; /* Address of top of loop */
2760 int addr2
; /* Address to jump to for next iteration */
2761 int tnum
; /* Root page of index */
2762 int iPartIdxLabel
; /* Jump to this label to skip a row */
2763 Vdbe
*v
; /* Generate code into this virtual machine */
2764 KeyInfo
*pKey
; /* KeyInfo for index */
2765 int regRecord
; /* Register holding assembled index record */
2766 sqlite3
*db
= pParse
->db
; /* The database connection */
2767 int iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
2769 #ifndef SQLITE_OMIT_AUTHORIZATION
2770 if( sqlite3AuthCheck(pParse
, SQLITE_REINDEX
, pIndex
->zName
, 0,
2771 db
->aDb
[iDb
].zName
) ){
2776 /* Require a write-lock on the table to perform this operation */
2777 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 1, pTab
->zName
);
2779 v
= sqlite3GetVdbe(pParse
);
2781 if( memRootPage
>=0 ){
2784 tnum
= pIndex
->tnum
;
2786 pKey
= sqlite3KeyInfoOfIndex(pParse
, pIndex
);
2787 assert( pKey
!=0 || db
->mallocFailed
|| pParse
->nErr
);
2789 /* Open the sorter cursor if we are to use one. */
2790 iSorter
= pParse
->nTab
++;
2791 sqlite3VdbeAddOp4(v
, OP_SorterOpen
, iSorter
, 0, pIndex
->nKeyCol
, (char*)
2792 sqlite3KeyInfoRef(pKey
), P4_KEYINFO
);
2794 /* Open the table. Loop through all rows of the table, inserting index
2795 ** records into the sorter. */
2796 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
2797 addr1
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, 0); VdbeCoverage(v
);
2798 regRecord
= sqlite3GetTempReg(pParse
);
2800 sqlite3GenerateIndexKey(pParse
,pIndex
,iTab
,regRecord
,0,&iPartIdxLabel
,0,0);
2801 sqlite3VdbeAddOp2(v
, OP_SorterInsert
, iSorter
, regRecord
);
2802 sqlite3ResolvePartIdxLabel(pParse
, iPartIdxLabel
);
2803 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addr1
+1); VdbeCoverage(v
);
2804 sqlite3VdbeJumpHere(v
, addr1
);
2805 if( memRootPage
<0 ) sqlite3VdbeAddOp2(v
, OP_Clear
, tnum
, iDb
);
2806 sqlite3VdbeAddOp4(v
, OP_OpenWrite
, iIdx
, tnum
, iDb
,
2807 (char *)pKey
, P4_KEYINFO
);
2808 sqlite3VdbeChangeP5(v
, OPFLAG_BULKCSR
|((memRootPage
>=0)?OPFLAG_P2ISREG
:0));
2810 addr1
= sqlite3VdbeAddOp2(v
, OP_SorterSort
, iSorter
, 0); VdbeCoverage(v
);
2811 if( IsUniqueIndex(pIndex
) ){
2812 int j2
= sqlite3VdbeCurrentAddr(v
) + 3;
2813 sqlite3VdbeGoto(v
, j2
);
2814 addr2
= sqlite3VdbeCurrentAddr(v
);
2815 sqlite3VdbeAddOp4Int(v
, OP_SorterCompare
, iSorter
, j2
, regRecord
,
2816 pIndex
->nKeyCol
); VdbeCoverage(v
);
2817 sqlite3UniqueConstraint(pParse
, OE_Abort
, pIndex
);
2819 addr2
= sqlite3VdbeCurrentAddr(v
);
2821 sqlite3VdbeAddOp3(v
, OP_SorterData
, iSorter
, regRecord
, iIdx
);
2822 sqlite3VdbeAddOp3(v
, OP_Last
, iIdx
, 0, -1);
2823 sqlite3VdbeAddOp3(v
, OP_IdxInsert
, iIdx
, regRecord
, 0);
2824 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
2825 sqlite3ReleaseTempReg(pParse
, regRecord
);
2826 sqlite3VdbeAddOp2(v
, OP_SorterNext
, iSorter
, addr2
); VdbeCoverage(v
);
2827 sqlite3VdbeJumpHere(v
, addr1
);
2829 sqlite3VdbeAddOp1(v
, OP_Close
, iTab
);
2830 sqlite3VdbeAddOp1(v
, OP_Close
, iIdx
);
2831 sqlite3VdbeAddOp1(v
, OP_Close
, iSorter
);
2835 ** Allocate heap space to hold an Index object with nCol columns.
2837 ** Increase the allocation size to provide an extra nExtra bytes
2838 ** of 8-byte aligned space after the Index object and return a
2839 ** pointer to this extra space in *ppExtra.
2841 Index
*sqlite3AllocateIndexObject(
2842 sqlite3
*db
, /* Database connection */
2843 i16 nCol
, /* Total number of columns in the index */
2844 int nExtra
, /* Number of bytes of extra space to alloc */
2845 char **ppExtra
/* Pointer to the "extra" space */
2847 Index
*p
; /* Allocated index object */
2848 int nByte
; /* Bytes of space for Index object + arrays */
2850 nByte
= ROUND8(sizeof(Index
)) + /* Index structure */
2851 ROUND8(sizeof(char*)*nCol
) + /* Index.azColl */
2852 ROUND8(sizeof(LogEst
)*(nCol
+1) + /* Index.aiRowLogEst */
2853 sizeof(i16
)*nCol
+ /* Index.aiColumn */
2854 sizeof(u8
)*nCol
); /* Index.aSortOrder */
2855 p
= sqlite3DbMallocZero(db
, nByte
+ nExtra
);
2857 char *pExtra
= ((char*)p
)+ROUND8(sizeof(Index
));
2858 p
->azColl
= (const char**)pExtra
; pExtra
+= ROUND8(sizeof(char*)*nCol
);
2859 p
->aiRowLogEst
= (LogEst
*)pExtra
; pExtra
+= sizeof(LogEst
)*(nCol
+1);
2860 p
->aiColumn
= (i16
*)pExtra
; pExtra
+= sizeof(i16
)*nCol
;
2861 p
->aSortOrder
= (u8
*)pExtra
;
2863 p
->nKeyCol
= nCol
- 1;
2864 *ppExtra
= ((char*)p
) + nByte
;
2870 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2871 ** and pTblList is the name of the table that is to be indexed. Both will
2872 ** be NULL for a primary key or an index that is created to satisfy a
2873 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2874 ** as the table to be indexed. pParse->pNewTable is a table that is
2875 ** currently being constructed by a CREATE TABLE statement.
2877 ** pList is a list of columns to be indexed. pList will be NULL if this
2878 ** is a primary key or unique-constraint on the most recent column added
2879 ** to the table currently under construction.
2881 void sqlite3CreateIndex(
2882 Parse
*pParse
, /* All information about this parse */
2883 Token
*pName1
, /* First part of index name. May be NULL */
2884 Token
*pName2
, /* Second part of index name. May be NULL */
2885 SrcList
*pTblName
, /* Table to index. Use pParse->pNewTable if 0 */
2886 ExprList
*pList
, /* A list of columns to be indexed */
2887 int onError
, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2888 Token
*pStart
, /* The CREATE token that begins this statement */
2889 Expr
*pPIWhere
, /* WHERE clause for partial indices */
2890 int sortOrder
, /* Sort order of primary key when pList==NULL */
2891 int ifNotExist
, /* Omit error if index already exists */
2892 u8 idxType
/* The index type */
2894 Table
*pTab
= 0; /* Table to be indexed */
2895 Index
*pIndex
= 0; /* The index to be created */
2896 char *zName
= 0; /* Name of the index */
2897 int nName
; /* Number of characters in zName */
2899 DbFixer sFix
; /* For assigning database names to pTable */
2900 int sortOrderMask
; /* 1 to honor DESC in index. 0 to ignore. */
2901 sqlite3
*db
= pParse
->db
;
2902 Db
*pDb
; /* The specific table containing the indexed database */
2903 int iDb
; /* Index of the database that is being written */
2904 Token
*pName
= 0; /* Unqualified name of the index to create */
2905 struct ExprList_item
*pListItem
; /* For looping over pList */
2906 int nExtra
= 0; /* Space allocated for zExtra[] */
2907 int nExtraCol
; /* Number of extra columns needed */
2908 char *zExtra
= 0; /* Extra space after the Index object */
2909 Index
*pPk
= 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
2911 if( db
->mallocFailed
|| pParse
->nErr
>0 ){
2912 goto exit_create_index
;
2914 if( IN_DECLARE_VTAB
&& idxType
!=SQLITE_IDXTYPE_PRIMARYKEY
){
2915 goto exit_create_index
;
2917 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
2918 goto exit_create_index
;
2922 ** Find the table that is to be indexed. Return early if not found.
2926 /* Use the two-part index name to determine the database
2927 ** to search for the table. 'Fix' the table name to this db
2928 ** before looking up the table.
2930 assert( pName1
&& pName2
);
2931 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
2932 if( iDb
<0 ) goto exit_create_index
;
2933 assert( pName
&& pName
->z
);
2935 #ifndef SQLITE_OMIT_TEMPDB
2936 /* If the index name was unqualified, check if the table
2937 ** is a temp table. If so, set the database to 1. Do not do this
2938 ** if initialising a database schema.
2940 if( !db
->init
.busy
){
2941 pTab
= sqlite3SrcListLookup(pParse
, pTblName
);
2942 if( pName2
->n
==0 && pTab
&& pTab
->pSchema
==db
->aDb
[1].pSchema
){
2948 sqlite3FixInit(&sFix
, pParse
, iDb
, "index", pName
);
2949 if( sqlite3FixSrcList(&sFix
, pTblName
) ){
2950 /* Because the parser constructs pTblName from a single identifier,
2951 ** sqlite3FixSrcList can never fail. */
2954 pTab
= sqlite3LocateTableItem(pParse
, 0, &pTblName
->a
[0]);
2955 assert( db
->mallocFailed
==0 || pTab
==0 );
2956 if( pTab
==0 ) goto exit_create_index
;
2957 if( iDb
==1 && db
->aDb
[iDb
].pSchema
!=pTab
->pSchema
){
2958 sqlite3ErrorMsg(pParse
,
2959 "cannot create a TEMP index on non-TEMP table \"%s\"",
2961 goto exit_create_index
;
2963 if( !HasRowid(pTab
) ) pPk
= sqlite3PrimaryKeyIndex(pTab
);
2966 assert( pStart
==0 );
2967 pTab
= pParse
->pNewTable
;
2968 if( !pTab
) goto exit_create_index
;
2969 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
2971 pDb
= &db
->aDb
[iDb
];
2974 assert( pParse
->nErr
==0 );
2975 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0
2977 #if SQLITE_USER_AUTHENTICATION
2978 && sqlite3UserAuthTable(pTab
->zName
)==0
2980 && sqlite3StrNICmp(&pTab
->zName
[7],"altertab_",9)!=0 ){
2981 sqlite3ErrorMsg(pParse
, "table %s may not be indexed", pTab
->zName
);
2982 goto exit_create_index
;
2984 #ifndef SQLITE_OMIT_VIEW
2985 if( pTab
->pSelect
){
2986 sqlite3ErrorMsg(pParse
, "views may not be indexed");
2987 goto exit_create_index
;
2990 #ifndef SQLITE_OMIT_VIRTUALTABLE
2991 if( IsVirtual(pTab
) ){
2992 sqlite3ErrorMsg(pParse
, "virtual tables may not be indexed");
2993 goto exit_create_index
;
2998 ** Find the name of the index. Make sure there is not already another
2999 ** index or table with the same name.
3001 ** Exception: If we are reading the names of permanent indices from the
3002 ** sqlite_master table (because some other process changed the schema) and
3003 ** one of the index names collides with the name of a temporary table or
3004 ** index, then we will continue to process this index.
3006 ** If pName==0 it means that we are
3007 ** dealing with a primary key or UNIQUE constraint. We have to invent our
3011 zName
= sqlite3NameFromToken(db
, pName
);
3012 if( zName
==0 ) goto exit_create_index
;
3013 assert( pName
->z
!=0 );
3014 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
) ){
3015 goto exit_create_index
;
3017 if( !db
->init
.busy
){
3018 if( sqlite3FindTable(db
, zName
, 0)!=0 ){
3019 sqlite3ErrorMsg(pParse
, "there is already a table named %s", zName
);
3020 goto exit_create_index
;
3023 if( sqlite3FindIndex(db
, zName
, pDb
->zName
)!=0 ){
3025 sqlite3ErrorMsg(pParse
, "index %s already exists", zName
);
3027 assert( !db
->init
.busy
);
3028 sqlite3CodeVerifySchema(pParse
, iDb
);
3030 goto exit_create_index
;
3035 for(pLoop
=pTab
->pIndex
, n
=1; pLoop
; pLoop
=pLoop
->pNext
, n
++){}
3036 zName
= sqlite3MPrintf(db
, "sqlite_autoindex_%s_%d", pTab
->zName
, n
);
3038 goto exit_create_index
;
3042 /* Check for authorization to create an index.
3044 #ifndef SQLITE_OMIT_AUTHORIZATION
3046 const char *zDb
= pDb
->zName
;
3047 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(iDb
), 0, zDb
) ){
3048 goto exit_create_index
;
3050 i
= SQLITE_CREATE_INDEX
;
3051 if( !OMIT_TEMPDB
&& iDb
==1 ) i
= SQLITE_CREATE_TEMP_INDEX
;
3052 if( sqlite3AuthCheck(pParse
, i
, zName
, pTab
->zName
, zDb
) ){
3053 goto exit_create_index
;
3058 /* If pList==0, it means this routine was called to make a primary
3059 ** key out of the last column added to the table under construction.
3060 ** So create a fake list to simulate this.
3064 sqlite3TokenInit(&prevCol
, pTab
->aCol
[pTab
->nCol
-1].zName
);
3065 pList
= sqlite3ExprListAppend(pParse
, 0,
3066 sqlite3ExprAlloc(db
, TK_ID
, &prevCol
, 0));
3067 if( pList
==0 ) goto exit_create_index
;
3068 assert( pList
->nExpr
==1 );
3069 sqlite3ExprListSetSortOrder(pList
, sortOrder
);
3071 sqlite3ExprListCheckLength(pParse
, pList
, "index");
3074 /* Figure out how many bytes of space are required to store explicitly
3075 ** specified collation sequence names.
3077 for(i
=0; i
<pList
->nExpr
; i
++){
3078 Expr
*pExpr
= pList
->a
[i
].pExpr
;
3080 if( pExpr
->op
==TK_COLLATE
){
3081 nExtra
+= (1 + sqlite3Strlen30(pExpr
->u
.zToken
));
3086 ** Allocate the index structure.
3088 nName
= sqlite3Strlen30(zName
);
3089 nExtraCol
= pPk
? pPk
->nKeyCol
: 1;
3090 pIndex
= sqlite3AllocateIndexObject(db
, pList
->nExpr
+ nExtraCol
,
3091 nName
+ nExtra
+ 1, &zExtra
);
3092 if( db
->mallocFailed
){
3093 goto exit_create_index
;
3095 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->aiRowLogEst
) );
3096 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->azColl
) );
3097 pIndex
->zName
= zExtra
;
3098 zExtra
+= nName
+ 1;
3099 memcpy(pIndex
->zName
, zName
, nName
+1);
3100 pIndex
->pTable
= pTab
;
3101 pIndex
->onError
= (u8
)onError
;
3102 pIndex
->uniqNotNull
= onError
!=OE_None
;
3103 pIndex
->idxType
= idxType
;
3104 pIndex
->pSchema
= db
->aDb
[iDb
].pSchema
;
3105 pIndex
->nKeyCol
= pList
->nExpr
;
3107 sqlite3ResolveSelfReference(pParse
, pTab
, NC_PartIdx
, pPIWhere
, 0);
3108 pIndex
->pPartIdxWhere
= pPIWhere
;
3111 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
3113 /* Check to see if we should honor DESC requests on index columns
3115 if( pDb
->pSchema
->file_format
>=4 ){
3116 sortOrderMask
= -1; /* Honor DESC */
3118 sortOrderMask
= 0; /* Ignore DESC */
3121 /* Analyze the list of expressions that form the terms of the index and
3122 ** report any errors. In the common case where the expression is exactly
3123 ** a table column, store that column in aiColumn[]. For general expressions,
3124 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
3126 ** TODO: Issue a warning if two or more columns of the index are identical.
3127 ** TODO: Issue a warning if the table primary key is used as part of the
3130 for(i
=0, pListItem
=pList
->a
; i
<pList
->nExpr
; i
++, pListItem
++){
3131 Expr
*pCExpr
; /* The i-th index expression */
3132 int requestedSortOrder
; /* ASC or DESC on the i-th expression */
3133 const char *zColl
; /* Collation sequence name */
3135 sqlite3StringToId(pListItem
->pExpr
);
3136 sqlite3ResolveSelfReference(pParse
, pTab
, NC_IdxExpr
, pListItem
->pExpr
, 0);
3137 if( pParse
->nErr
) goto exit_create_index
;
3138 pCExpr
= sqlite3ExprSkipCollate(pListItem
->pExpr
);
3139 if( pCExpr
->op
!=TK_COLUMN
){
3140 if( pTab
==pParse
->pNewTable
){
3141 sqlite3ErrorMsg(pParse
, "expressions prohibited in PRIMARY KEY and "
3142 "UNIQUE constraints");
3143 goto exit_create_index
;
3145 if( pIndex
->aColExpr
==0 ){
3146 ExprList
*pCopy
= sqlite3ExprListDup(db
, pList
, 0);
3147 pIndex
->aColExpr
= pCopy
;
3148 if( !db
->mallocFailed
){
3150 pListItem
= &pCopy
->a
[i
];
3154 pIndex
->aiColumn
[i
] = XN_EXPR
;
3155 pIndex
->uniqNotNull
= 0;
3157 j
= pCExpr
->iColumn
;
3158 assert( j
<=0x7fff );
3161 }else if( pTab
->aCol
[j
].notNull
==0 ){
3162 pIndex
->uniqNotNull
= 0;
3164 pIndex
->aiColumn
[i
] = (i16
)j
;
3167 if( pListItem
->pExpr
->op
==TK_COLLATE
){
3169 zColl
= pListItem
->pExpr
->u
.zToken
;
3170 nColl
= sqlite3Strlen30(zColl
) + 1;
3171 assert( nExtra
>=nColl
);
3172 memcpy(zExtra
, zColl
, nColl
);
3177 zColl
= pTab
->aCol
[j
].zColl
;
3179 if( !zColl
) zColl
= sqlite3StrBINARY
;
3180 if( !db
->init
.busy
&& !sqlite3LocateCollSeq(pParse
, zColl
) ){
3181 goto exit_create_index
;
3183 pIndex
->azColl
[i
] = zColl
;
3184 requestedSortOrder
= pListItem
->sortOrder
& sortOrderMask
;
3185 pIndex
->aSortOrder
[i
] = (u8
)requestedSortOrder
;
3188 /* Append the table key to the end of the index. For WITHOUT ROWID
3189 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
3190 ** normal tables (when pPk==0) this will be the rowid.
3193 for(j
=0; j
<pPk
->nKeyCol
; j
++){
3194 int x
= pPk
->aiColumn
[j
];
3196 if( hasColumn(pIndex
->aiColumn
, pIndex
->nKeyCol
, x
) ){
3199 pIndex
->aiColumn
[i
] = x
;
3200 pIndex
->azColl
[i
] = pPk
->azColl
[j
];
3201 pIndex
->aSortOrder
[i
] = pPk
->aSortOrder
[j
];
3205 assert( i
==pIndex
->nColumn
);
3207 pIndex
->aiColumn
[i
] = XN_ROWID
;
3208 pIndex
->azColl
[i
] = sqlite3StrBINARY
;
3210 sqlite3DefaultRowEst(pIndex
);
3211 if( pParse
->pNewTable
==0 ) estimateIndexWidth(pIndex
);
3213 /* If this index contains every column of its table, then mark
3214 ** it as a covering index */
3215 assert( HasRowid(pTab
)
3216 || pTab
->iPKey
<0 || sqlite3ColumnOfIndex(pIndex
, pTab
->iPKey
)>=0 );
3217 if( pTblName
!=0 && pIndex
->nColumn
>=pTab
->nCol
){
3218 pIndex
->isCovering
= 1;
3219 for(j
=0; j
<pTab
->nCol
; j
++){
3220 if( j
==pTab
->iPKey
) continue;
3221 if( sqlite3ColumnOfIndex(pIndex
,j
)>=0 ) continue;
3222 pIndex
->isCovering
= 0;
3227 if( pTab
==pParse
->pNewTable
){
3228 /* This routine has been called to create an automatic index as a
3229 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3230 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3233 ** CREATE TABLE t(x PRIMARY KEY, y);
3234 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3236 ** Either way, check to see if the table already has such an index. If
3237 ** so, don't bother creating this one. This only applies to
3238 ** automatically created indices. Users can do as they wish with
3239 ** explicit indices.
3241 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3242 ** (and thus suppressing the second one) even if they have different
3245 ** If there are different collating sequences or if the columns of
3246 ** the constraint occur in different orders, then the constraints are
3247 ** considered distinct and both result in separate indices.
3250 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
3252 assert( IsUniqueIndex(pIdx
) );
3253 assert( pIdx
->idxType
!=SQLITE_IDXTYPE_APPDEF
);
3254 assert( IsUniqueIndex(pIndex
) );
3256 if( pIdx
->nKeyCol
!=pIndex
->nKeyCol
) continue;
3257 for(k
=0; k
<pIdx
->nKeyCol
; k
++){
3260 assert( pIdx
->aiColumn
[k
]>=0 );
3261 if( pIdx
->aiColumn
[k
]!=pIndex
->aiColumn
[k
] ) break;
3262 z1
= pIdx
->azColl
[k
];
3263 z2
= pIndex
->azColl
[k
];
3264 if( sqlite3StrICmp(z1
, z2
) ) break;
3266 if( k
==pIdx
->nKeyCol
){
3267 if( pIdx
->onError
!=pIndex
->onError
){
3268 /* This constraint creates the same index as a previous
3269 ** constraint specified somewhere in the CREATE TABLE statement.
3270 ** However the ON CONFLICT clauses are different. If both this
3271 ** constraint and the previous equivalent constraint have explicit
3272 ** ON CONFLICT clauses this is an error. Otherwise, use the
3273 ** explicitly specified behavior for the index.
3275 if( !(pIdx
->onError
==OE_Default
|| pIndex
->onError
==OE_Default
) ){
3276 sqlite3ErrorMsg(pParse
,
3277 "conflicting ON CONFLICT clauses specified", 0);
3279 if( pIdx
->onError
==OE_Default
){
3280 pIdx
->onError
= pIndex
->onError
;
3283 if( idxType
==SQLITE_IDXTYPE_PRIMARYKEY
) pIdx
->idxType
= idxType
;
3284 goto exit_create_index
;
3289 /* Link the new Index structure to its table and to the other
3290 ** in-memory database structures.
3292 assert( pParse
->nErr
==0 );
3293 if( db
->init
.busy
){
3295 assert( !IN_DECLARE_VTAB
);
3296 assert( sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
3297 p
= sqlite3HashInsert(&pIndex
->pSchema
->idxHash
,
3298 pIndex
->zName
, pIndex
);
3300 assert( p
==pIndex
); /* Malloc must have failed */
3301 sqlite3OomFault(db
);
3302 goto exit_create_index
;
3304 db
->flags
|= SQLITE_InternChanges
;
3306 pIndex
->tnum
= db
->init
.newTnum
;
3310 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3311 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3312 ** emit code to allocate the index rootpage on disk and make an entry for
3313 ** the index in the sqlite_master table and populate the index with
3314 ** content. But, do not do this if we are simply reading the sqlite_master
3315 ** table to parse the schema, or if this index is the PRIMARY KEY index
3316 ** of a WITHOUT ROWID table.
3318 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3319 ** or UNIQUE index in a CREATE TABLE statement. Since the table
3320 ** has just been created, it contains no data and the index initialization
3321 ** step can be skipped.
3323 else if( HasRowid(pTab
) || pTblName
!=0 ){
3326 int iMem
= ++pParse
->nMem
;
3328 v
= sqlite3GetVdbe(pParse
);
3329 if( v
==0 ) goto exit_create_index
;
3331 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3333 /* Create the rootpage for the index using CreateIndex. But before
3334 ** doing so, code a Noop instruction and store its address in
3335 ** Index.tnum. This is required in case this index is actually a
3336 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3337 ** that case the convertToWithoutRowidTable() routine will replace
3338 ** the Noop with a Goto to jump over the VDBE code generated below. */
3339 pIndex
->tnum
= sqlite3VdbeAddOp0(v
, OP_Noop
);
3340 sqlite3VdbeAddOp2(v
, OP_CreateIndex
, iDb
, iMem
);
3342 /* Gather the complete text of the CREATE INDEX statement into
3343 ** the zStmt variable
3346 int n
= (int)(pParse
->sLastToken
.z
- pName
->z
) + pParse
->sLastToken
.n
;
3347 if( pName
->z
[n
-1]==';' ) n
--;
3348 /* A named index with an explicit CREATE INDEX statement */
3349 zStmt
= sqlite3MPrintf(db
, "CREATE%s INDEX %.*s",
3350 onError
==OE_None
? "" : " UNIQUE", n
, pName
->z
);
3352 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3353 /* zStmt = sqlite3MPrintf(""); */
3357 /* Add an entry in sqlite_master for this index
3359 sqlite3NestedParse(pParse
,
3360 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3361 db
->aDb
[iDb
].zName
, SCHEMA_TABLE(iDb
),
3367 sqlite3DbFree(db
, zStmt
);
3369 /* Fill the index with data and reparse the schema. Code an OP_Expire
3370 ** to invalidate all pre-compiled statements.
3373 sqlite3RefillIndex(pParse
, pIndex
, iMem
);
3374 sqlite3ChangeCookie(pParse
, iDb
);
3375 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
3376 sqlite3MPrintf(db
, "name='%q' AND type='index'", pIndex
->zName
));
3377 sqlite3VdbeAddOp0(v
, OP_Expire
);
3380 sqlite3VdbeJumpHere(v
, pIndex
->tnum
);
3383 /* When adding an index to the list of indices for a table, make
3384 ** sure all indices labeled OE_Replace come after all those labeled
3385 ** OE_Ignore. This is necessary for the correct constraint check
3386 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3387 ** UPDATE and INSERT statements.
3389 if( db
->init
.busy
|| pTblName
==0 ){
3390 if( onError
!=OE_Replace
|| pTab
->pIndex
==0
3391 || pTab
->pIndex
->onError
==OE_Replace
){
3392 pIndex
->pNext
= pTab
->pIndex
;
3393 pTab
->pIndex
= pIndex
;
3395 Index
*pOther
= pTab
->pIndex
;
3396 while( pOther
->pNext
&& pOther
->pNext
->onError
!=OE_Replace
){
3397 pOther
= pOther
->pNext
;
3399 pIndex
->pNext
= pOther
->pNext
;
3400 pOther
->pNext
= pIndex
;
3405 /* Clean up before exiting */
3407 if( pIndex
) freeIndex(db
, pIndex
);
3408 sqlite3ExprDelete(db
, pPIWhere
);
3409 sqlite3ExprListDelete(db
, pList
);
3410 sqlite3SrcListDelete(db
, pTblName
);
3411 sqlite3DbFree(db
, zName
);
3415 ** Fill the Index.aiRowEst[] array with default information - information
3416 ** to be used when we have not run the ANALYZE command.
3418 ** aiRowEst[0] is supposed to contain the number of elements in the index.
3419 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3420 ** number of rows in the table that match any particular value of the
3421 ** first column of the index. aiRowEst[2] is an estimate of the number
3422 ** of rows that match any particular combination of the first 2 columns
3423 ** of the index. And so forth. It must always be the case that
3425 ** aiRowEst[N]<=aiRowEst[N-1]
3428 ** Apart from that, we have little to go on besides intuition as to
3429 ** how aiRowEst[] should be initialized. The numbers generated here
3430 ** are based on typical values found in actual indices.
3432 void sqlite3DefaultRowEst(Index
*pIdx
){
3433 /* 10, 9, 8, 7, 6 */
3434 LogEst aVal
[] = { 33, 32, 30, 28, 26 };
3435 LogEst
*a
= pIdx
->aiRowLogEst
;
3436 int nCopy
= MIN(ArraySize(aVal
), pIdx
->nKeyCol
);
3439 /* Set the first entry (number of rows in the index) to the estimated
3440 ** number of rows in the table, or half the number of rows in the table
3441 ** for a partial index. But do not let the estimate drop below 10. */
3442 a
[0] = pIdx
->pTable
->nRowLogEst
;
3443 if( pIdx
->pPartIdxWhere
!=0 ) a
[0] -= 10; assert( 10==sqlite3LogEst(2) );
3444 if( a
[0]<33 ) a
[0] = 33; assert( 33==sqlite3LogEst(10) );
3446 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3447 ** 6 and each subsequent value (if any) is 5. */
3448 memcpy(&a
[1], aVal
, nCopy
*sizeof(LogEst
));
3449 for(i
=nCopy
+1; i
<=pIdx
->nKeyCol
; i
++){
3450 a
[i
] = 23; assert( 23==sqlite3LogEst(5) );
3453 assert( 0==sqlite3LogEst(1) );
3454 if( IsUniqueIndex(pIdx
) ) a
[pIdx
->nKeyCol
] = 0;
3458 ** This routine will drop an existing named index. This routine
3459 ** implements the DROP INDEX statement.
3461 void sqlite3DropIndex(Parse
*pParse
, SrcList
*pName
, int ifExists
){
3464 sqlite3
*db
= pParse
->db
;
3467 assert( pParse
->nErr
==0 ); /* Never called with prior errors */
3468 if( db
->mallocFailed
){
3469 goto exit_drop_index
;
3471 assert( pName
->nSrc
==1 );
3472 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
3473 goto exit_drop_index
;
3475 pIndex
= sqlite3FindIndex(db
, pName
->a
[0].zName
, pName
->a
[0].zDatabase
);
3478 sqlite3ErrorMsg(pParse
, "no such index: %S", pName
, 0);
3480 sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
3482 pParse
->checkSchema
= 1;
3483 goto exit_drop_index
;
3485 if( pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
){
3486 sqlite3ErrorMsg(pParse
, "index associated with UNIQUE "
3487 "or PRIMARY KEY constraint cannot be dropped", 0);
3488 goto exit_drop_index
;
3490 iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
3491 #ifndef SQLITE_OMIT_AUTHORIZATION
3493 int code
= SQLITE_DROP_INDEX
;
3494 Table
*pTab
= pIndex
->pTable
;
3495 const char *zDb
= db
->aDb
[iDb
].zName
;
3496 const char *zTab
= SCHEMA_TABLE(iDb
);
3497 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
) ){
3498 goto exit_drop_index
;
3500 if( !OMIT_TEMPDB
&& iDb
) code
= SQLITE_DROP_TEMP_INDEX
;
3501 if( sqlite3AuthCheck(pParse
, code
, pIndex
->zName
, pTab
->zName
, zDb
) ){
3502 goto exit_drop_index
;
3507 /* Generate code to remove the index and from the master table */
3508 v
= sqlite3GetVdbe(pParse
);
3510 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3511 sqlite3NestedParse(pParse
,
3512 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3513 db
->aDb
[iDb
].zName
, SCHEMA_TABLE(iDb
), pIndex
->zName
3515 sqlite3ClearStatTables(pParse
, iDb
, "idx", pIndex
->zName
);
3516 sqlite3ChangeCookie(pParse
, iDb
);
3517 destroyRootPage(pParse
, pIndex
->tnum
, iDb
);
3518 sqlite3VdbeAddOp4(v
, OP_DropIndex
, iDb
, 0, 0, pIndex
->zName
, 0);
3522 sqlite3SrcListDelete(db
, pName
);
3526 ** pArray is a pointer to an array of objects. Each object in the
3527 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3528 ** to extend the array so that there is space for a new object at the end.
3530 ** When this function is called, *pnEntry contains the current size of
3531 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3534 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3535 ** space allocated for the new object is zeroed, *pnEntry updated to
3536 ** reflect the new size of the array and a pointer to the new allocation
3537 ** returned. *pIdx is set to the index of the new array entry in this case.
3539 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3540 ** unchanged and a copy of pArray returned.
3542 void *sqlite3ArrayAllocate(
3543 sqlite3
*db
, /* Connection to notify of malloc failures */
3544 void *pArray
, /* Array of objects. Might be reallocated */
3545 int szEntry
, /* Size of each object in the array */
3546 int *pnEntry
, /* Number of objects currently in use */
3547 int *pIdx
/* Write the index of a new slot here */
3551 if( (n
& (n
-1))==0 ){
3552 int sz
= (n
==0) ? 1 : 2*n
;
3553 void *pNew
= sqlite3DbRealloc(db
, pArray
, sz
*szEntry
);
3561 memset(&z
[n
* szEntry
], 0, szEntry
);
3568 ** Append a new element to the given IdList. Create a new IdList if
3571 ** A new IdList is returned, or NULL if malloc() fails.
3573 IdList
*sqlite3IdListAppend(sqlite3
*db
, IdList
*pList
, Token
*pToken
){
3576 pList
= sqlite3DbMallocZero(db
, sizeof(IdList
) );
3577 if( pList
==0 ) return 0;
3579 pList
->a
= sqlite3ArrayAllocate(
3582 sizeof(pList
->a
[0]),
3587 sqlite3IdListDelete(db
, pList
);
3590 pList
->a
[i
].zName
= sqlite3NameFromToken(db
, pToken
);
3595 ** Delete an IdList.
3597 void sqlite3IdListDelete(sqlite3
*db
, IdList
*pList
){
3599 if( pList
==0 ) return;
3600 for(i
=0; i
<pList
->nId
; i
++){
3601 sqlite3DbFree(db
, pList
->a
[i
].zName
);
3603 sqlite3DbFree(db
, pList
->a
);
3604 sqlite3DbFree(db
, pList
);
3608 ** Return the index in pList of the identifier named zId. Return -1
3611 int sqlite3IdListIndex(IdList
*pList
, const char *zName
){
3613 if( pList
==0 ) return -1;
3614 for(i
=0; i
<pList
->nId
; i
++){
3615 if( sqlite3StrICmp(pList
->a
[i
].zName
, zName
)==0 ) return i
;
3621 ** Expand the space allocated for the given SrcList object by
3622 ** creating nExtra new slots beginning at iStart. iStart is zero based.
3623 ** New slots are zeroed.
3625 ** For example, suppose a SrcList initially contains two entries: A,B.
3626 ** To append 3 new entries onto the end, do this:
3628 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3630 ** After the call above it would contain: A, B, nil, nil, nil.
3631 ** If the iStart argument had been 1 instead of 2, then the result
3632 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
3633 ** the iStart value would be 0. The result then would
3634 ** be: nil, nil, nil, A, B.
3636 ** If a memory allocation fails the SrcList is unchanged. The
3637 ** db->mallocFailed flag will be set to true.
3639 SrcList
*sqlite3SrcListEnlarge(
3640 sqlite3
*db
, /* Database connection to notify of OOM errors */
3641 SrcList
*pSrc
, /* The SrcList to be enlarged */
3642 int nExtra
, /* Number of new slots to add to pSrc->a[] */
3643 int iStart
/* Index in pSrc->a[] of first new slot */
3647 /* Sanity checking on calling parameters */
3648 assert( iStart
>=0 );
3649 assert( nExtra
>=1 );
3651 assert( iStart
<=pSrc
->nSrc
);
3653 /* Allocate additional space if needed */
3654 if( (u32
)pSrc
->nSrc
+nExtra
>pSrc
->nAlloc
){
3656 int nAlloc
= pSrc
->nSrc
+nExtra
;
3658 pNew
= sqlite3DbRealloc(db
, pSrc
,
3659 sizeof(*pSrc
) + (nAlloc
-1)*sizeof(pSrc
->a
[0]) );
3661 assert( db
->mallocFailed
);
3665 nGot
= (sqlite3DbMallocSize(db
, pNew
) - sizeof(*pSrc
))/sizeof(pSrc
->a
[0])+1;
3666 pSrc
->nAlloc
= nGot
;
3669 /* Move existing slots that come after the newly inserted slots
3670 ** out of the way */
3671 for(i
=pSrc
->nSrc
-1; i
>=iStart
; i
--){
3672 pSrc
->a
[i
+nExtra
] = pSrc
->a
[i
];
3674 pSrc
->nSrc
+= nExtra
;
3676 /* Zero the newly allocated slots */
3677 memset(&pSrc
->a
[iStart
], 0, sizeof(pSrc
->a
[0])*nExtra
);
3678 for(i
=iStart
; i
<iStart
+nExtra
; i
++){
3679 pSrc
->a
[i
].iCursor
= -1;
3682 /* Return a pointer to the enlarged SrcList */
3688 ** Append a new table name to the given SrcList. Create a new SrcList if
3689 ** need be. A new entry is created in the SrcList even if pTable is NULL.
3691 ** A SrcList is returned, or NULL if there is an OOM error. The returned
3692 ** SrcList might be the same as the SrcList that was input or it might be
3693 ** a new one. If an OOM error does occurs, then the prior value of pList
3694 ** that is input to this routine is automatically freed.
3696 ** If pDatabase is not null, it means that the table has an optional
3697 ** database name prefix. Like this: "database.table". The pDatabase
3698 ** points to the table name and the pTable points to the database name.
3699 ** The SrcList.a[].zName field is filled with the table name which might
3700 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3701 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3702 ** or with NULL if no database is specified.
3704 ** In other words, if call like this:
3706 ** sqlite3SrcListAppend(D,A,B,0);
3708 ** Then B is a table name and the database name is unspecified. If called
3711 ** sqlite3SrcListAppend(D,A,B,C);
3713 ** Then C is the table name and B is the database name. If C is defined
3714 ** then so is B. In other words, we never have a case where:
3716 ** sqlite3SrcListAppend(D,A,0,C);
3718 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3719 ** before being added to the SrcList.
3721 SrcList
*sqlite3SrcListAppend(
3722 sqlite3
*db
, /* Connection to notify of malloc failures */
3723 SrcList
*pList
, /* Append to this SrcList. NULL creates a new SrcList */
3724 Token
*pTable
, /* Table to append */
3725 Token
*pDatabase
/* Database of the table */
3727 struct SrcList_item
*pItem
;
3728 assert( pDatabase
==0 || pTable
!=0 ); /* Cannot have C without B */
3731 pList
= sqlite3DbMallocRawNN(db
, sizeof(SrcList
) );
3732 if( pList
==0 ) return 0;
3736 pList
= sqlite3SrcListEnlarge(db
, pList
, 1, pList
->nSrc
);
3737 if( db
->mallocFailed
){
3738 sqlite3SrcListDelete(db
, pList
);
3741 pItem
= &pList
->a
[pList
->nSrc
-1];
3742 if( pDatabase
&& pDatabase
->z
==0 ){
3746 Token
*pTemp
= pDatabase
;
3750 pItem
->zName
= sqlite3NameFromToken(db
, pTable
);
3751 pItem
->zDatabase
= sqlite3NameFromToken(db
, pDatabase
);
3756 ** Assign VdbeCursor index numbers to all tables in a SrcList
3758 void sqlite3SrcListAssignCursors(Parse
*pParse
, SrcList
*pList
){
3760 struct SrcList_item
*pItem
;
3761 assert(pList
|| pParse
->db
->mallocFailed
);
3763 for(i
=0, pItem
=pList
->a
; i
<pList
->nSrc
; i
++, pItem
++){
3764 if( pItem
->iCursor
>=0 ) break;
3765 pItem
->iCursor
= pParse
->nTab
++;
3766 if( pItem
->pSelect
){
3767 sqlite3SrcListAssignCursors(pParse
, pItem
->pSelect
->pSrc
);
3774 ** Delete an entire SrcList including all its substructure.
3776 void sqlite3SrcListDelete(sqlite3
*db
, SrcList
*pList
){
3778 struct SrcList_item
*pItem
;
3779 if( pList
==0 ) return;
3780 for(pItem
=pList
->a
, i
=0; i
<pList
->nSrc
; i
++, pItem
++){
3781 sqlite3DbFree(db
, pItem
->zDatabase
);
3782 sqlite3DbFree(db
, pItem
->zName
);
3783 sqlite3DbFree(db
, pItem
->zAlias
);
3784 if( pItem
->fg
.isIndexedBy
) sqlite3DbFree(db
, pItem
->u1
.zIndexedBy
);
3785 if( pItem
->fg
.isTabFunc
) sqlite3ExprListDelete(db
, pItem
->u1
.pFuncArg
);
3786 sqlite3DeleteTable(db
, pItem
->pTab
);
3787 sqlite3SelectDelete(db
, pItem
->pSelect
);
3788 sqlite3ExprDelete(db
, pItem
->pOn
);
3789 sqlite3IdListDelete(db
, pItem
->pUsing
);
3791 sqlite3DbFree(db
, pList
);
3795 ** This routine is called by the parser to add a new term to the
3796 ** end of a growing FROM clause. The "p" parameter is the part of
3797 ** the FROM clause that has already been constructed. "p" is NULL
3798 ** if this is the first term of the FROM clause. pTable and pDatabase
3799 ** are the name of the table and database named in the FROM clause term.
3800 ** pDatabase is NULL if the database name qualifier is missing - the
3801 ** usual case. If the term has an alias, then pAlias points to the
3802 ** alias token. If the term is a subquery, then pSubquery is the
3803 ** SELECT statement that the subquery encodes. The pTable and
3804 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3805 ** parameters are the content of the ON and USING clauses.
3807 ** Return a new SrcList which encodes is the FROM with the new
3810 SrcList
*sqlite3SrcListAppendFromTerm(
3811 Parse
*pParse
, /* Parsing context */
3812 SrcList
*p
, /* The left part of the FROM clause already seen */
3813 Token
*pTable
, /* Name of the table to add to the FROM clause */
3814 Token
*pDatabase
, /* Name of the database containing pTable */
3815 Token
*pAlias
, /* The right-hand side of the AS subexpression */
3816 Select
*pSubquery
, /* A subquery used in place of a table name */
3817 Expr
*pOn
, /* The ON clause of a join */
3818 IdList
*pUsing
/* The USING clause of a join */
3820 struct SrcList_item
*pItem
;
3821 sqlite3
*db
= pParse
->db
;
3822 if( !p
&& (pOn
|| pUsing
) ){
3823 sqlite3ErrorMsg(pParse
, "a JOIN clause is required before %s",
3824 (pOn
? "ON" : "USING")
3826 goto append_from_error
;
3828 p
= sqlite3SrcListAppend(db
, p
, pTable
, pDatabase
);
3829 if( p
==0 || NEVER(p
->nSrc
==0) ){
3830 goto append_from_error
;
3832 pItem
= &p
->a
[p
->nSrc
-1];
3833 assert( pAlias
!=0 );
3835 pItem
->zAlias
= sqlite3NameFromToken(db
, pAlias
);
3837 pItem
->pSelect
= pSubquery
;
3839 pItem
->pUsing
= pUsing
;
3844 sqlite3ExprDelete(db
, pOn
);
3845 sqlite3IdListDelete(db
, pUsing
);
3846 sqlite3SelectDelete(db
, pSubquery
);
3851 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3852 ** element of the source-list passed as the second argument.
3854 void sqlite3SrcListIndexedBy(Parse
*pParse
, SrcList
*p
, Token
*pIndexedBy
){
3855 assert( pIndexedBy
!=0 );
3856 if( p
&& ALWAYS(p
->nSrc
>0) ){
3857 struct SrcList_item
*pItem
= &p
->a
[p
->nSrc
-1];
3858 assert( pItem
->fg
.notIndexed
==0 );
3859 assert( pItem
->fg
.isIndexedBy
==0 );
3860 assert( pItem
->fg
.isTabFunc
==0 );
3861 if( pIndexedBy
->n
==1 && !pIndexedBy
->z
){
3862 /* A "NOT INDEXED" clause was supplied. See parse.y
3863 ** construct "indexed_opt" for details. */
3864 pItem
->fg
.notIndexed
= 1;
3866 pItem
->u1
.zIndexedBy
= sqlite3NameFromToken(pParse
->db
, pIndexedBy
);
3867 pItem
->fg
.isIndexedBy
= (pItem
->u1
.zIndexedBy
!=0);
3873 ** Add the list of function arguments to the SrcList entry for a
3874 ** table-valued-function.
3876 void sqlite3SrcListFuncArgs(Parse
*pParse
, SrcList
*p
, ExprList
*pList
){
3878 struct SrcList_item
*pItem
= &p
->a
[p
->nSrc
-1];
3879 assert( pItem
->fg
.notIndexed
==0 );
3880 assert( pItem
->fg
.isIndexedBy
==0 );
3881 assert( pItem
->fg
.isTabFunc
==0 );
3882 pItem
->u1
.pFuncArg
= pList
;
3883 pItem
->fg
.isTabFunc
= 1;
3885 sqlite3ExprListDelete(pParse
->db
, pList
);
3890 ** When building up a FROM clause in the parser, the join operator
3891 ** is initially attached to the left operand. But the code generator
3892 ** expects the join operator to be on the right operand. This routine
3893 ** Shifts all join operators from left to right for an entire FROM
3896 ** Example: Suppose the join is like this:
3898 ** A natural cross join B
3900 ** The operator is "natural cross join". The A and B operands are stored
3901 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
3902 ** operator with A. This routine shifts that operator over to B.
3904 void sqlite3SrcListShiftJoinType(SrcList
*p
){
3907 for(i
=p
->nSrc
-1; i
>0; i
--){
3908 p
->a
[i
].fg
.jointype
= p
->a
[i
-1].fg
.jointype
;
3910 p
->a
[0].fg
.jointype
= 0;
3915 ** Generate VDBE code for a BEGIN statement.
3917 void sqlite3BeginTransaction(Parse
*pParse
, int type
){
3922 assert( pParse
!=0 );
3925 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
, "BEGIN", 0, 0) ){
3928 v
= sqlite3GetVdbe(pParse
);
3930 if( type
!=TK_DEFERRED
){
3931 for(i
=0; i
<db
->nDb
; i
++){
3932 sqlite3VdbeAddOp2(v
, OP_Transaction
, i
, (type
==TK_EXCLUSIVE
)+1);
3933 sqlite3VdbeUsesBtree(v
, i
);
3936 sqlite3VdbeAddOp0(v
, OP_AutoCommit
);
3940 ** Generate VDBE code for a COMMIT statement.
3942 void sqlite3CommitTransaction(Parse
*pParse
){
3945 assert( pParse
!=0 );
3946 assert( pParse
->db
!=0 );
3947 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
, "COMMIT", 0, 0) ){
3950 v
= sqlite3GetVdbe(pParse
);
3952 sqlite3VdbeAddOp1(v
, OP_AutoCommit
, 1);
3957 ** Generate VDBE code for a ROLLBACK statement.
3959 void sqlite3RollbackTransaction(Parse
*pParse
){
3962 assert( pParse
!=0 );
3963 assert( pParse
->db
!=0 );
3964 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
, "ROLLBACK", 0, 0) ){
3967 v
= sqlite3GetVdbe(pParse
);
3969 sqlite3VdbeAddOp2(v
, OP_AutoCommit
, 1, 1);
3974 ** This function is called by the parser when it parses a command to create,
3975 ** release or rollback an SQL savepoint.
3977 void sqlite3Savepoint(Parse
*pParse
, int op
, Token
*pName
){
3978 char *zName
= sqlite3NameFromToken(pParse
->db
, pName
);
3980 Vdbe
*v
= sqlite3GetVdbe(pParse
);
3981 #ifndef SQLITE_OMIT_AUTHORIZATION
3982 static const char * const az
[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3983 assert( !SAVEPOINT_BEGIN
&& SAVEPOINT_RELEASE
==1 && SAVEPOINT_ROLLBACK
==2 );
3985 if( !v
|| sqlite3AuthCheck(pParse
, SQLITE_SAVEPOINT
, az
[op
], zName
, 0) ){
3986 sqlite3DbFree(pParse
->db
, zName
);
3989 sqlite3VdbeAddOp4(v
, OP_Savepoint
, op
, 0, 0, zName
, P4_DYNAMIC
);
3994 ** Make sure the TEMP database is open and available for use. Return
3995 ** the number of errors. Leave any error messages in the pParse structure.
3997 int sqlite3OpenTempDatabase(Parse
*pParse
){
3998 sqlite3
*db
= pParse
->db
;
3999 if( db
->aDb
[1].pBt
==0 && !pParse
->explain
){
4002 static const int flags
=
4003 SQLITE_OPEN_READWRITE
|
4004 SQLITE_OPEN_CREATE
|
4005 SQLITE_OPEN_EXCLUSIVE
|
4006 SQLITE_OPEN_DELETEONCLOSE
|
4007 SQLITE_OPEN_TEMP_DB
;
4009 rc
= sqlite3BtreeOpen(db
->pVfs
, 0, db
, &pBt
, 0, flags
);
4010 if( rc
!=SQLITE_OK
){
4011 sqlite3ErrorMsg(pParse
, "unable to open a temporary database "
4012 "file for storing temporary tables");
4016 db
->aDb
[1].pBt
= pBt
;
4017 assert( db
->aDb
[1].pSchema
);
4018 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
, -1, 0) ){
4019 sqlite3OomFault(db
);
4027 ** Record the fact that the schema cookie will need to be verified
4028 ** for database iDb. The code to actually verify the schema cookie
4029 ** will occur at the end of the top-level VDBE and will be generated
4030 ** later, by sqlite3FinishCoding().
4032 void sqlite3CodeVerifySchema(Parse
*pParse
, int iDb
){
4033 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4034 sqlite3
*db
= pToplevel
->db
;
4036 assert( iDb
>=0 && iDb
<db
->nDb
);
4037 assert( db
->aDb
[iDb
].pBt
!=0 || iDb
==1 );
4038 assert( iDb
<SQLITE_MAX_ATTACHED
+2 );
4039 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
4040 if( DbMaskTest(pToplevel
->cookieMask
, iDb
)==0 ){
4041 DbMaskSet(pToplevel
->cookieMask
, iDb
);
4042 pToplevel
->cookieValue
[iDb
] = db
->aDb
[iDb
].pSchema
->schema_cookie
;
4043 if( !OMIT_TEMPDB
&& iDb
==1 ){
4044 sqlite3OpenTempDatabase(pToplevel
);
4050 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4051 ** attached database. Otherwise, invoke it for the database named zDb only.
4053 void sqlite3CodeVerifyNamedSchema(Parse
*pParse
, const char *zDb
){
4054 sqlite3
*db
= pParse
->db
;
4056 for(i
=0; i
<db
->nDb
; i
++){
4057 Db
*pDb
= &db
->aDb
[i
];
4058 if( pDb
->pBt
&& (!zDb
|| 0==sqlite3StrICmp(zDb
, pDb
->zName
)) ){
4059 sqlite3CodeVerifySchema(pParse
, i
);
4065 ** Generate VDBE code that prepares for doing an operation that
4066 ** might change the database.
4068 ** This routine starts a new transaction if we are not already within
4069 ** a transaction. If we are already within a transaction, then a checkpoint
4070 ** is set if the setStatement parameter is true. A checkpoint should
4071 ** be set for operations that might fail (due to a constraint) part of
4072 ** the way through and which will need to undo some writes without having to
4073 ** rollback the whole transaction. For operations where all constraints
4074 ** can be checked before any changes are made to the database, it is never
4075 ** necessary to undo a write and the checkpoint should not be set.
4077 void sqlite3BeginWriteOperation(Parse
*pParse
, int setStatement
, int iDb
){
4078 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4079 sqlite3CodeVerifySchema(pParse
, iDb
);
4080 DbMaskSet(pToplevel
->writeMask
, iDb
);
4081 pToplevel
->isMultiWrite
|= setStatement
;
4085 ** Indicate that the statement currently under construction might write
4086 ** more than one entry (example: deleting one row then inserting another,
4087 ** inserting multiple rows in a table, or inserting a row and index entries.)
4088 ** If an abort occurs after some of these writes have completed, then it will
4089 ** be necessary to undo the completed writes.
4091 void sqlite3MultiWrite(Parse
*pParse
){
4092 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4093 pToplevel
->isMultiWrite
= 1;
4097 ** The code generator calls this routine if is discovers that it is
4098 ** possible to abort a statement prior to completion. In order to
4099 ** perform this abort without corrupting the database, we need to make
4100 ** sure that the statement is protected by a statement transaction.
4102 ** Technically, we only need to set the mayAbort flag if the
4103 ** isMultiWrite flag was previously set. There is a time dependency
4104 ** such that the abort must occur after the multiwrite. This makes
4105 ** some statements involving the REPLACE conflict resolution algorithm
4106 ** go a little faster. But taking advantage of this time dependency
4107 ** makes it more difficult to prove that the code is correct (in
4108 ** particular, it prevents us from writing an effective
4109 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
4110 ** to take the safe route and skip the optimization.
4112 void sqlite3MayAbort(Parse
*pParse
){
4113 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4114 pToplevel
->mayAbort
= 1;
4118 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4119 ** error. The onError parameter determines which (if any) of the statement
4120 ** and/or current transaction is rolled back.
4122 void sqlite3HaltConstraint(
4123 Parse
*pParse
, /* Parsing context */
4124 int errCode
, /* extended error code */
4125 int onError
, /* Constraint type */
4126 char *p4
, /* Error message */
4127 i8 p4type
, /* P4_STATIC or P4_TRANSIENT */
4128 u8 p5Errmsg
/* P5_ErrMsg type */
4130 Vdbe
*v
= sqlite3GetVdbe(pParse
);
4131 assert( (errCode
&0xff)==SQLITE_CONSTRAINT
);
4132 if( onError
==OE_Abort
){
4133 sqlite3MayAbort(pParse
);
4135 sqlite3VdbeAddOp4(v
, OP_Halt
, errCode
, onError
, 0, p4
, p4type
);
4136 sqlite3VdbeChangeP5(v
, p5Errmsg
);
4140 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4142 void sqlite3UniqueConstraint(
4143 Parse
*pParse
, /* Parsing context */
4144 int onError
, /* Constraint type */
4145 Index
*pIdx
/* The index that triggers the constraint */
4150 Table
*pTab
= pIdx
->pTable
;
4152 sqlite3StrAccumInit(&errMsg
, pParse
->db
, 0, 0, 200);
4153 if( pIdx
->aColExpr
){
4154 sqlite3XPrintf(&errMsg
, "index '%q'", pIdx
->zName
);
4156 for(j
=0; j
<pIdx
->nKeyCol
; j
++){
4158 assert( pIdx
->aiColumn
[j
]>=0 );
4159 zCol
= pTab
->aCol
[pIdx
->aiColumn
[j
]].zName
;
4160 if( j
) sqlite3StrAccumAppend(&errMsg
, ", ", 2);
4161 sqlite3XPrintf(&errMsg
, "%s.%s", pTab
->zName
, zCol
);
4164 zErr
= sqlite3StrAccumFinish(&errMsg
);
4165 sqlite3HaltConstraint(pParse
,
4166 IsPrimaryKeyIndex(pIdx
) ? SQLITE_CONSTRAINT_PRIMARYKEY
4167 : SQLITE_CONSTRAINT_UNIQUE
,
4168 onError
, zErr
, P4_DYNAMIC
, P5_ConstraintUnique
);
4173 ** Code an OP_Halt due to non-unique rowid.
4175 void sqlite3RowidConstraint(
4176 Parse
*pParse
, /* Parsing context */
4177 int onError
, /* Conflict resolution algorithm */
4178 Table
*pTab
/* The table with the non-unique rowid */
4182 if( pTab
->iPKey
>=0 ){
4183 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.%s", pTab
->zName
,
4184 pTab
->aCol
[pTab
->iPKey
].zName
);
4185 rc
= SQLITE_CONSTRAINT_PRIMARYKEY
;
4187 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.rowid", pTab
->zName
);
4188 rc
= SQLITE_CONSTRAINT_ROWID
;
4190 sqlite3HaltConstraint(pParse
, rc
, onError
, zMsg
, P4_DYNAMIC
,
4191 P5_ConstraintUnique
);
4195 ** Check to see if pIndex uses the collating sequence pColl. Return
4196 ** true if it does and false if it does not.
4198 #ifndef SQLITE_OMIT_REINDEX
4199 static int collationMatch(const char *zColl
, Index
*pIndex
){
4202 for(i
=0; i
<pIndex
->nColumn
; i
++){
4203 const char *z
= pIndex
->azColl
[i
];
4204 assert( z
!=0 || pIndex
->aiColumn
[i
]<0 );
4205 if( pIndex
->aiColumn
[i
]>=0 && 0==sqlite3StrICmp(z
, zColl
) ){
4214 ** Recompute all indices of pTab that use the collating sequence pColl.
4215 ** If pColl==0 then recompute all indices of pTab.
4217 #ifndef SQLITE_OMIT_REINDEX
4218 static void reindexTable(Parse
*pParse
, Table
*pTab
, char const *zColl
){
4219 Index
*pIndex
; /* An index associated with pTab */
4221 for(pIndex
=pTab
->pIndex
; pIndex
; pIndex
=pIndex
->pNext
){
4222 if( zColl
==0 || collationMatch(zColl
, pIndex
) ){
4223 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
4224 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
4225 sqlite3RefillIndex(pParse
, pIndex
, -1);
4232 ** Recompute all indices of all tables in all databases where the
4233 ** indices use the collating sequence pColl. If pColl==0 then recompute
4234 ** all indices everywhere.
4236 #ifndef SQLITE_OMIT_REINDEX
4237 static void reindexDatabases(Parse
*pParse
, char const *zColl
){
4238 Db
*pDb
; /* A single database */
4239 int iDb
; /* The database index number */
4240 sqlite3
*db
= pParse
->db
; /* The database connection */
4241 HashElem
*k
; /* For looping over tables in pDb */
4242 Table
*pTab
; /* A table in the database */
4244 assert( sqlite3BtreeHoldsAllMutexes(db
) ); /* Needed for schema access */
4245 for(iDb
=0, pDb
=db
->aDb
; iDb
<db
->nDb
; iDb
++, pDb
++){
4247 for(k
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
4248 pTab
= (Table
*)sqliteHashData(k
);
4249 reindexTable(pParse
, pTab
, zColl
);
4256 ** Generate code for the REINDEX command.
4259 ** REINDEX <collation> -- 2
4260 ** REINDEX ?<database>.?<tablename> -- 3
4261 ** REINDEX ?<database>.?<indexname> -- 4
4263 ** Form 1 causes all indices in all attached databases to be rebuilt.
4264 ** Form 2 rebuilds all indices in all databases that use the named
4265 ** collating function. Forms 3 and 4 rebuild the named index or all
4266 ** indices associated with the named table.
4268 #ifndef SQLITE_OMIT_REINDEX
4269 void sqlite3Reindex(Parse
*pParse
, Token
*pName1
, Token
*pName2
){
4270 CollSeq
*pColl
; /* Collating sequence to be reindexed, or NULL */
4271 char *z
; /* Name of a table or index */
4272 const char *zDb
; /* Name of the database */
4273 Table
*pTab
; /* A table in the database */
4274 Index
*pIndex
; /* An index associated with pTab */
4275 int iDb
; /* The database index number */
4276 sqlite3
*db
= pParse
->db
; /* The database connection */
4277 Token
*pObjName
; /* Name of the table or index to be reindexed */
4279 /* Read the database schema. If an error occurs, leave an error message
4280 ** and code in pParse and return NULL. */
4281 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
4286 reindexDatabases(pParse
, 0);
4288 }else if( NEVER(pName2
==0) || pName2
->z
==0 ){
4290 assert( pName1
->z
);
4291 zColl
= sqlite3NameFromToken(pParse
->db
, pName1
);
4292 if( !zColl
) return;
4293 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
4295 reindexDatabases(pParse
, zColl
);
4296 sqlite3DbFree(db
, zColl
);
4299 sqlite3DbFree(db
, zColl
);
4301 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pObjName
);
4303 z
= sqlite3NameFromToken(db
, pObjName
);
4305 zDb
= db
->aDb
[iDb
].zName
;
4306 pTab
= sqlite3FindTable(db
, z
, zDb
);
4308 reindexTable(pParse
, pTab
, 0);
4309 sqlite3DbFree(db
, z
);
4312 pIndex
= sqlite3FindIndex(db
, z
, zDb
);
4313 sqlite3DbFree(db
, z
);
4315 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
4316 sqlite3RefillIndex(pParse
, pIndex
, -1);
4319 sqlite3ErrorMsg(pParse
, "unable to identify the object to be reindexed");
4324 ** Return a KeyInfo structure that is appropriate for the given Index.
4326 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4327 ** when it has finished using it.
4329 KeyInfo
*sqlite3KeyInfoOfIndex(Parse
*pParse
, Index
*pIdx
){
4331 int nCol
= pIdx
->nColumn
;
4332 int nKey
= pIdx
->nKeyCol
;
4334 if( pParse
->nErr
) return 0;
4335 if( pIdx
->uniqNotNull
){
4336 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nKey
, nCol
-nKey
);
4338 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nCol
, 0);
4341 assert( sqlite3KeyInfoIsWriteable(pKey
) );
4342 for(i
=0; i
<nCol
; i
++){
4343 const char *zColl
= pIdx
->azColl
[i
];
4344 pKey
->aColl
[i
] = zColl
==sqlite3StrBINARY
? 0 :
4345 sqlite3LocateCollSeq(pParse
, zColl
);
4346 pKey
->aSortOrder
[i
] = pIdx
->aSortOrder
[i
];
4349 sqlite3KeyInfoUnref(pKey
);
4356 #ifndef SQLITE_OMIT_CTE
4358 ** This routine is invoked once per CTE by the parser while parsing a
4361 With
*sqlite3WithAdd(
4362 Parse
*pParse
, /* Parsing context */
4363 With
*pWith
, /* Existing WITH clause, or NULL */
4364 Token
*pName
, /* Name of the common-table */
4365 ExprList
*pArglist
, /* Optional column name list for the table */
4366 Select
*pQuery
/* Query used to initialize the table */
4368 sqlite3
*db
= pParse
->db
;
4372 /* Check that the CTE name is unique within this WITH clause. If
4373 ** not, store an error in the Parse structure. */
4374 zName
= sqlite3NameFromToken(pParse
->db
, pName
);
4375 if( zName
&& pWith
){
4377 for(i
=0; i
<pWith
->nCte
; i
++){
4378 if( sqlite3StrICmp(zName
, pWith
->a
[i
].zName
)==0 ){
4379 sqlite3ErrorMsg(pParse
, "duplicate WITH table name: %s", zName
);
4385 int nByte
= sizeof(*pWith
) + (sizeof(pWith
->a
[1]) * pWith
->nCte
);
4386 pNew
= sqlite3DbRealloc(db
, pWith
, nByte
);
4388 pNew
= sqlite3DbMallocZero(db
, sizeof(*pWith
));
4390 assert( (pNew
!=0 && zName
!=0) || db
->mallocFailed
);
4392 if( db
->mallocFailed
){
4393 sqlite3ExprListDelete(db
, pArglist
);
4394 sqlite3SelectDelete(db
, pQuery
);
4395 sqlite3DbFree(db
, zName
);
4398 pNew
->a
[pNew
->nCte
].pSelect
= pQuery
;
4399 pNew
->a
[pNew
->nCte
].pCols
= pArglist
;
4400 pNew
->a
[pNew
->nCte
].zName
= zName
;
4401 pNew
->a
[pNew
->nCte
].zCteErr
= 0;
4409 ** Free the contents of the With object passed as the second argument.
4411 void sqlite3WithDelete(sqlite3
*db
, With
*pWith
){
4414 for(i
=0; i
<pWith
->nCte
; i
++){
4415 struct Cte
*pCte
= &pWith
->a
[i
];
4416 sqlite3ExprListDelete(db
, pCte
->pCols
);
4417 sqlite3SelectDelete(db
, pCte
->pSelect
);
4418 sqlite3DbFree(db
, pCte
->zName
);
4420 sqlite3DbFree(db
, pWith
);
4423 #endif /* !defined(SQLITE_OMIT_CTE) */