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 *zLockName
; /* Name of the table */
40 ** Record the fact that we want to lock a table at run-time.
42 ** The table to be locked has root page iTab and is found in database iDb.
43 ** A read or a write lock can be taken depending on isWritelock.
45 ** This routine just records the fact that the lock is desired. The
46 ** code to make the lock occur is generated by a later call to
47 ** codeTableLocks() which occurs during sqlite3FinishCoding().
49 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
);
63 if( !sqlite3BtreeSharable(pParse
->db
->aDb
[iDb
].pBt
) ) return;
64 for(i
=0; i
<pToplevel
->nTableLock
; i
++){
65 p
= &pToplevel
->aTableLock
[i
];
66 if( p
->iDb
==iDb
&& p
->iTab
==iTab
){
67 p
->isWriteLock
= (p
->isWriteLock
|| isWriteLock
);
72 nBytes
= sizeof(TableLock
) * (pToplevel
->nTableLock
+1);
73 pToplevel
->aTableLock
=
74 sqlite3DbReallocOrFree(pToplevel
->db
, pToplevel
->aTableLock
, nBytes
);
75 if( pToplevel
->aTableLock
){
76 p
= &pToplevel
->aTableLock
[pToplevel
->nTableLock
++];
79 p
->isWriteLock
= isWriteLock
;
82 pToplevel
->nTableLock
= 0;
83 sqlite3OomFault(pToplevel
->db
);
88 ** Code an OP_TableLock instruction for each table locked by the
89 ** statement (configured by calls to sqlite3TableLock()).
91 static void codeTableLocks(Parse
*pParse
){
95 pVdbe
= sqlite3GetVdbe(pParse
);
96 assert( pVdbe
!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
98 for(i
=0; i
<pParse
->nTableLock
; i
++){
99 TableLock
*p
= &pParse
->aTableLock
[i
];
101 sqlite3VdbeAddOp4(pVdbe
, OP_TableLock
, p1
, p
->iTab
, p
->isWriteLock
,
102 p
->zLockName
, P4_STATIC
);
106 #define codeTableLocks(x)
110 ** Return TRUE if the given yDbMask object is empty - if it contains no
111 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
112 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
114 #if SQLITE_MAX_ATTACHED>30
115 int sqlite3DbMaskAllZero(yDbMask m
){
117 for(i
=0; i
<sizeof(yDbMask
); i
++) if( m
[i
] ) return 0;
123 ** This routine is called after a single SQL statement has been
124 ** parsed and a VDBE program to execute that statement has been
125 ** prepared. This routine puts the finishing touches on the
126 ** VDBE program and resets the pParse structure for the next
129 ** Note that if an error occurred, it might be the case that
130 ** no VDBE code was generated.
132 void sqlite3FinishCoding(Parse
*pParse
){
136 assert( pParse
->pToplevel
==0 );
138 if( pParse
->nested
) return;
139 if( db
->mallocFailed
|| pParse
->nErr
){
140 if( pParse
->rc
==SQLITE_OK
) pParse
->rc
= SQLITE_ERROR
;
144 /* Begin by generating some termination code at the end of the
147 v
= sqlite3GetVdbe(pParse
);
148 assert( !pParse
->isMultiWrite
149 || sqlite3VdbeAssertMayAbort(v
, pParse
->mayAbort
));
151 sqlite3VdbeAddOp0(v
, OP_Halt
);
153 #if SQLITE_USER_AUTHENTICATION
154 if( pParse
->nTableLock
>0 && db
->init
.busy
==0 ){
155 sqlite3UserAuthInit(db
);
156 if( db
->auth
.authLevel
<UAUTH_User
){
157 sqlite3ErrorMsg(pParse
, "user not authenticated");
158 pParse
->rc
= SQLITE_AUTH_USER
;
164 /* The cookie mask contains one bit for each database file open.
165 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
166 ** set for each database that is used. Generate code to start a
167 ** transaction on each used database and to verify the schema cookie
168 ** on each used database.
170 if( db
->mallocFailed
==0
171 && (DbMaskNonZero(pParse
->cookieMask
) || pParse
->pConstExpr
)
174 assert( sqlite3VdbeGetOp(v
, 0)->opcode
==OP_Init
);
175 sqlite3VdbeJumpHere(v
, 0);
176 for(iDb
=0; iDb
<db
->nDb
; iDb
++){
178 if( DbMaskTest(pParse
->cookieMask
, iDb
)==0 ) continue;
179 sqlite3VdbeUsesBtree(v
, iDb
);
180 pSchema
= db
->aDb
[iDb
].pSchema
;
181 sqlite3VdbeAddOp4Int(v
,
182 OP_Transaction
, /* Opcode */
184 DbMaskTest(pParse
->writeMask
,iDb
), /* P2 */
185 pSchema
->schema_cookie
, /* P3 */
186 pSchema
->iGeneration
/* P4 */
188 if( db
->init
.busy
==0 ) sqlite3VdbeChangeP5(v
, 1);
190 "usesStmtJournal=%d", pParse
->mayAbort
&& pParse
->isMultiWrite
));
192 #ifndef SQLITE_OMIT_VIRTUALTABLE
193 for(i
=0; i
<pParse
->nVtabLock
; i
++){
194 char *vtab
= (char *)sqlite3GetVTable(db
, pParse
->apVtabLock
[i
]);
195 sqlite3VdbeAddOp4(v
, OP_VBegin
, 0, 0, 0, vtab
, P4_VTAB
);
197 pParse
->nVtabLock
= 0;
200 /* Once all the cookies have been verified and transactions opened,
201 ** obtain the required table-locks. This is a no-op unless the
202 ** shared-cache feature is enabled.
204 codeTableLocks(pParse
);
206 /* Initialize any AUTOINCREMENT data structures required.
208 sqlite3AutoincrementBegin(pParse
);
210 /* Code constant expressions that where factored out of inner loops */
211 if( pParse
->pConstExpr
){
212 ExprList
*pEL
= pParse
->pConstExpr
;
213 pParse
->okConstFactor
= 0;
214 for(i
=0; i
<pEL
->nExpr
; i
++){
215 sqlite3ExprCode(pParse
, pEL
->a
[i
].pExpr
, pEL
->a
[i
].u
.iConstExprReg
);
219 /* Finally, jump back to the beginning of the executable code. */
220 sqlite3VdbeGoto(v
, 1);
225 /* Get the VDBE program ready for execution
227 if( v
&& pParse
->nErr
==0 && !db
->mallocFailed
){
228 assert( pParse
->iCacheLevel
==0 ); /* Disables and re-enables match */
229 /* A minimum of one cursor is required if autoincrement is used
230 * See ticket [a696379c1f08866] */
231 if( pParse
->pAinc
!=0 && pParse
->nTab
==0 ) pParse
->nTab
= 1;
232 sqlite3VdbeMakeReady(v
, pParse
);
233 pParse
->rc
= SQLITE_DONE
;
235 pParse
->rc
= SQLITE_ERROR
;
240 ** Run the parser and code generator recursively in order to generate
241 ** code for the SQL statement given onto the end of the pParse context
242 ** currently under construction. When the parser is run recursively
243 ** this way, the final OP_Halt is not appended and other initialization
244 ** and finalization steps are omitted because those are handling by the
247 ** Not everything is nestable. This facility is designed to permit
248 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
249 ** care if you decide to try to use this routine for some other purposes.
251 void sqlite3NestedParse(Parse
*pParse
, const char *zFormat
, ...){
255 sqlite3
*db
= pParse
->db
;
256 char saveBuf
[PARSE_TAIL_SZ
];
258 if( pParse
->nErr
) return;
259 assert( pParse
->nested
<10 ); /* Nesting should only be of limited depth */
260 va_start(ap
, zFormat
);
261 zSql
= sqlite3VMPrintf(db
, zFormat
, ap
);
264 return; /* A malloc must have failed */
267 memcpy(saveBuf
, PARSE_TAIL(pParse
), PARSE_TAIL_SZ
);
268 memset(PARSE_TAIL(pParse
), 0, PARSE_TAIL_SZ
);
269 sqlite3RunParser(pParse
, zSql
, &zErrMsg
);
270 sqlite3DbFree(db
, zErrMsg
);
271 sqlite3DbFree(db
, zSql
);
272 memcpy(PARSE_TAIL(pParse
), saveBuf
, PARSE_TAIL_SZ
);
276 #if SQLITE_USER_AUTHENTICATION
278 ** Return TRUE if zTable is the name of the system table that stores the
279 ** list of users and their access credentials.
281 int sqlite3UserAuthTable(const char *zTable
){
282 return sqlite3_stricmp(zTable
, "sqlite_user")==0;
287 ** Locate the in-memory structure that describes a particular database
288 ** table given the name of that table and (optionally) the name of the
289 ** database containing the table. Return NULL if not found.
291 ** If zDatabase is 0, all databases are searched for the table and the
292 ** first matching table is returned. (No checking for duplicate table
293 ** names is done.) The search order is TEMP first, then MAIN, then any
294 ** auxiliary databases added using the ATTACH command.
296 ** See also sqlite3LocateTable().
298 Table
*sqlite3FindTable(sqlite3
*db
, const char *zName
, const char *zDatabase
){
302 /* All mutexes are required for schema access. Make sure we hold them. */
303 assert( zDatabase
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
304 #if SQLITE_USER_AUTHENTICATION
305 /* Only the admin user is allowed to know that the sqlite_user table
307 if( db
->auth
.authLevel
<UAUTH_Admin
&& sqlite3UserAuthTable(zName
)!=0 ){
312 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
313 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
314 if( zDatabase
==0 || sqlite3StrICmp(zDatabase
, db
->aDb
[j
].zDbSName
)==0 ){
315 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
316 p
= sqlite3HashFind(&db
->aDb
[j
].pSchema
->tblHash
, zName
);
320 /* Not found. If the name we were looking for was temp.sqlite_master
321 ** then change the name to sqlite_temp_master and try again. */
322 if( sqlite3StrICmp(zName
, MASTER_NAME
)!=0 ) break;
323 if( sqlite3_stricmp(zDatabase
, db
->aDb
[1].zDbSName
)!=0 ) break;
324 zName
= TEMP_MASTER_NAME
;
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
==0 && sqlite3_strnicmp(zName
, "pragma_", 7)==0 ){
363 pMod
= sqlite3PragmaVtabRegister(pParse
->db
, zName
);
365 if( pMod
&& sqlite3VtabEponymousTableInit(pParse
, pMod
) ){
366 return pMod
->pEpoTab
;
370 if( (flags
& LOCATE_NOERR
)==0 ){
372 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zMsg
, zDbase
, zName
);
374 sqlite3ErrorMsg(pParse
, "%s: %s", zMsg
, zName
);
376 pParse
->checkSchema
= 1;
384 ** Locate the table identified by *p.
386 ** This is a wrapper around sqlite3LocateTable(). The difference between
387 ** sqlite3LocateTable() and this function is that this function restricts
388 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
389 ** non-NULL if it is part of a view or trigger program definition. See
390 ** sqlite3FixSrcList() for details.
392 Table
*sqlite3LocateTableItem(
395 struct SrcList_item
*p
398 assert( p
->pSchema
==0 || p
->zDatabase
==0 );
400 int iDb
= sqlite3SchemaToIndex(pParse
->db
, p
->pSchema
);
401 zDb
= pParse
->db
->aDb
[iDb
].zDbSName
;
405 return sqlite3LocateTable(pParse
, flags
, p
->zName
, zDb
);
409 ** Locate the in-memory structure that describes
410 ** a particular index given the name of that index
411 ** and the name of the database that contains the index.
412 ** Return NULL if not found.
414 ** If zDatabase is 0, all databases are searched for the
415 ** table and the first matching index is returned. (No checking
416 ** for duplicate index names is done.) The search order is
417 ** TEMP first, then MAIN, then any auxiliary databases added
418 ** using the ATTACH command.
420 Index
*sqlite3FindIndex(sqlite3
*db
, const char *zName
, const char *zDb
){
423 /* All mutexes are required for schema access. Make sure we hold them. */
424 assert( zDb
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
425 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
426 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
427 Schema
*pSchema
= db
->aDb
[j
].pSchema
;
429 if( zDb
&& sqlite3StrICmp(zDb
, db
->aDb
[j
].zDbSName
) ) continue;
430 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
431 p
= sqlite3HashFind(&pSchema
->idxHash
, zName
);
438 ** Reclaim the memory used by an index
440 static void freeIndex(sqlite3
*db
, Index
*p
){
441 #ifndef SQLITE_OMIT_ANALYZE
442 sqlite3DeleteIndexSamples(db
, p
);
444 sqlite3ExprDelete(db
, p
->pPartIdxWhere
);
445 sqlite3ExprListDelete(db
, p
->aColExpr
);
446 sqlite3DbFree(db
, p
->zColAff
);
447 if( p
->isResized
) sqlite3DbFree(db
, (void *)p
->azColl
);
448 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
449 sqlite3_free(p
->aiRowEst
);
451 sqlite3DbFree(db
, p
);
455 ** For the index called zIdxName which is found in the database iDb,
456 ** unlike that index from its Table then remove the index from
457 ** the index hash table and free all memory structures associated
460 void sqlite3UnlinkAndDeleteIndex(sqlite3
*db
, int iDb
, const char *zIdxName
){
464 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
465 pHash
= &db
->aDb
[iDb
].pSchema
->idxHash
;
466 pIndex
= sqlite3HashInsert(pHash
, zIdxName
, 0);
467 if( ALWAYS(pIndex
) ){
468 if( pIndex
->pTable
->pIndex
==pIndex
){
469 pIndex
->pTable
->pIndex
= pIndex
->pNext
;
472 /* Justification of ALWAYS(); The index must be on the list of
474 p
= pIndex
->pTable
->pIndex
;
475 while( ALWAYS(p
) && p
->pNext
!=pIndex
){ p
= p
->pNext
; }
476 if( ALWAYS(p
&& p
->pNext
==pIndex
) ){
477 p
->pNext
= pIndex
->pNext
;
480 freeIndex(db
, pIndex
);
482 db
->mDbFlags
|= DBFLAG_SchemaChange
;
486 ** Look through the list of open database files in db->aDb[] and if
487 ** any have been closed, remove them from the list. Reallocate the
488 ** db->aDb[] structure to a smaller size, if possible.
490 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
491 ** are never candidates for being collapsed.
493 void sqlite3CollapseDatabaseArray(sqlite3
*db
){
495 for(i
=j
=2; i
<db
->nDb
; i
++){
496 struct Db
*pDb
= &db
->aDb
[i
];
498 sqlite3DbFree(db
, pDb
->zDbSName
);
503 db
->aDb
[j
] = db
->aDb
[i
];
508 if( db
->nDb
<=2 && db
->aDb
!=db
->aDbStatic
){
509 memcpy(db
->aDbStatic
, db
->aDb
, 2*sizeof(db
->aDb
[0]));
510 sqlite3DbFree(db
, db
->aDb
);
511 db
->aDb
= db
->aDbStatic
;
516 ** Reset the schema for the database at index iDb. Also reset the
517 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
518 ** Deferred resets may be run by calling with iDb<0.
520 void sqlite3ResetOneSchema(sqlite3
*db
, int iDb
){
522 assert( iDb
<db
->nDb
);
525 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
526 DbSetProperty(db
, iDb
, DB_ResetWanted
);
527 DbSetProperty(db
, 1, DB_ResetWanted
);
530 if( db
->nSchemaLock
==0 ){
531 for(i
=0; i
<db
->nDb
; i
++){
532 if( DbHasProperty(db
, i
, DB_ResetWanted
) ){
533 sqlite3SchemaClear(db
->aDb
[i
].pSchema
);
540 ** Erase all schema information from all attached databases (including
541 ** "main" and "temp") for a single database connection.
543 void sqlite3ResetAllSchemasOfConnection(sqlite3
*db
){
545 sqlite3BtreeEnterAll(db
);
546 assert( db
->nSchemaLock
==0 );
547 for(i
=0; i
<db
->nDb
; i
++){
548 Db
*pDb
= &db
->aDb
[i
];
550 sqlite3SchemaClear(pDb
->pSchema
);
553 db
->mDbFlags
&= ~DBFLAG_SchemaChange
;
554 sqlite3VtabUnlockList(db
);
555 sqlite3BtreeLeaveAll(db
);
556 sqlite3CollapseDatabaseArray(db
);
560 ** This routine is called when a commit occurs.
562 void sqlite3CommitInternalChanges(sqlite3
*db
){
563 db
->mDbFlags
&= ~DBFLAG_SchemaChange
;
567 ** Delete memory allocated for the column names of a table or view (the
568 ** Table.aCol[] array).
570 void sqlite3DeleteColumnNames(sqlite3
*db
, Table
*pTable
){
574 if( (pCol
= pTable
->aCol
)!=0 ){
575 for(i
=0; i
<pTable
->nCol
; i
++, pCol
++){
576 sqlite3DbFree(db
, pCol
->zName
);
577 sqlite3ExprDelete(db
, pCol
->pDflt
);
578 sqlite3DbFree(db
, pCol
->zColl
);
580 sqlite3DbFree(db
, pTable
->aCol
);
585 ** Remove the memory data structures associated with the given
586 ** Table. No changes are made to disk by this routine.
588 ** This routine just deletes the data structure. It does not unlink
589 ** the table data structure from the hash table. But it does destroy
590 ** memory structures of the indices and foreign keys associated with
593 ** The db parameter is optional. It is needed if the Table object
594 ** contains lookaside memory. (Table objects in the schema do not use
595 ** lookaside memory, but some ephemeral Table objects do.) Or the
596 ** db parameter can be used with db->pnBytesFreed to measure the memory
597 ** used by the Table object.
599 static void SQLITE_NOINLINE
deleteTable(sqlite3
*db
, Table
*pTable
){
600 Index
*pIndex
, *pNext
;
603 /* Record the number of outstanding lookaside allocations in schema Tables
604 ** prior to doing any free() operations. Since schema Tables do not use
605 ** lookaside, this number should not change. */
607 if( db
&& (pTable
->tabFlags
& TF_Ephemeral
)==0 ){
608 nLookaside
= sqlite3LookasideUsed(db
, 0);
612 /* Delete all indices associated with this table. */
613 for(pIndex
= pTable
->pIndex
; pIndex
; pIndex
=pNext
){
614 pNext
= pIndex
->pNext
;
615 assert( pIndex
->pSchema
==pTable
->pSchema
616 || (IsVirtual(pTable
) && pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
) );
617 if( (db
==0 || db
->pnBytesFreed
==0) && !IsVirtual(pTable
) ){
618 char *zName
= pIndex
->zName
;
619 TESTONLY ( Index
*pOld
= ) sqlite3HashInsert(
620 &pIndex
->pSchema
->idxHash
, zName
, 0
622 assert( db
==0 || sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
623 assert( pOld
==pIndex
|| pOld
==0 );
625 freeIndex(db
, pIndex
);
628 /* Delete any foreign keys attached to this table. */
629 sqlite3FkDelete(db
, pTable
);
631 /* Delete the Table structure itself.
633 sqlite3DeleteColumnNames(db
, pTable
);
634 sqlite3DbFree(db
, pTable
->zName
);
635 sqlite3DbFree(db
, pTable
->zColAff
);
636 sqlite3SelectDelete(db
, pTable
->pSelect
);
637 sqlite3ExprListDelete(db
, pTable
->pCheck
);
638 #ifndef SQLITE_OMIT_VIRTUALTABLE
639 sqlite3VtabClear(db
, pTable
);
641 sqlite3DbFree(db
, pTable
);
643 /* Verify that no lookaside memory was used by schema tables */
644 assert( nLookaside
==0 || nLookaside
==sqlite3LookasideUsed(db
,0) );
646 void sqlite3DeleteTable(sqlite3
*db
, Table
*pTable
){
647 /* Do not delete the table until the reference count reaches zero. */
648 if( !pTable
) return;
649 if( ((!db
|| db
->pnBytesFreed
==0) && (--pTable
->nTabRef
)>0) ) return;
650 deleteTable(db
, pTable
);
655 ** Unlink the given table from the hash tables and the delete the
656 ** table structure with all its indices and foreign keys.
658 void sqlite3UnlinkAndDeleteTable(sqlite3
*db
, int iDb
, const char *zTabName
){
663 assert( iDb
>=0 && iDb
<db
->nDb
);
665 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
666 testcase( zTabName
[0]==0 ); /* Zero-length table names are allowed */
668 p
= sqlite3HashInsert(&pDb
->pSchema
->tblHash
, zTabName
, 0);
669 sqlite3DeleteTable(db
, p
);
670 db
->mDbFlags
|= DBFLAG_SchemaChange
;
674 ** Given a token, return a string that consists of the text of that
675 ** token. Space to hold the returned string
676 ** is obtained from sqliteMalloc() and must be freed by the calling
679 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
680 ** surround the body of the token are removed.
682 ** Tokens are often just pointers into the original SQL text and so
683 ** are not \000 terminated and are not persistent. The returned string
684 ** is \000 terminated and is persistent.
686 char *sqlite3NameFromToken(sqlite3
*db
, Token
*pName
){
689 zName
= sqlite3DbStrNDup(db
, (char*)pName
->z
, pName
->n
);
690 sqlite3Dequote(zName
);
698 ** Open the sqlite_master table stored in database number iDb for
699 ** writing. The table is opened using cursor 0.
701 void sqlite3OpenMasterTable(Parse
*p
, int iDb
){
702 Vdbe
*v
= sqlite3GetVdbe(p
);
703 sqlite3TableLock(p
, iDb
, MASTER_ROOT
, 1, MASTER_NAME
);
704 sqlite3VdbeAddOp4Int(v
, OP_OpenWrite
, 0, MASTER_ROOT
, iDb
, 5);
711 ** Parameter zName points to a nul-terminated buffer containing the name
712 ** of a database ("main", "temp" or the name of an attached db). This
713 ** function returns the index of the named database in db->aDb[], or
714 ** -1 if the named db cannot be found.
716 int sqlite3FindDbName(sqlite3
*db
, const char *zName
){
717 int i
= -1; /* Database number */
720 for(i
=(db
->nDb
-1), pDb
=&db
->aDb
[i
]; i
>=0; i
--, pDb
--){
721 if( 0==sqlite3_stricmp(pDb
->zDbSName
, zName
) ) break;
722 /* "main" is always an acceptable alias for the primary database
723 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
724 if( i
==0 && 0==sqlite3_stricmp("main", zName
) ) break;
731 ** The token *pName contains the name of a database (either "main" or
732 ** "temp" or the name of an attached db). This routine returns the
733 ** index of the named database in db->aDb[], or -1 if the named db
736 int sqlite3FindDb(sqlite3
*db
, Token
*pName
){
737 int i
; /* Database number */
738 char *zName
; /* Name we are searching for */
739 zName
= sqlite3NameFromToken(db
, pName
);
740 i
= sqlite3FindDbName(db
, zName
);
741 sqlite3DbFree(db
, zName
);
745 /* The table or view or trigger name is passed to this routine via tokens
746 ** pName1 and pName2. If the table name was fully qualified, for example:
748 ** CREATE TABLE xxx.yyy (...);
750 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
751 ** the table name is not fully qualified, i.e.:
753 ** CREATE TABLE yyy(...);
755 ** Then pName1 is set to "yyy" and pName2 is "".
757 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
758 ** pName2) that stores the unqualified table name. The index of the
759 ** database "xxx" is returned.
761 int sqlite3TwoPartName(
762 Parse
*pParse
, /* Parsing and code generating context */
763 Token
*pName1
, /* The "xxx" in the name "xxx.yyy" or "xxx" */
764 Token
*pName2
, /* The "yyy" in the name "xxx.yyy" */
765 Token
**pUnqual
/* Write the unqualified object name here */
767 int iDb
; /* Database holding the object */
768 sqlite3
*db
= pParse
->db
;
772 if( db
->init
.busy
) {
773 sqlite3ErrorMsg(pParse
, "corrupt database");
777 iDb
= sqlite3FindDb(db
, pName1
);
779 sqlite3ErrorMsg(pParse
, "unknown database %T", pName1
);
783 assert( db
->init
.iDb
==0 || db
->init
.busy
784 || (db
->mDbFlags
& DBFLAG_Vacuum
)!=0);
792 ** This routine is used to check if the UTF-8 string zName is a legal
793 ** unqualified name for a new schema object (table, index, view or
794 ** trigger). All names are legal except those that begin with the string
795 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
796 ** is reserved for internal use.
798 int sqlite3CheckObjectName(Parse
*pParse
, const char *zName
){
799 if( !pParse
->db
->init
.busy
&& pParse
->nested
==0
800 && (pParse
->db
->flags
& SQLITE_WriteSchema
)==0
801 && 0==sqlite3StrNICmp(zName
, "sqlite_", 7) ){
802 sqlite3ErrorMsg(pParse
, "object name reserved for internal use: %s", zName
);
809 ** Return the PRIMARY KEY index of a table
811 Index
*sqlite3PrimaryKeyIndex(Table
*pTab
){
813 for(p
=pTab
->pIndex
; p
&& !IsPrimaryKeyIndex(p
); p
=p
->pNext
){}
818 ** Return the column of index pIdx that corresponds to table
819 ** column iCol. Return -1 if not found.
821 i16
sqlite3ColumnOfIndex(Index
*pIdx
, i16 iCol
){
823 for(i
=0; i
<pIdx
->nColumn
; i
++){
824 if( iCol
==pIdx
->aiColumn
[i
] ) return i
;
830 ** Begin constructing a new table representation in memory. This is
831 ** the first of several action routines that get called in response
832 ** to a CREATE TABLE statement. In particular, this routine is called
833 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
834 ** flag is true if the table should be stored in the auxiliary database
835 ** file instead of in the main database file. This is normally the case
836 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
839 ** The new table record is initialized and put in pParse->pNewTable.
840 ** As more of the CREATE TABLE statement is parsed, additional action
841 ** routines will be called to add more information to this record.
842 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
843 ** is called to complete the construction of the new table record.
845 void sqlite3StartTable(
846 Parse
*pParse
, /* Parser context */
847 Token
*pName1
, /* First part of the name of the table or view */
848 Token
*pName2
, /* Second part of the name of the table or view */
849 int isTemp
, /* True if this is a TEMP table */
850 int isView
, /* True if this is a VIEW */
851 int isVirtual
, /* True if this is a VIRTUAL table */
852 int noErr
/* Do nothing if table already exists */
855 char *zName
= 0; /* The name of the new table */
856 sqlite3
*db
= pParse
->db
;
858 int iDb
; /* Database number to create the table in */
859 Token
*pName
; /* Unqualified name of the table to create */
861 if( db
->init
.busy
&& db
->init
.newTnum
==1 ){
862 /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
864 zName
= sqlite3DbStrDup(db
, SCHEMA_TABLE(iDb
));
867 /* The common case */
868 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
870 if( !OMIT_TEMPDB
&& isTemp
&& pName2
->n
>0 && iDb
!=1 ){
871 /* If creating a temp table, the name may not be qualified. Unless
872 ** the database name is "temp" anyway. */
873 sqlite3ErrorMsg(pParse
, "temporary table name must be unqualified");
876 if( !OMIT_TEMPDB
&& isTemp
) iDb
= 1;
877 zName
= sqlite3NameFromToken(db
, pName
);
879 pParse
->sNameToken
= *pName
;
880 if( zName
==0 ) return;
881 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
) ){
882 goto begin_table_error
;
884 if( db
->init
.iDb
==1 ) isTemp
= 1;
885 #ifndef SQLITE_OMIT_AUTHORIZATION
886 assert( isTemp
==0 || isTemp
==1 );
887 assert( isView
==0 || isView
==1 );
889 static const u8 aCode
[] = {
891 SQLITE_CREATE_TEMP_TABLE
,
893 SQLITE_CREATE_TEMP_VIEW
895 char *zDb
= db
->aDb
[iDb
].zDbSName
;
896 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(isTemp
), 0, zDb
) ){
897 goto begin_table_error
;
899 if( !isVirtual
&& sqlite3AuthCheck(pParse
, (int)aCode
[isTemp
+2*isView
],
901 goto begin_table_error
;
906 /* Make sure the new table name does not collide with an existing
907 ** index or table name in the same database. Issue an error message if
908 ** it does. The exception is if the statement being parsed was passed
909 ** to an sqlite3_declare_vtab() call. In that case only the column names
910 ** and types will be used, so there is no need to test for namespace
913 if( !IN_DECLARE_VTAB
){
914 char *zDb
= db
->aDb
[iDb
].zDbSName
;
915 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
916 goto begin_table_error
;
918 pTable
= sqlite3FindTable(db
, zName
, zDb
);
921 sqlite3ErrorMsg(pParse
, "table %T already exists", pName
);
923 assert( !db
->init
.busy
|| CORRUPT_DB
);
924 sqlite3CodeVerifySchema(pParse
, iDb
);
926 goto begin_table_error
;
928 if( sqlite3FindIndex(db
, zName
, zDb
)!=0 ){
929 sqlite3ErrorMsg(pParse
, "there is already an index named %s", zName
);
930 goto begin_table_error
;
934 pTable
= sqlite3DbMallocZero(db
, sizeof(Table
));
936 assert( db
->mallocFailed
);
937 pParse
->rc
= SQLITE_NOMEM_BKPT
;
939 goto begin_table_error
;
941 pTable
->zName
= zName
;
943 pTable
->pSchema
= db
->aDb
[iDb
].pSchema
;
945 #ifdef SQLITE_DEFAULT_ROWEST
946 pTable
->nRowLogEst
= sqlite3LogEst(SQLITE_DEFAULT_ROWEST
);
948 pTable
->nRowLogEst
= 200; assert( 200==sqlite3LogEst(1048576) );
950 assert( pParse
->pNewTable
==0 );
951 pParse
->pNewTable
= pTable
;
953 /* If this is the magic sqlite_sequence table used by autoincrement,
954 ** then record a pointer to this table in the main database structure
955 ** so that INSERT can find the table easily.
957 #ifndef SQLITE_OMIT_AUTOINCREMENT
958 if( !pParse
->nested
&& strcmp(zName
, "sqlite_sequence")==0 ){
959 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
960 pTable
->pSchema
->pSeqTab
= pTable
;
964 /* Begin generating the code that will insert the table record into
965 ** the SQLITE_MASTER table. Note in particular that we must go ahead
966 ** and allocate the record number for the table entry now. Before any
967 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
968 ** indices to be created and the table record must come before the
969 ** indices. Hence, the record number for the table must be allocated
972 if( !db
->init
.busy
&& (v
= sqlite3GetVdbe(pParse
))!=0 ){
975 int reg1
, reg2
, reg3
;
976 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
977 static const char nullRow
[] = { 6, 0, 0, 0, 0, 0 };
978 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
980 #ifndef SQLITE_OMIT_VIRTUALTABLE
982 sqlite3VdbeAddOp0(v
, OP_VBegin
);
986 /* If the file format and encoding in the database have not been set,
989 reg1
= pParse
->regRowid
= ++pParse
->nMem
;
990 reg2
= pParse
->regRoot
= ++pParse
->nMem
;
991 reg3
= ++pParse
->nMem
;
992 sqlite3VdbeAddOp3(v
, OP_ReadCookie
, iDb
, reg3
, BTREE_FILE_FORMAT
);
993 sqlite3VdbeUsesBtree(v
, iDb
);
994 addr1
= sqlite3VdbeAddOp1(v
, OP_If
, reg3
); VdbeCoverage(v
);
995 fileFormat
= (db
->flags
& SQLITE_LegacyFileFmt
)!=0 ?
996 1 : SQLITE_MAX_FILE_FORMAT
;
997 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_FILE_FORMAT
, fileFormat
);
998 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_TEXT_ENCODING
, ENC(db
));
999 sqlite3VdbeJumpHere(v
, addr1
);
1001 /* This just creates a place-holder record in the sqlite_master table.
1002 ** The record created does not contain anything yet. It will be replaced
1003 ** by the real entry in code generated at sqlite3EndTable().
1005 ** The rowid for the new entry is left in register pParse->regRowid.
1006 ** The root page number of the new table is left in reg pParse->regRoot.
1007 ** The rowid and root page number values are needed by the code that
1008 ** sqlite3EndTable will generate.
1010 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1011 if( isView
|| isVirtual
){
1012 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, reg2
);
1017 sqlite3VdbeAddOp3(v
, OP_CreateBtree
, iDb
, reg2
, BTREE_INTKEY
);
1019 sqlite3OpenMasterTable(pParse
, iDb
);
1020 sqlite3VdbeAddOp2(v
, OP_NewRowid
, 0, reg1
);
1021 sqlite3VdbeAddOp4(v
, OP_Blob
, 6, reg3
, 0, nullRow
, P4_STATIC
);
1022 sqlite3VdbeAddOp3(v
, OP_Insert
, 0, reg3
, reg1
);
1023 sqlite3VdbeChangeP5(v
, OPFLAG_APPEND
);
1024 sqlite3VdbeAddOp0(v
, OP_Close
);
1027 /* Normal (non-error) return. */
1030 /* If an error occurs, we jump here */
1032 sqlite3DbFree(db
, zName
);
1036 /* Set properties of a table column based on the (magical)
1037 ** name of the column.
1039 #if SQLITE_ENABLE_HIDDEN_COLUMNS
1040 void sqlite3ColumnPropertiesFromName(Table
*pTab
, Column
*pCol
){
1041 if( sqlite3_strnicmp(pCol
->zName
, "__hidden__", 10)==0 ){
1042 pCol
->colFlags
|= COLFLAG_HIDDEN
;
1043 }else if( pTab
&& pCol
!=pTab
->aCol
&& (pCol
[-1].colFlags
& COLFLAG_HIDDEN
) ){
1044 pTab
->tabFlags
|= TF_OOOHidden
;
1051 ** Add a new column to the table currently being constructed.
1053 ** The parser calls this routine once for each column declaration
1054 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
1055 ** first to get things going. Then this routine is called for each
1058 void sqlite3AddColumn(Parse
*pParse
, Token
*pName
, Token
*pType
){
1064 sqlite3
*db
= pParse
->db
;
1065 if( (p
= pParse
->pNewTable
)==0 ) return;
1066 if( p
->nCol
+1>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1067 sqlite3ErrorMsg(pParse
, "too many columns on %s", p
->zName
);
1070 z
= sqlite3DbMallocRaw(db
, pName
->n
+ pType
->n
+ 2);
1072 memcpy(z
, pName
->z
, pName
->n
);
1075 for(i
=0; i
<p
->nCol
; i
++){
1076 if( sqlite3_stricmp(z
, p
->aCol
[i
].zName
)==0 ){
1077 sqlite3ErrorMsg(pParse
, "duplicate column name: %s", z
);
1078 sqlite3DbFree(db
, z
);
1082 if( (p
->nCol
& 0x7)==0 ){
1084 aNew
= sqlite3DbRealloc(db
,p
->aCol
,(p
->nCol
+8)*sizeof(p
->aCol
[0]));
1086 sqlite3DbFree(db
, z
);
1091 pCol
= &p
->aCol
[p
->nCol
];
1092 memset(pCol
, 0, sizeof(p
->aCol
[0]));
1094 sqlite3ColumnPropertiesFromName(p
, pCol
);
1097 /* If there is no type specified, columns have the default affinity
1099 pCol
->affinity
= SQLITE_AFF_BLOB
;
1102 zType
= z
+ sqlite3Strlen30(z
) + 1;
1103 memcpy(zType
, pType
->z
, pType
->n
);
1104 zType
[pType
->n
] = 0;
1105 sqlite3Dequote(zType
);
1106 pCol
->affinity
= sqlite3AffinityType(zType
, &pCol
->szEst
);
1107 pCol
->colFlags
|= COLFLAG_HASTYPE
;
1110 pParse
->constraintName
.n
= 0;
1114 ** This routine is called by the parser while in the middle of
1115 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1116 ** been seen on a column. This routine sets the notNull flag on
1117 ** the column currently under construction.
1119 void sqlite3AddNotNull(Parse
*pParse
, int onError
){
1122 p
= pParse
->pNewTable
;
1123 if( p
==0 || NEVER(p
->nCol
<1) ) return;
1124 pCol
= &p
->aCol
[p
->nCol
-1];
1125 pCol
->notNull
= (u8
)onError
;
1126 p
->tabFlags
|= TF_HasNotNull
;
1128 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1129 ** on this column. */
1130 if( pCol
->colFlags
& COLFLAG_UNIQUE
){
1132 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1133 assert( pIdx
->nKeyCol
==1 && pIdx
->onError
!=OE_None
);
1134 if( pIdx
->aiColumn
[0]==p
->nCol
-1 ){
1135 pIdx
->uniqNotNull
= 1;
1142 ** Scan the column type name zType (length nType) and return the
1143 ** associated affinity type.
1145 ** This routine does a case-independent search of zType for the
1146 ** substrings in the following table. If one of the substrings is
1147 ** found, the corresponding affinity is returned. If zType contains
1148 ** more than one of the substrings, entries toward the top of
1149 ** the table take priority. For example, if zType is 'BLOBINT',
1150 ** SQLITE_AFF_INTEGER is returned.
1152 ** Substring | Affinity
1153 ** --------------------------------
1154 ** 'INT' | SQLITE_AFF_INTEGER
1155 ** 'CHAR' | SQLITE_AFF_TEXT
1156 ** 'CLOB' | SQLITE_AFF_TEXT
1157 ** 'TEXT' | SQLITE_AFF_TEXT
1158 ** 'BLOB' | SQLITE_AFF_BLOB
1159 ** 'REAL' | SQLITE_AFF_REAL
1160 ** 'FLOA' | SQLITE_AFF_REAL
1161 ** 'DOUB' | SQLITE_AFF_REAL
1163 ** If none of the substrings in the above table are found,
1164 ** SQLITE_AFF_NUMERIC is returned.
1166 char sqlite3AffinityType(const char *zIn
, u8
*pszEst
){
1168 char aff
= SQLITE_AFF_NUMERIC
;
1169 const char *zChar
= 0;
1173 h
= (h
<<8) + sqlite3UpperToLower
[(*zIn
)&0xff];
1175 if( h
==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1176 aff
= SQLITE_AFF_TEXT
;
1178 }else if( h
==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1179 aff
= SQLITE_AFF_TEXT
;
1180 }else if( h
==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1181 aff
= SQLITE_AFF_TEXT
;
1182 }else if( h
==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1183 && (aff
==SQLITE_AFF_NUMERIC
|| aff
==SQLITE_AFF_REAL
) ){
1184 aff
= SQLITE_AFF_BLOB
;
1185 if( zIn
[0]=='(' ) zChar
= zIn
;
1186 #ifndef SQLITE_OMIT_FLOATING_POINT
1187 }else if( h
==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1188 && aff
==SQLITE_AFF_NUMERIC
){
1189 aff
= SQLITE_AFF_REAL
;
1190 }else if( h
==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1191 && aff
==SQLITE_AFF_NUMERIC
){
1192 aff
= SQLITE_AFF_REAL
;
1193 }else if( h
==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1194 && aff
==SQLITE_AFF_NUMERIC
){
1195 aff
= SQLITE_AFF_REAL
;
1197 }else if( (h
&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1198 aff
= SQLITE_AFF_INTEGER
;
1203 /* If pszEst is not NULL, store an estimate of the field size. The
1204 ** estimate is scaled so that the size of an integer is 1. */
1206 *pszEst
= 1; /* default size is approx 4 bytes */
1207 if( aff
<SQLITE_AFF_NUMERIC
){
1210 if( sqlite3Isdigit(zChar
[0]) ){
1212 sqlite3GetInt32(zChar
, &v
);
1214 if( v
>255 ) v
= 255;
1215 *pszEst
= v
; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1221 *pszEst
= 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1229 ** The expression is the default value for the most recently added column
1230 ** of the table currently under construction.
1232 ** Default value expressions must be constant. Raise an exception if this
1235 ** This routine is called by the parser while in the middle of
1236 ** parsing a CREATE TABLE statement.
1238 void sqlite3AddDefaultValue(
1239 Parse
*pParse
, /* Parsing context */
1240 Expr
*pExpr
, /* The parsed expression of the default value */
1241 const char *zStart
, /* Start of the default value text */
1242 const char *zEnd
/* First character past end of defaut value text */
1246 sqlite3
*db
= pParse
->db
;
1247 p
= pParse
->pNewTable
;
1249 pCol
= &(p
->aCol
[p
->nCol
-1]);
1250 if( !sqlite3ExprIsConstantOrFunction(pExpr
, db
->init
.busy
) ){
1251 sqlite3ErrorMsg(pParse
, "default value of column [%s] is not constant",
1254 /* A copy of pExpr is used instead of the original, as pExpr contains
1255 ** tokens that point to volatile memory.
1258 sqlite3ExprDelete(db
, pCol
->pDflt
);
1259 memset(&x
, 0, sizeof(x
));
1261 x
.u
.zToken
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
1264 pCol
->pDflt
= sqlite3ExprDup(db
, &x
, EXPRDUP_REDUCE
);
1265 sqlite3DbFree(db
, x
.u
.zToken
);
1268 sqlite3ExprDelete(db
, pExpr
);
1272 ** Backwards Compatibility Hack:
1274 ** Historical versions of SQLite accepted strings as column names in
1275 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1277 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1278 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1280 ** This is goofy. But to preserve backwards compatibility we continue to
1281 ** accept it. This routine does the necessary conversion. It converts
1282 ** the expression given in its argument from a TK_STRING into a TK_ID
1283 ** if the expression is just a TK_STRING with an optional COLLATE clause.
1284 ** If the epxression is anything other than TK_STRING, the expression is
1287 static void sqlite3StringToId(Expr
*p
){
1288 if( p
->op
==TK_STRING
){
1290 }else if( p
->op
==TK_COLLATE
&& p
->pLeft
->op
==TK_STRING
){
1291 p
->pLeft
->op
= TK_ID
;
1296 ** Designate the PRIMARY KEY for the table. pList is a list of names
1297 ** of columns that form the primary key. If pList is NULL, then the
1298 ** most recently added column of the table is the primary key.
1300 ** A table can have at most one primary key. If the table already has
1301 ** a primary key (and this is the second primary key) then create an
1304 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1305 ** then we will try to use that column as the rowid. Set the Table.iPKey
1306 ** field of the table under construction to be the index of the
1307 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1308 ** no INTEGER PRIMARY KEY.
1310 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1311 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1313 void sqlite3AddPrimaryKey(
1314 Parse
*pParse
, /* Parsing context */
1315 ExprList
*pList
, /* List of field names to be indexed */
1316 int onError
, /* What to do with a uniqueness conflict */
1317 int autoInc
, /* True if the AUTOINCREMENT keyword is present */
1318 int sortOrder
/* SQLITE_SO_ASC or SQLITE_SO_DESC */
1320 Table
*pTab
= pParse
->pNewTable
;
1324 if( pTab
==0 ) goto primary_key_exit
;
1325 if( pTab
->tabFlags
& TF_HasPrimaryKey
){
1326 sqlite3ErrorMsg(pParse
,
1327 "table \"%s\" has more than one primary key", pTab
->zName
);
1328 goto primary_key_exit
;
1330 pTab
->tabFlags
|= TF_HasPrimaryKey
;
1332 iCol
= pTab
->nCol
- 1;
1333 pCol
= &pTab
->aCol
[iCol
];
1334 pCol
->colFlags
|= COLFLAG_PRIMKEY
;
1337 nTerm
= pList
->nExpr
;
1338 for(i
=0; i
<nTerm
; i
++){
1339 Expr
*pCExpr
= sqlite3ExprSkipCollate(pList
->a
[i
].pExpr
);
1340 assert( pCExpr
!=0 );
1341 sqlite3StringToId(pCExpr
);
1342 if( pCExpr
->op
==TK_ID
){
1343 const char *zCName
= pCExpr
->u
.zToken
;
1344 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
1345 if( sqlite3StrICmp(zCName
, pTab
->aCol
[iCol
].zName
)==0 ){
1346 pCol
= &pTab
->aCol
[iCol
];
1347 pCol
->colFlags
|= COLFLAG_PRIMKEY
;
1356 && sqlite3StrICmp(sqlite3ColumnType(pCol
,""), "INTEGER")==0
1357 && sortOrder
!=SQLITE_SO_DESC
1360 pTab
->keyConf
= (u8
)onError
;
1361 assert( autoInc
==0 || autoInc
==1 );
1362 pTab
->tabFlags
|= autoInc
*TF_Autoincrement
;
1363 if( pList
) pParse
->iPkSortOrder
= pList
->a
[0].sortOrder
;
1364 }else if( autoInc
){
1365 #ifndef SQLITE_OMIT_AUTOINCREMENT
1366 sqlite3ErrorMsg(pParse
, "AUTOINCREMENT is only allowed on an "
1367 "INTEGER PRIMARY KEY");
1370 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, onError
, 0,
1371 0, sortOrder
, 0, SQLITE_IDXTYPE_PRIMARYKEY
);
1376 sqlite3ExprListDelete(pParse
->db
, pList
);
1381 ** Add a new CHECK constraint to the table currently under construction.
1383 void sqlite3AddCheckConstraint(
1384 Parse
*pParse
, /* Parsing context */
1385 Expr
*pCheckExpr
/* The check expression */
1387 #ifndef SQLITE_OMIT_CHECK
1388 Table
*pTab
= pParse
->pNewTable
;
1389 sqlite3
*db
= pParse
->db
;
1390 if( pTab
&& !IN_DECLARE_VTAB
1391 && !sqlite3BtreeIsReadonly(db
->aDb
[db
->init
.iDb
].pBt
)
1393 pTab
->pCheck
= sqlite3ExprListAppend(pParse
, pTab
->pCheck
, pCheckExpr
);
1394 if( pParse
->constraintName
.n
){
1395 sqlite3ExprListSetName(pParse
, pTab
->pCheck
, &pParse
->constraintName
, 1);
1400 sqlite3ExprDelete(pParse
->db
, pCheckExpr
);
1405 ** Set the collation function of the most recently parsed table column
1406 ** to the CollSeq given.
1408 void sqlite3AddCollateType(Parse
*pParse
, Token
*pToken
){
1411 char *zColl
; /* Dequoted name of collation sequence */
1414 if( (p
= pParse
->pNewTable
)==0 ) return;
1417 zColl
= sqlite3NameFromToken(db
, pToken
);
1418 if( !zColl
) return;
1420 if( sqlite3LocateCollSeq(pParse
, zColl
) ){
1422 sqlite3DbFree(db
, p
->aCol
[i
].zColl
);
1423 p
->aCol
[i
].zColl
= zColl
;
1425 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1426 ** then an index may have been created on this column before the
1427 ** collation type was added. Correct this if it is the case.
1429 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1430 assert( pIdx
->nKeyCol
==1 );
1431 if( pIdx
->aiColumn
[0]==i
){
1432 pIdx
->azColl
[0] = p
->aCol
[i
].zColl
;
1436 sqlite3DbFree(db
, zColl
);
1441 ** This function returns the collation sequence for database native text
1442 ** encoding identified by the string zName, length nName.
1444 ** If the requested collation sequence is not available, or not available
1445 ** in the database native encoding, the collation factory is invoked to
1446 ** request it. If the collation factory does not supply such a sequence,
1447 ** and the sequence is available in another text encoding, then that is
1448 ** returned instead.
1450 ** If no versions of the requested collations sequence are available, or
1451 ** another error occurs, NULL is returned and an error message written into
1454 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1455 ** invokes the collation factory if the named collation cannot be found
1456 ** and generates an error message.
1458 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1460 CollSeq
*sqlite3LocateCollSeq(Parse
*pParse
, const char *zName
){
1461 sqlite3
*db
= pParse
->db
;
1463 u8 initbusy
= db
->init
.busy
;
1466 pColl
= sqlite3FindCollSeq(db
, enc
, zName
, initbusy
);
1467 if( !initbusy
&& (!pColl
|| !pColl
->xCmp
) ){
1468 pColl
= sqlite3GetCollSeq(pParse
, enc
, pColl
, zName
);
1476 ** Generate code that will increment the schema cookie.
1478 ** The schema cookie is used to determine when the schema for the
1479 ** database changes. After each schema change, the cookie value
1480 ** changes. When a process first reads the schema it records the
1481 ** cookie. Thereafter, whenever it goes to access the database,
1482 ** it checks the cookie to make sure the schema has not changed
1483 ** since it was last read.
1485 ** This plan is not completely bullet-proof. It is possible for
1486 ** the schema to change multiple times and for the cookie to be
1487 ** set back to prior value. But schema changes are infrequent
1488 ** and the probability of hitting the same cookie value is only
1489 ** 1 chance in 2^32. So we're safe enough.
1491 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
1492 ** the schema-version whenever the schema changes.
1494 void sqlite3ChangeCookie(Parse
*pParse
, int iDb
){
1495 sqlite3
*db
= pParse
->db
;
1496 Vdbe
*v
= pParse
->pVdbe
;
1497 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
1498 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_SCHEMA_VERSION
,
1499 (int)(1+(unsigned)db
->aDb
[iDb
].pSchema
->schema_cookie
));
1503 ** Measure the number of characters needed to output the given
1504 ** identifier. The number returned includes any quotes used
1505 ** but does not include the null terminator.
1507 ** The estimate is conservative. It might be larger that what is
1510 static int identLength(const char *z
){
1512 for(n
=0; *z
; n
++, z
++){
1513 if( *z
=='"' ){ n
++; }
1519 ** The first parameter is a pointer to an output buffer. The second
1520 ** parameter is a pointer to an integer that contains the offset at
1521 ** which to write into the output buffer. This function copies the
1522 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1523 ** to the specified offset in the buffer and updates *pIdx to refer
1524 ** to the first byte after the last byte written before returning.
1526 ** If the string zSignedIdent consists entirely of alpha-numeric
1527 ** characters, does not begin with a digit and is not an SQL keyword,
1528 ** then it is copied to the output buffer exactly as it is. Otherwise,
1529 ** it is quoted using double-quotes.
1531 static void identPut(char *z
, int *pIdx
, char *zSignedIdent
){
1532 unsigned char *zIdent
= (unsigned char*)zSignedIdent
;
1533 int i
, j
, needQuote
;
1536 for(j
=0; zIdent
[j
]; j
++){
1537 if( !sqlite3Isalnum(zIdent
[j
]) && zIdent
[j
]!='_' ) break;
1539 needQuote
= sqlite3Isdigit(zIdent
[0])
1540 || sqlite3KeywordCode(zIdent
, j
)!=TK_ID
1544 if( needQuote
) z
[i
++] = '"';
1545 for(j
=0; zIdent
[j
]; j
++){
1547 if( zIdent
[j
]=='"' ) z
[i
++] = '"';
1549 if( needQuote
) z
[i
++] = '"';
1555 ** Generate a CREATE TABLE statement appropriate for the given
1556 ** table. Memory to hold the text of the statement is obtained
1557 ** from sqliteMalloc() and must be freed by the calling function.
1559 static char *createTableStmt(sqlite3
*db
, Table
*p
){
1562 char *zSep
, *zSep2
, *zEnd
;
1565 for(pCol
= p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
1566 n
+= identLength(pCol
->zName
) + 5;
1568 n
+= identLength(p
->zName
);
1578 n
+= 35 + 6*p
->nCol
;
1579 zStmt
= sqlite3DbMallocRaw(0, n
);
1581 sqlite3OomFault(db
);
1584 sqlite3_snprintf(n
, zStmt
, "CREATE TABLE ");
1585 k
= sqlite3Strlen30(zStmt
);
1586 identPut(zStmt
, &k
, p
->zName
);
1588 for(pCol
=p
->aCol
, i
=0; i
<p
->nCol
; i
++, pCol
++){
1589 static const char * const azType
[] = {
1590 /* SQLITE_AFF_BLOB */ "",
1591 /* SQLITE_AFF_TEXT */ " TEXT",
1592 /* SQLITE_AFF_NUMERIC */ " NUM",
1593 /* SQLITE_AFF_INTEGER */ " INT",
1594 /* SQLITE_AFF_REAL */ " REAL"
1599 sqlite3_snprintf(n
-k
, &zStmt
[k
], zSep
);
1600 k
+= sqlite3Strlen30(&zStmt
[k
]);
1602 identPut(zStmt
, &k
, pCol
->zName
);
1603 assert( pCol
->affinity
-SQLITE_AFF_BLOB
>= 0 );
1604 assert( pCol
->affinity
-SQLITE_AFF_BLOB
< ArraySize(azType
) );
1605 testcase( pCol
->affinity
==SQLITE_AFF_BLOB
);
1606 testcase( pCol
->affinity
==SQLITE_AFF_TEXT
);
1607 testcase( pCol
->affinity
==SQLITE_AFF_NUMERIC
);
1608 testcase( pCol
->affinity
==SQLITE_AFF_INTEGER
);
1609 testcase( pCol
->affinity
==SQLITE_AFF_REAL
);
1611 zType
= azType
[pCol
->affinity
- SQLITE_AFF_BLOB
];
1612 len
= sqlite3Strlen30(zType
);
1613 assert( pCol
->affinity
==SQLITE_AFF_BLOB
1614 || pCol
->affinity
==sqlite3AffinityType(zType
, 0) );
1615 memcpy(&zStmt
[k
], zType
, len
);
1619 sqlite3_snprintf(n
-k
, &zStmt
[k
], "%s", zEnd
);
1624 ** Resize an Index object to hold N columns total. Return SQLITE_OK
1625 ** on success and SQLITE_NOMEM on an OOM error.
1627 static int resizeIndexObject(sqlite3
*db
, Index
*pIdx
, int N
){
1630 if( pIdx
->nColumn
>=N
) return SQLITE_OK
;
1631 assert( pIdx
->isResized
==0 );
1632 nByte
= (sizeof(char*) + sizeof(i16
) + 1)*N
;
1633 zExtra
= sqlite3DbMallocZero(db
, nByte
);
1634 if( zExtra
==0 ) return SQLITE_NOMEM_BKPT
;
1635 memcpy(zExtra
, pIdx
->azColl
, sizeof(char*)*pIdx
->nColumn
);
1636 pIdx
->azColl
= (const char**)zExtra
;
1637 zExtra
+= sizeof(char*)*N
;
1638 memcpy(zExtra
, pIdx
->aiColumn
, sizeof(i16
)*pIdx
->nColumn
);
1639 pIdx
->aiColumn
= (i16
*)zExtra
;
1640 zExtra
+= sizeof(i16
)*N
;
1641 memcpy(zExtra
, pIdx
->aSortOrder
, pIdx
->nColumn
);
1642 pIdx
->aSortOrder
= (u8
*)zExtra
;
1644 pIdx
->isResized
= 1;
1649 ** Estimate the total row width for a table.
1651 static void estimateTableWidth(Table
*pTab
){
1652 unsigned wTable
= 0;
1653 const Column
*pTabCol
;
1655 for(i
=pTab
->nCol
, pTabCol
=pTab
->aCol
; i
>0; i
--, pTabCol
++){
1656 wTable
+= pTabCol
->szEst
;
1658 if( pTab
->iPKey
<0 ) wTable
++;
1659 pTab
->szTabRow
= sqlite3LogEst(wTable
*4);
1663 ** Estimate the average size of a row for an index.
1665 static void estimateIndexWidth(Index
*pIdx
){
1666 unsigned wIndex
= 0;
1668 const Column
*aCol
= pIdx
->pTable
->aCol
;
1669 for(i
=0; i
<pIdx
->nColumn
; i
++){
1670 i16 x
= pIdx
->aiColumn
[i
];
1671 assert( x
<pIdx
->pTable
->nCol
);
1672 wIndex
+= x
<0 ? 1 : aCol
[pIdx
->aiColumn
[i
]].szEst
;
1674 pIdx
->szIdxRow
= sqlite3LogEst(wIndex
*4);
1677 /* Return true if value x is found any of the first nCol entries of aiCol[]
1679 static int hasColumn(const i16
*aiCol
, int nCol
, int x
){
1680 while( nCol
-- > 0 ) if( x
==*(aiCol
++) ) return 1;
1685 ** This routine runs at the end of parsing a CREATE TABLE statement that
1686 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
1687 ** internal schema data structures and the generated VDBE code so that they
1688 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1691 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1692 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
1693 ** into BTREE_BLOBKEY.
1694 ** (3) Bypass the creation of the sqlite_master table entry
1695 ** for the PRIMARY KEY as the primary key index is now
1696 ** identified by the sqlite_master table entry of the table itself.
1697 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
1698 ** schema to the rootpage from the main table.
1699 ** (5) Add all table columns to the PRIMARY KEY Index object
1700 ** so that the PRIMARY KEY is a covering index. The surplus
1701 ** columns are part of KeyInfo.nAllField and are not used for
1702 ** sorting or lookup or uniqueness checks.
1703 ** (6) Replace the rowid tail on all automatically generated UNIQUE
1704 ** indices with the PRIMARY KEY columns.
1706 ** For virtual tables, only (1) is performed.
1708 static void convertToWithoutRowidTable(Parse
*pParse
, Table
*pTab
){
1713 sqlite3
*db
= pParse
->db
;
1714 Vdbe
*v
= pParse
->pVdbe
;
1716 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
1718 if( !db
->init
.imposterTable
){
1719 for(i
=0; i
<pTab
->nCol
; i
++){
1720 if( (pTab
->aCol
[i
].colFlags
& COLFLAG_PRIMKEY
)!=0 ){
1721 pTab
->aCol
[i
].notNull
= OE_Abort
;
1726 /* The remaining transformations only apply to b-tree tables, not to
1727 ** virtual tables */
1728 if( IN_DECLARE_VTAB
) return;
1730 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
1731 ** into BTREE_BLOBKEY.
1733 if( pParse
->addrCrTab
){
1735 sqlite3VdbeChangeP3(v
, pParse
->addrCrTab
, BTREE_BLOBKEY
);
1738 /* Locate the PRIMARY KEY index. Or, if this table was originally
1739 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1741 if( pTab
->iPKey
>=0 ){
1744 sqlite3TokenInit(&ipkToken
, pTab
->aCol
[pTab
->iPKey
].zName
);
1745 pList
= sqlite3ExprListAppend(pParse
, 0,
1746 sqlite3ExprAlloc(db
, TK_ID
, &ipkToken
, 0));
1747 if( pList
==0 ) return;
1748 pList
->a
[0].sortOrder
= pParse
->iPkSortOrder
;
1749 assert( pParse
->pNewTable
==pTab
);
1750 sqlite3CreateIndex(pParse
, 0, 0, 0, pList
, pTab
->keyConf
, 0, 0, 0, 0,
1751 SQLITE_IDXTYPE_PRIMARYKEY
);
1752 if( db
->mallocFailed
) return;
1753 pPk
= sqlite3PrimaryKeyIndex(pTab
);
1756 pPk
= sqlite3PrimaryKeyIndex(pTab
);
1759 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1760 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1761 ** code assumes the PRIMARY KEY contains no repeated columns.
1763 for(i
=j
=1; i
<pPk
->nKeyCol
; i
++){
1764 if( hasColumn(pPk
->aiColumn
, j
, pPk
->aiColumn
[i
]) ){
1767 pPk
->aiColumn
[j
++] = pPk
->aiColumn
[i
];
1773 pPk
->isCovering
= 1;
1774 if( !db
->init
.imposterTable
) pPk
->uniqNotNull
= 1;
1777 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1778 ** table entry. This is only required if currently generating VDBE
1779 ** code for a CREATE TABLE (not when parsing one as part of reading
1780 ** a database schema). */
1781 if( v
&& pPk
->tnum
>0 ){
1782 assert( db
->init
.busy
==0 );
1783 sqlite3VdbeChangeOpcode(v
, pPk
->tnum
, OP_Goto
);
1786 /* The root page of the PRIMARY KEY is the table root page */
1787 pPk
->tnum
= pTab
->tnum
;
1789 /* Update the in-memory representation of all UNIQUE indices by converting
1790 ** the final rowid column into one or more columns of the PRIMARY KEY.
1792 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1794 if( IsPrimaryKeyIndex(pIdx
) ) continue;
1795 for(i
=n
=0; i
<nPk
; i
++){
1796 if( !hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) ) n
++;
1799 /* This index is a superset of the primary key */
1800 pIdx
->nColumn
= pIdx
->nKeyCol
;
1803 if( resizeIndexObject(db
, pIdx
, pIdx
->nKeyCol
+n
) ) return;
1804 for(i
=0, j
=pIdx
->nKeyCol
; i
<nPk
; i
++){
1805 if( !hasColumn(pIdx
->aiColumn
, pIdx
->nKeyCol
, pPk
->aiColumn
[i
]) ){
1806 pIdx
->aiColumn
[j
] = pPk
->aiColumn
[i
];
1807 pIdx
->azColl
[j
] = pPk
->azColl
[i
];
1811 assert( pIdx
->nColumn
>=pIdx
->nKeyCol
+n
);
1812 assert( pIdx
->nColumn
>=j
);
1815 /* Add all table columns to the PRIMARY KEY index
1817 if( nPk
<pTab
->nCol
){
1818 if( resizeIndexObject(db
, pPk
, pTab
->nCol
) ) return;
1819 for(i
=0, j
=nPk
; i
<pTab
->nCol
; i
++){
1820 if( !hasColumn(pPk
->aiColumn
, j
, i
) ){
1821 assert( j
<pPk
->nColumn
);
1822 pPk
->aiColumn
[j
] = i
;
1823 pPk
->azColl
[j
] = sqlite3StrBINARY
;
1827 assert( pPk
->nColumn
==j
);
1828 assert( pTab
->nCol
==j
);
1830 pPk
->nColumn
= pTab
->nCol
;
1835 ** This routine is called to report the final ")" that terminates
1836 ** a CREATE TABLE statement.
1838 ** The table structure that other action routines have been building
1839 ** is added to the internal hash tables, assuming no errors have
1842 ** An entry for the table is made in the master table on disk, unless
1843 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1844 ** it means we are reading the sqlite_master table because we just
1845 ** connected to the database or because the sqlite_master table has
1846 ** recently changed, so the entry for this table already exists in
1847 ** the sqlite_master table. We do not want to create it again.
1849 ** If the pSelect argument is not NULL, it means that this routine
1850 ** was called to create a table generated from a
1851 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1852 ** the new table will match the result set of the SELECT.
1854 void sqlite3EndTable(
1855 Parse
*pParse
, /* Parse context */
1856 Token
*pCons
, /* The ',' token after the last column defn. */
1857 Token
*pEnd
, /* The ')' before options in the CREATE TABLE */
1858 u8 tabOpts
, /* Extra table options. Usually 0. */
1859 Select
*pSelect
/* Select from a "CREATE ... AS SELECT" */
1861 Table
*p
; /* The new table */
1862 sqlite3
*db
= pParse
->db
; /* The database connection */
1863 int iDb
; /* Database in which the table lives */
1864 Index
*pIdx
; /* An implied index of the table */
1866 if( pEnd
==0 && pSelect
==0 ){
1869 assert( !db
->mallocFailed
);
1870 p
= pParse
->pNewTable
;
1873 /* If the db->init.busy is 1 it means we are reading the SQL off the
1874 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1875 ** So do not write to the disk again. Extract the root page number
1876 ** for the table from the db->init.newTnum field. (The page number
1877 ** should have been put there by the sqliteOpenCb routine.)
1879 ** If the root page number is 1, that means this is the sqlite_master
1880 ** table itself. So mark it read-only.
1882 if( db
->init
.busy
){
1884 sqlite3ErrorMsg(pParse
, "");
1887 p
->tnum
= db
->init
.newTnum
;
1888 if( p
->tnum
==1 ) p
->tabFlags
|= TF_Readonly
;
1891 /* Special processing for WITHOUT ROWID Tables */
1892 if( tabOpts
& TF_WithoutRowid
){
1893 if( (p
->tabFlags
& TF_Autoincrement
) ){
1894 sqlite3ErrorMsg(pParse
,
1895 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1898 if( (p
->tabFlags
& TF_HasPrimaryKey
)==0 ){
1899 sqlite3ErrorMsg(pParse
, "PRIMARY KEY missing on table %s", p
->zName
);
1901 p
->tabFlags
|= TF_WithoutRowid
| TF_NoVisibleRowid
;
1902 convertToWithoutRowidTable(pParse
, p
);
1906 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
1908 #ifndef SQLITE_OMIT_CHECK
1909 /* Resolve names in all CHECK constraint expressions.
1912 sqlite3ResolveSelfReference(pParse
, p
, NC_IsCheck
, 0, p
->pCheck
);
1914 #endif /* !defined(SQLITE_OMIT_CHECK) */
1916 /* Estimate the average row size for the table and for all implied indices */
1917 estimateTableWidth(p
);
1918 for(pIdx
=p
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1919 estimateIndexWidth(pIdx
);
1922 /* If not initializing, then create a record for the new table
1923 ** in the SQLITE_MASTER table of the database.
1925 ** If this is a TEMPORARY table, write the entry into the auxiliary
1926 ** file instead of into the main database file.
1928 if( !db
->init
.busy
){
1931 char *zType
; /* "view" or "table" */
1932 char *zType2
; /* "VIEW" or "TABLE" */
1933 char *zStmt
; /* Text of the CREATE TABLE or CREATE VIEW statement */
1935 v
= sqlite3GetVdbe(pParse
);
1936 if( NEVER(v
==0) ) return;
1938 sqlite3VdbeAddOp1(v
, OP_Close
, 0);
1941 ** Initialize zType for the new view or table.
1943 if( p
->pSelect
==0 ){
1944 /* A regular table */
1947 #ifndef SQLITE_OMIT_VIEW
1955 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1956 ** statement to populate the new table. The root-page number for the
1957 ** new table is in register pParse->regRoot.
1959 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1960 ** suitable state to query for the column names and types to be used
1961 ** by the new table.
1963 ** A shared-cache write-lock is not required to write to the new table,
1964 ** as a schema-lock must have already been obtained to create it. Since
1965 ** a schema-lock excludes all other database users, the write-lock would
1969 SelectDest dest
; /* Where the SELECT should store results */
1970 int regYield
; /* Register holding co-routine entry-point */
1971 int addrTop
; /* Top of the co-routine */
1972 int regRec
; /* A record to be insert into the new table */
1973 int regRowid
; /* Rowid of the next row to insert */
1974 int addrInsLoop
; /* Top of the loop for inserting rows */
1975 Table
*pSelTab
; /* A table that describes the SELECT results */
1977 regYield
= ++pParse
->nMem
;
1978 regRec
= ++pParse
->nMem
;
1979 regRowid
= ++pParse
->nMem
;
1980 assert(pParse
->nTab
==1);
1981 sqlite3MayAbort(pParse
);
1982 sqlite3VdbeAddOp3(v
, OP_OpenWrite
, 1, pParse
->regRoot
, iDb
);
1983 sqlite3VdbeChangeP5(v
, OPFLAG_P2ISREG
);
1985 addrTop
= sqlite3VdbeCurrentAddr(v
) + 1;
1986 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, addrTop
);
1987 if( pParse
->nErr
) return;
1988 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSelect
);
1989 if( pSelTab
==0 ) return;
1990 assert( p
->aCol
==0 );
1991 p
->nCol
= pSelTab
->nCol
;
1992 p
->aCol
= pSelTab
->aCol
;
1995 sqlite3DeleteTable(db
, pSelTab
);
1996 sqlite3SelectDestInit(&dest
, SRT_Coroutine
, regYield
);
1997 sqlite3Select(pParse
, pSelect
, &dest
);
1998 if( pParse
->nErr
) return;
1999 sqlite3VdbeEndCoroutine(v
, regYield
);
2000 sqlite3VdbeJumpHere(v
, addrTop
- 1);
2001 addrInsLoop
= sqlite3VdbeAddOp1(v
, OP_Yield
, dest
.iSDParm
);
2003 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, dest
.iSdst
, dest
.nSdst
, regRec
);
2004 sqlite3TableAffinity(v
, p
, 0);
2005 sqlite3VdbeAddOp2(v
, OP_NewRowid
, 1, regRowid
);
2006 sqlite3VdbeAddOp3(v
, OP_Insert
, 1, regRec
, regRowid
);
2007 sqlite3VdbeGoto(v
, addrInsLoop
);
2008 sqlite3VdbeJumpHere(v
, addrInsLoop
);
2009 sqlite3VdbeAddOp1(v
, OP_Close
, 1);
2012 /* Compute the complete text of the CREATE statement */
2014 zStmt
= createTableStmt(db
, p
);
2016 Token
*pEnd2
= tabOpts
? &pParse
->sLastToken
: pEnd
;
2017 n
= (int)(pEnd2
->z
- pParse
->sNameToken
.z
);
2018 if( pEnd2
->z
[0]!=';' ) n
+= pEnd2
->n
;
2019 zStmt
= sqlite3MPrintf(db
,
2020 "CREATE %s %.*s", zType2
, n
, pParse
->sNameToken
.z
2024 /* A slot for the record has already been allocated in the
2025 ** SQLITE_MASTER table. We just need to update that slot with all
2026 ** the information we've collected.
2028 sqlite3NestedParse(pParse
,
2030 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
2032 db
->aDb
[iDb
].zDbSName
, MASTER_NAME
,
2040 sqlite3DbFree(db
, zStmt
);
2041 sqlite3ChangeCookie(pParse
, iDb
);
2043 #ifndef SQLITE_OMIT_AUTOINCREMENT
2044 /* Check to see if we need to create an sqlite_sequence table for
2045 ** keeping track of autoincrement keys.
2047 if( (p
->tabFlags
& TF_Autoincrement
)!=0 ){
2048 Db
*pDb
= &db
->aDb
[iDb
];
2049 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2050 if( pDb
->pSchema
->pSeqTab
==0 ){
2051 sqlite3NestedParse(pParse
,
2052 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2059 /* Reparse everything to update our internal data structures */
2060 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
2061 sqlite3MPrintf(db
, "tbl_name='%q' AND type!='trigger'", p
->zName
));
2065 /* Add the table to the in-memory representation of the database.
2067 if( db
->init
.busy
){
2069 Schema
*pSchema
= p
->pSchema
;
2070 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2071 pOld
= sqlite3HashInsert(&pSchema
->tblHash
, p
->zName
, p
);
2073 assert( p
==pOld
); /* Malloc must have failed inside HashInsert() */
2074 sqlite3OomFault(db
);
2077 pParse
->pNewTable
= 0;
2078 db
->mDbFlags
|= DBFLAG_SchemaChange
;
2080 #ifndef SQLITE_OMIT_ALTERTABLE
2082 const char *zName
= (const char *)pParse
->sNameToken
.z
;
2084 assert( !pSelect
&& pCons
&& pEnd
);
2088 nName
= (int)((const char *)pCons
->z
- zName
);
2089 p
->addColOffset
= 13 + sqlite3Utf8CharLen(zName
, nName
);
2095 #ifndef SQLITE_OMIT_VIEW
2097 ** The parser calls this routine in order to create a new VIEW
2099 void sqlite3CreateView(
2100 Parse
*pParse
, /* The parsing context */
2101 Token
*pBegin
, /* The CREATE token that begins the statement */
2102 Token
*pName1
, /* The token that holds the name of the view */
2103 Token
*pName2
, /* The token that holds the name of the view */
2104 ExprList
*pCNames
, /* Optional list of view column names */
2105 Select
*pSelect
, /* A SELECT statement that will become the new view */
2106 int isTemp
, /* TRUE for a TEMPORARY view */
2107 int noErr
/* Suppress error messages if VIEW already exists */
2116 sqlite3
*db
= pParse
->db
;
2118 if( pParse
->nVar
>0 ){
2119 sqlite3ErrorMsg(pParse
, "parameters are not allowed in views");
2120 goto create_view_fail
;
2122 sqlite3StartTable(pParse
, pName1
, pName2
, isTemp
, 1, 0, noErr
);
2123 p
= pParse
->pNewTable
;
2124 if( p
==0 || pParse
->nErr
) goto create_view_fail
;
2125 sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
2126 iDb
= sqlite3SchemaToIndex(db
, p
->pSchema
);
2127 sqlite3FixInit(&sFix
, pParse
, iDb
, "view", pName
);
2128 if( sqlite3FixSelect(&sFix
, pSelect
) ) goto create_view_fail
;
2130 /* Make a copy of the entire SELECT statement that defines the view.
2131 ** This will force all the Expr.token.z values to be dynamically
2132 ** allocated rather than point to the input string - which means that
2133 ** they will persist after the current sqlite3_exec() call returns.
2135 p
->pSelect
= sqlite3SelectDup(db
, pSelect
, EXPRDUP_REDUCE
);
2136 p
->pCheck
= sqlite3ExprListDup(db
, pCNames
, EXPRDUP_REDUCE
);
2137 if( db
->mallocFailed
) goto create_view_fail
;
2139 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2142 sEnd
= pParse
->sLastToken
;
2143 assert( sEnd
.z
[0]!=0 || sEnd
.n
==0 );
2144 if( sEnd
.z
[0]!=';' ){
2148 n
= (int)(sEnd
.z
- pBegin
->z
);
2151 while( sqlite3Isspace(z
[n
-1]) ){ n
--; }
2155 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
2156 sqlite3EndTable(pParse
, 0, &sEnd
, 0, 0);
2159 sqlite3SelectDelete(db
, pSelect
);
2160 sqlite3ExprListDelete(db
, pCNames
);
2163 #endif /* SQLITE_OMIT_VIEW */
2165 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
2167 ** The Table structure pTable is really a VIEW. Fill in the names of
2168 ** the columns of the view in the pTable structure. Return the number
2169 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
2171 int sqlite3ViewGetColumnNames(Parse
*pParse
, Table
*pTable
){
2172 Table
*pSelTab
; /* A fake table from which we get the result set */
2173 Select
*pSel
; /* Copy of the SELECT that implements the view */
2174 int nErr
= 0; /* Number of errors encountered */
2175 int n
; /* Temporarily holds the number of cursors assigned */
2176 sqlite3
*db
= pParse
->db
; /* Database connection for malloc errors */
2177 #ifndef SQLITE_OMIT_VIRTUALTABLE
2180 #ifndef SQLITE_OMIT_AUTHORIZATION
2181 sqlite3_xauth xAuth
; /* Saved xAuth pointer */
2186 #ifndef SQLITE_OMIT_VIRTUALTABLE
2188 rc
= sqlite3VtabCallConnect(pParse
, pTable
);
2193 if( IsVirtual(pTable
) ) return 0;
2196 #ifndef SQLITE_OMIT_VIEW
2197 /* A positive nCol means the columns names for this view are
2200 if( pTable
->nCol
>0 ) return 0;
2202 /* A negative nCol is a special marker meaning that we are currently
2203 ** trying to compute the column names. If we enter this routine with
2204 ** a negative nCol, it means two or more views form a loop, like this:
2206 ** CREATE VIEW one AS SELECT * FROM two;
2207 ** CREATE VIEW two AS SELECT * FROM one;
2209 ** Actually, the error above is now caught prior to reaching this point.
2210 ** But the following test is still important as it does come up
2211 ** in the following:
2213 ** CREATE TABLE main.ex1(a);
2214 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2215 ** SELECT * FROM temp.ex1;
2217 if( pTable
->nCol
<0 ){
2218 sqlite3ErrorMsg(pParse
, "view %s is circularly defined", pTable
->zName
);
2221 assert( pTable
->nCol
>=0 );
2223 /* If we get this far, it means we need to compute the table names.
2224 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2225 ** "*" elements in the results set of the view and will assign cursors
2226 ** to the elements of the FROM clause. But we do not want these changes
2227 ** to be permanent. So the computation is done on a copy of the SELECT
2228 ** statement that defines the view.
2230 assert( pTable
->pSelect
);
2231 pSel
= sqlite3SelectDup(db
, pTable
->pSelect
, 0);
2234 sqlite3SrcListAssignCursors(pParse
, pSel
->pSrc
);
2236 db
->lookaside
.bDisable
++;
2237 #ifndef SQLITE_OMIT_AUTHORIZATION
2240 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
);
2243 pSelTab
= sqlite3ResultSetOfSelect(pParse
, pSel
);
2246 if( pTable
->pCheck
){
2247 /* CREATE VIEW name(arglist) AS ...
2248 ** The names of the columns in the table are taken from
2249 ** arglist which is stored in pTable->pCheck. The pCheck field
2250 ** normally holds CHECK constraints on an ordinary table, but for
2251 ** a VIEW it holds the list of column names.
2253 sqlite3ColumnsFromExprList(pParse
, pTable
->pCheck
,
2254 &pTable
->nCol
, &pTable
->aCol
);
2255 if( db
->mallocFailed
==0
2257 && pTable
->nCol
==pSel
->pEList
->nExpr
2259 sqlite3SelectAddColumnTypeAndCollation(pParse
, pTable
, pSel
);
2261 }else if( pSelTab
){
2262 /* CREATE VIEW name AS... without an argument list. Construct
2263 ** the column names from the SELECT statement that defines the view.
2265 assert( pTable
->aCol
==0 );
2266 pTable
->nCol
= pSelTab
->nCol
;
2267 pTable
->aCol
= pSelTab
->aCol
;
2270 assert( sqlite3SchemaMutexHeld(db
, 0, pTable
->pSchema
) );
2275 sqlite3DeleteTable(db
, pSelTab
);
2276 sqlite3SelectDelete(db
, pSel
);
2277 db
->lookaside
.bDisable
--;
2281 pTable
->pSchema
->schemaFlags
|= DB_UnresetViews
;
2282 #endif /* SQLITE_OMIT_VIEW */
2285 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
2287 #ifndef SQLITE_OMIT_VIEW
2289 ** Clear the column names from every VIEW in database idx.
2291 static void sqliteViewResetAll(sqlite3
*db
, int idx
){
2293 assert( sqlite3SchemaMutexHeld(db
, idx
, 0) );
2294 if( !DbHasProperty(db
, idx
, DB_UnresetViews
) ) return;
2295 for(i
=sqliteHashFirst(&db
->aDb
[idx
].pSchema
->tblHash
); i
;i
=sqliteHashNext(i
)){
2296 Table
*pTab
= sqliteHashData(i
);
2297 if( pTab
->pSelect
){
2298 sqlite3DeleteColumnNames(db
, pTab
);
2303 DbClearProperty(db
, idx
, DB_UnresetViews
);
2306 # define sqliteViewResetAll(A,B)
2307 #endif /* SQLITE_OMIT_VIEW */
2310 ** This function is called by the VDBE to adjust the internal schema
2311 ** used by SQLite when the btree layer moves a table root page. The
2312 ** root-page of a table or index in database iDb has changed from iFrom
2315 ** Ticket #1728: The symbol table might still contain information
2316 ** on tables and/or indices that are the process of being deleted.
2317 ** If you are unlucky, one of those deleted indices or tables might
2318 ** have the same rootpage number as the real table or index that is
2319 ** being moved. So we cannot stop searching after the first match
2320 ** because the first match might be for one of the deleted indices
2321 ** or tables and not the table/index that is actually being moved.
2322 ** We must continue looping until all tables and indices with
2323 ** rootpage==iFrom have been converted to have a rootpage of iTo
2324 ** in order to be certain that we got the right one.
2326 #ifndef SQLITE_OMIT_AUTOVACUUM
2327 void sqlite3RootPageMoved(sqlite3
*db
, int iDb
, int iFrom
, int iTo
){
2332 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
2333 pDb
= &db
->aDb
[iDb
];
2334 pHash
= &pDb
->pSchema
->tblHash
;
2335 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
2336 Table
*pTab
= sqliteHashData(pElem
);
2337 if( pTab
->tnum
==iFrom
){
2341 pHash
= &pDb
->pSchema
->idxHash
;
2342 for(pElem
=sqliteHashFirst(pHash
); pElem
; pElem
=sqliteHashNext(pElem
)){
2343 Index
*pIdx
= sqliteHashData(pElem
);
2344 if( pIdx
->tnum
==iFrom
){
2352 ** Write code to erase the table with root-page iTable from database iDb.
2353 ** Also write code to modify the sqlite_master table and internal schema
2354 ** if a root-page of another table is moved by the btree-layer whilst
2355 ** erasing iTable (this can happen with an auto-vacuum database).
2357 static void destroyRootPage(Parse
*pParse
, int iTable
, int iDb
){
2358 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2359 int r1
= sqlite3GetTempReg(pParse
);
2361 sqlite3VdbeAddOp3(v
, OP_Destroy
, iTable
, r1
, iDb
);
2362 sqlite3MayAbort(pParse
);
2363 #ifndef SQLITE_OMIT_AUTOVACUUM
2364 /* OP_Destroy stores an in integer r1. If this integer
2365 ** is non-zero, then it is the root page number of a table moved to
2366 ** location iTable. The following code modifies the sqlite_master table to
2369 ** The "#NNN" in the SQL is a special constant that means whatever value
2370 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2371 ** token for additional information.
2373 sqlite3NestedParse(pParse
,
2374 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2375 pParse
->db
->aDb
[iDb
].zDbSName
, MASTER_NAME
, iTable
, r1
, r1
);
2377 sqlite3ReleaseTempReg(pParse
, r1
);
2381 ** Write VDBE code to erase table pTab and all associated indices on disk.
2382 ** Code to update the sqlite_master tables and internal schema definitions
2383 ** in case a root-page belonging to another table is moved by the btree layer
2384 ** is also added (this can happen with an auto-vacuum database).
2386 static void destroyTable(Parse
*pParse
, Table
*pTab
){
2387 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2388 ** is not defined), then it is important to call OP_Destroy on the
2389 ** table and index root-pages in order, starting with the numerically
2390 ** largest root-page number. This guarantees that none of the root-pages
2391 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2392 ** following were coded:
2398 ** and root page 5 happened to be the largest root-page number in the
2399 ** database, then root page 5 would be moved to page 4 by the
2400 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2401 ** a free-list page.
2403 int iTab
= pTab
->tnum
;
2410 if( iDestroyed
==0 || iTab
<iDestroyed
){
2413 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
2414 int iIdx
= pIdx
->tnum
;
2415 assert( pIdx
->pSchema
==pTab
->pSchema
);
2416 if( (iDestroyed
==0 || (iIdx
<iDestroyed
)) && iIdx
>iLargest
){
2423 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
2424 assert( iDb
>=0 && iDb
<pParse
->db
->nDb
);
2425 destroyRootPage(pParse
, iLargest
, iDb
);
2426 iDestroyed
= iLargest
;
2432 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2433 ** after a DROP INDEX or DROP TABLE command.
2435 static void sqlite3ClearStatTables(
2436 Parse
*pParse
, /* The parsing context */
2437 int iDb
, /* The database number */
2438 const char *zType
, /* "idx" or "tbl" */
2439 const char *zName
/* Name of index or table */
2442 const char *zDbName
= pParse
->db
->aDb
[iDb
].zDbSName
;
2443 for(i
=1; i
<=4; i
++){
2445 sqlite3_snprintf(sizeof(zTab
),zTab
,"sqlite_stat%d",i
);
2446 if( sqlite3FindTable(pParse
->db
, zTab
, zDbName
) ){
2447 sqlite3NestedParse(pParse
,
2448 "DELETE FROM %Q.%s WHERE %s=%Q",
2449 zDbName
, zTab
, zType
, zName
2456 ** Generate code to drop a table.
2458 void sqlite3CodeDropTable(Parse
*pParse
, Table
*pTab
, int iDb
, int isView
){
2460 sqlite3
*db
= pParse
->db
;
2462 Db
*pDb
= &db
->aDb
[iDb
];
2464 v
= sqlite3GetVdbe(pParse
);
2466 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
2468 #ifndef SQLITE_OMIT_VIRTUALTABLE
2469 if( IsVirtual(pTab
) ){
2470 sqlite3VdbeAddOp0(v
, OP_VBegin
);
2474 /* Drop all triggers associated with the table being dropped. Code
2475 ** is generated to remove entries from sqlite_master and/or
2476 ** sqlite_temp_master if required.
2478 pTrigger
= sqlite3TriggerList(pParse
, pTab
);
2480 assert( pTrigger
->pSchema
==pTab
->pSchema
||
2481 pTrigger
->pSchema
==db
->aDb
[1].pSchema
);
2482 sqlite3DropTriggerPtr(pParse
, pTrigger
);
2483 pTrigger
= pTrigger
->pNext
;
2486 #ifndef SQLITE_OMIT_AUTOINCREMENT
2487 /* Remove any entries of the sqlite_sequence table associated with
2488 ** the table being dropped. This is done before the table is dropped
2489 ** at the btree level, in case the sqlite_sequence table needs to
2490 ** move as a result of the drop (can happen in auto-vacuum mode).
2492 if( pTab
->tabFlags
& TF_Autoincrement
){
2493 sqlite3NestedParse(pParse
,
2494 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2495 pDb
->zDbSName
, pTab
->zName
2500 /* Drop all SQLITE_MASTER table and index entries that refer to the
2501 ** table. The program name loops through the master table and deletes
2502 ** every row that refers to a table of the same name as the one being
2503 ** dropped. Triggers are handled separately because a trigger can be
2504 ** created in the temp database that refers to a table in another
2507 sqlite3NestedParse(pParse
,
2508 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2509 pDb
->zDbSName
, MASTER_NAME
, pTab
->zName
);
2510 if( !isView
&& !IsVirtual(pTab
) ){
2511 destroyTable(pParse
, pTab
);
2514 /* Remove the table entry from SQLite's internal schema and modify
2515 ** the schema cookie.
2517 if( IsVirtual(pTab
) ){
2518 sqlite3VdbeAddOp4(v
, OP_VDestroy
, iDb
, 0, 0, pTab
->zName
, 0);
2520 sqlite3VdbeAddOp4(v
, OP_DropTable
, iDb
, 0, 0, pTab
->zName
, 0);
2521 sqlite3ChangeCookie(pParse
, iDb
);
2522 sqliteViewResetAll(db
, iDb
);
2526 ** This routine is called to do the work of a DROP TABLE statement.
2527 ** pName is the name of the table to be dropped.
2529 void sqlite3DropTable(Parse
*pParse
, SrcList
*pName
, int isView
, int noErr
){
2532 sqlite3
*db
= pParse
->db
;
2535 if( db
->mallocFailed
){
2536 goto exit_drop_table
;
2538 assert( pParse
->nErr
==0 );
2539 assert( pName
->nSrc
==1 );
2540 if( sqlite3ReadSchema(pParse
) ) goto exit_drop_table
;
2541 if( noErr
) db
->suppressErr
++;
2542 assert( isView
==0 || isView
==LOCATE_VIEW
);
2543 pTab
= sqlite3LocateTableItem(pParse
, isView
, &pName
->a
[0]);
2544 if( noErr
) db
->suppressErr
--;
2547 if( noErr
) sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
2548 goto exit_drop_table
;
2550 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
2551 assert( iDb
>=0 && iDb
<db
->nDb
);
2553 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2554 ** it is initialized.
2556 if( IsVirtual(pTab
) && sqlite3ViewGetColumnNames(pParse
, pTab
) ){
2557 goto exit_drop_table
;
2559 #ifndef SQLITE_OMIT_AUTHORIZATION
2562 const char *zTab
= SCHEMA_TABLE(iDb
);
2563 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
2564 const char *zArg2
= 0;
2565 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
)){
2566 goto exit_drop_table
;
2569 if( !OMIT_TEMPDB
&& iDb
==1 ){
2570 code
= SQLITE_DROP_TEMP_VIEW
;
2572 code
= SQLITE_DROP_VIEW
;
2574 #ifndef SQLITE_OMIT_VIRTUALTABLE
2575 }else if( IsVirtual(pTab
) ){
2576 code
= SQLITE_DROP_VTABLE
;
2577 zArg2
= sqlite3GetVTable(db
, pTab
)->pMod
->zName
;
2580 if( !OMIT_TEMPDB
&& iDb
==1 ){
2581 code
= SQLITE_DROP_TEMP_TABLE
;
2583 code
= SQLITE_DROP_TABLE
;
2586 if( sqlite3AuthCheck(pParse
, code
, pTab
->zName
, zArg2
, zDb
) ){
2587 goto exit_drop_table
;
2589 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, pTab
->zName
, 0, zDb
) ){
2590 goto exit_drop_table
;
2594 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0
2595 && sqlite3StrNICmp(pTab
->zName
, "sqlite_stat", 11)!=0 ){
2596 sqlite3ErrorMsg(pParse
, "table %s may not be dropped", pTab
->zName
);
2597 goto exit_drop_table
;
2600 #ifndef SQLITE_OMIT_VIEW
2601 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2604 if( isView
&& pTab
->pSelect
==0 ){
2605 sqlite3ErrorMsg(pParse
, "use DROP TABLE to delete table %s", pTab
->zName
);
2606 goto exit_drop_table
;
2608 if( !isView
&& pTab
->pSelect
){
2609 sqlite3ErrorMsg(pParse
, "use DROP VIEW to delete view %s", pTab
->zName
);
2610 goto exit_drop_table
;
2614 /* Generate code to remove the table from the master table
2617 v
= sqlite3GetVdbe(pParse
);
2619 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
2620 sqlite3ClearStatTables(pParse
, iDb
, "tbl", pTab
->zName
);
2621 sqlite3FkDropTable(pParse
, pName
, pTab
);
2622 sqlite3CodeDropTable(pParse
, pTab
, iDb
, isView
);
2626 sqlite3SrcListDelete(db
, pName
);
2630 ** This routine is called to create a new foreign key on the table
2631 ** currently under construction. pFromCol determines which columns
2632 ** in the current table point to the foreign key. If pFromCol==0 then
2633 ** connect the key to the last column inserted. pTo is the name of
2634 ** the table referred to (a.k.a the "parent" table). pToCol is a list
2635 ** of tables in the parent pTo table. flags contains all
2636 ** information about the conflict resolution algorithms specified
2637 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2639 ** An FKey structure is created and added to the table currently
2640 ** under construction in the pParse->pNewTable field.
2642 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2643 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2645 void sqlite3CreateForeignKey(
2646 Parse
*pParse
, /* Parsing context */
2647 ExprList
*pFromCol
, /* Columns in this table that point to other table */
2648 Token
*pTo
, /* Name of the other table */
2649 ExprList
*pToCol
, /* Columns in the other table */
2650 int flags
/* Conflict resolution algorithms. */
2652 sqlite3
*db
= pParse
->db
;
2653 #ifndef SQLITE_OMIT_FOREIGN_KEY
2656 Table
*p
= pParse
->pNewTable
;
2663 if( p
==0 || IN_DECLARE_VTAB
) goto fk_end
;
2665 int iCol
= p
->nCol
-1;
2666 if( NEVER(iCol
<0) ) goto fk_end
;
2667 if( pToCol
&& pToCol
->nExpr
!=1 ){
2668 sqlite3ErrorMsg(pParse
, "foreign key on %s"
2669 " should reference only one column of table %T",
2670 p
->aCol
[iCol
].zName
, pTo
);
2674 }else if( pToCol
&& pToCol
->nExpr
!=pFromCol
->nExpr
){
2675 sqlite3ErrorMsg(pParse
,
2676 "number of columns in foreign key does not match the number of "
2677 "columns in the referenced table");
2680 nCol
= pFromCol
->nExpr
;
2682 nByte
= sizeof(*pFKey
) + (nCol
-1)*sizeof(pFKey
->aCol
[0]) + pTo
->n
+ 1;
2684 for(i
=0; i
<pToCol
->nExpr
; i
++){
2685 nByte
+= sqlite3Strlen30(pToCol
->a
[i
].zName
) + 1;
2688 pFKey
= sqlite3DbMallocZero(db
, nByte
);
2693 pFKey
->pNextFrom
= p
->pFKey
;
2694 z
= (char*)&pFKey
->aCol
[nCol
];
2696 memcpy(z
, pTo
->z
, pTo
->n
);
2702 pFKey
->aCol
[0].iFrom
= p
->nCol
-1;
2704 for(i
=0; i
<nCol
; i
++){
2706 for(j
=0; j
<p
->nCol
; j
++){
2707 if( sqlite3StrICmp(p
->aCol
[j
].zName
, pFromCol
->a
[i
].zName
)==0 ){
2708 pFKey
->aCol
[i
].iFrom
= j
;
2713 sqlite3ErrorMsg(pParse
,
2714 "unknown column \"%s\" in foreign key definition",
2715 pFromCol
->a
[i
].zName
);
2721 for(i
=0; i
<nCol
; i
++){
2722 int n
= sqlite3Strlen30(pToCol
->a
[i
].zName
);
2723 pFKey
->aCol
[i
].zCol
= z
;
2724 memcpy(z
, pToCol
->a
[i
].zName
, n
);
2729 pFKey
->isDeferred
= 0;
2730 pFKey
->aAction
[0] = (u8
)(flags
& 0xff); /* ON DELETE action */
2731 pFKey
->aAction
[1] = (u8
)((flags
>> 8 ) & 0xff); /* ON UPDATE action */
2733 assert( sqlite3SchemaMutexHeld(db
, 0, p
->pSchema
) );
2734 pNextTo
= (FKey
*)sqlite3HashInsert(&p
->pSchema
->fkeyHash
,
2735 pFKey
->zTo
, (void *)pFKey
2737 if( pNextTo
==pFKey
){
2738 sqlite3OomFault(db
);
2742 assert( pNextTo
->pPrevTo
==0 );
2743 pFKey
->pNextTo
= pNextTo
;
2744 pNextTo
->pPrevTo
= pFKey
;
2747 /* Link the foreign key to the table as the last step.
2753 sqlite3DbFree(db
, pFKey
);
2754 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2755 sqlite3ExprListDelete(db
, pFromCol
);
2756 sqlite3ExprListDelete(db
, pToCol
);
2760 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2761 ** clause is seen as part of a foreign key definition. The isDeferred
2762 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2763 ** The behavior of the most recently created foreign key is adjusted
2766 void sqlite3DeferForeignKey(Parse
*pParse
, int isDeferred
){
2767 #ifndef SQLITE_OMIT_FOREIGN_KEY
2770 if( (pTab
= pParse
->pNewTable
)==0 || (pFKey
= pTab
->pFKey
)==0 ) return;
2771 assert( isDeferred
==0 || isDeferred
==1 ); /* EV: R-30323-21917 */
2772 pFKey
->isDeferred
= (u8
)isDeferred
;
2777 ** Generate code that will erase and refill index *pIdx. This is
2778 ** used to initialize a newly created index or to recompute the
2779 ** content of an index in response to a REINDEX command.
2781 ** if memRootPage is not negative, it means that the index is newly
2782 ** created. The register specified by memRootPage contains the
2783 ** root page number of the index. If memRootPage is negative, then
2784 ** the index already exists and must be cleared before being refilled and
2785 ** the root page number of the index is taken from pIndex->tnum.
2787 static void sqlite3RefillIndex(Parse
*pParse
, Index
*pIndex
, int memRootPage
){
2788 Table
*pTab
= pIndex
->pTable
; /* The table that is indexed */
2789 int iTab
= pParse
->nTab
++; /* Btree cursor used for pTab */
2790 int iIdx
= pParse
->nTab
++; /* Btree cursor used for pIndex */
2791 int iSorter
; /* Cursor opened by OpenSorter (if in use) */
2792 int addr1
; /* Address of top of loop */
2793 int addr2
; /* Address to jump to for next iteration */
2794 int tnum
; /* Root page of index */
2795 int iPartIdxLabel
; /* Jump to this label to skip a row */
2796 Vdbe
*v
; /* Generate code into this virtual machine */
2797 KeyInfo
*pKey
; /* KeyInfo for index */
2798 int regRecord
; /* Register holding assembled index record */
2799 sqlite3
*db
= pParse
->db
; /* The database connection */
2800 int iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
2802 #ifndef SQLITE_OMIT_AUTHORIZATION
2803 if( sqlite3AuthCheck(pParse
, SQLITE_REINDEX
, pIndex
->zName
, 0,
2804 db
->aDb
[iDb
].zDbSName
) ){
2809 /* Require a write-lock on the table to perform this operation */
2810 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 1, pTab
->zName
);
2812 v
= sqlite3GetVdbe(pParse
);
2814 if( memRootPage
>=0 ){
2817 tnum
= pIndex
->tnum
;
2819 pKey
= sqlite3KeyInfoOfIndex(pParse
, pIndex
);
2820 assert( pKey
!=0 || db
->mallocFailed
|| pParse
->nErr
);
2822 /* Open the sorter cursor if we are to use one. */
2823 iSorter
= pParse
->nTab
++;
2824 sqlite3VdbeAddOp4(v
, OP_SorterOpen
, iSorter
, 0, pIndex
->nKeyCol
, (char*)
2825 sqlite3KeyInfoRef(pKey
), P4_KEYINFO
);
2827 /* Open the table. Loop through all rows of the table, inserting index
2828 ** records into the sorter. */
2829 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
2830 addr1
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, 0); VdbeCoverage(v
);
2831 regRecord
= sqlite3GetTempReg(pParse
);
2833 sqlite3GenerateIndexKey(pParse
,pIndex
,iTab
,regRecord
,0,&iPartIdxLabel
,0,0);
2834 sqlite3VdbeAddOp2(v
, OP_SorterInsert
, iSorter
, regRecord
);
2835 sqlite3ResolvePartIdxLabel(pParse
, iPartIdxLabel
);
2836 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addr1
+1); VdbeCoverage(v
);
2837 sqlite3VdbeJumpHere(v
, addr1
);
2838 if( memRootPage
<0 ) sqlite3VdbeAddOp2(v
, OP_Clear
, tnum
, iDb
);
2839 sqlite3VdbeAddOp4(v
, OP_OpenWrite
, iIdx
, tnum
, iDb
,
2840 (char *)pKey
, P4_KEYINFO
);
2841 sqlite3VdbeChangeP5(v
, OPFLAG_BULKCSR
|((memRootPage
>=0)?OPFLAG_P2ISREG
:0));
2843 addr1
= sqlite3VdbeAddOp2(v
, OP_SorterSort
, iSorter
, 0); VdbeCoverage(v
);
2844 if( IsUniqueIndex(pIndex
) ){
2845 int j2
= sqlite3VdbeCurrentAddr(v
) + 3;
2846 sqlite3VdbeGoto(v
, j2
);
2847 addr2
= sqlite3VdbeCurrentAddr(v
);
2848 sqlite3VdbeAddOp4Int(v
, OP_SorterCompare
, iSorter
, j2
, regRecord
,
2849 pIndex
->nKeyCol
); VdbeCoverage(v
);
2850 sqlite3UniqueConstraint(pParse
, OE_Abort
, pIndex
);
2852 addr2
= sqlite3VdbeCurrentAddr(v
);
2854 sqlite3VdbeAddOp3(v
, OP_SorterData
, iSorter
, regRecord
, iIdx
);
2855 sqlite3VdbeAddOp1(v
, OP_SeekEnd
, iIdx
);
2856 sqlite3VdbeAddOp2(v
, OP_IdxInsert
, iIdx
, regRecord
);
2857 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
2858 sqlite3ReleaseTempReg(pParse
, regRecord
);
2859 sqlite3VdbeAddOp2(v
, OP_SorterNext
, iSorter
, addr2
); VdbeCoverage(v
);
2860 sqlite3VdbeJumpHere(v
, addr1
);
2862 sqlite3VdbeAddOp1(v
, OP_Close
, iTab
);
2863 sqlite3VdbeAddOp1(v
, OP_Close
, iIdx
);
2864 sqlite3VdbeAddOp1(v
, OP_Close
, iSorter
);
2868 ** Allocate heap space to hold an Index object with nCol columns.
2870 ** Increase the allocation size to provide an extra nExtra bytes
2871 ** of 8-byte aligned space after the Index object and return a
2872 ** pointer to this extra space in *ppExtra.
2874 Index
*sqlite3AllocateIndexObject(
2875 sqlite3
*db
, /* Database connection */
2876 i16 nCol
, /* Total number of columns in the index */
2877 int nExtra
, /* Number of bytes of extra space to alloc */
2878 char **ppExtra
/* Pointer to the "extra" space */
2880 Index
*p
; /* Allocated index object */
2881 int nByte
; /* Bytes of space for Index object + arrays */
2883 nByte
= ROUND8(sizeof(Index
)) + /* Index structure */
2884 ROUND8(sizeof(char*)*nCol
) + /* Index.azColl */
2885 ROUND8(sizeof(LogEst
)*(nCol
+1) + /* Index.aiRowLogEst */
2886 sizeof(i16
)*nCol
+ /* Index.aiColumn */
2887 sizeof(u8
)*nCol
); /* Index.aSortOrder */
2888 p
= sqlite3DbMallocZero(db
, nByte
+ nExtra
);
2890 char *pExtra
= ((char*)p
)+ROUND8(sizeof(Index
));
2891 p
->azColl
= (const char**)pExtra
; pExtra
+= ROUND8(sizeof(char*)*nCol
);
2892 p
->aiRowLogEst
= (LogEst
*)pExtra
; pExtra
+= sizeof(LogEst
)*(nCol
+1);
2893 p
->aiColumn
= (i16
*)pExtra
; pExtra
+= sizeof(i16
)*nCol
;
2894 p
->aSortOrder
= (u8
*)pExtra
;
2896 p
->nKeyCol
= nCol
- 1;
2897 *ppExtra
= ((char*)p
) + nByte
;
2903 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2904 ** and pTblList is the name of the table that is to be indexed. Both will
2905 ** be NULL for a primary key or an index that is created to satisfy a
2906 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2907 ** as the table to be indexed. pParse->pNewTable is a table that is
2908 ** currently being constructed by a CREATE TABLE statement.
2910 ** pList is a list of columns to be indexed. pList will be NULL if this
2911 ** is a primary key or unique-constraint on the most recent column added
2912 ** to the table currently under construction.
2914 void sqlite3CreateIndex(
2915 Parse
*pParse
, /* All information about this parse */
2916 Token
*pName1
, /* First part of index name. May be NULL */
2917 Token
*pName2
, /* Second part of index name. May be NULL */
2918 SrcList
*pTblName
, /* Table to index. Use pParse->pNewTable if 0 */
2919 ExprList
*pList
, /* A list of columns to be indexed */
2920 int onError
, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2921 Token
*pStart
, /* The CREATE token that begins this statement */
2922 Expr
*pPIWhere
, /* WHERE clause for partial indices */
2923 int sortOrder
, /* Sort order of primary key when pList==NULL */
2924 int ifNotExist
, /* Omit error if index already exists */
2925 u8 idxType
/* The index type */
2927 Table
*pTab
= 0; /* Table to be indexed */
2928 Index
*pIndex
= 0; /* The index to be created */
2929 char *zName
= 0; /* Name of the index */
2930 int nName
; /* Number of characters in zName */
2932 DbFixer sFix
; /* For assigning database names to pTable */
2933 int sortOrderMask
; /* 1 to honor DESC in index. 0 to ignore. */
2934 sqlite3
*db
= pParse
->db
;
2935 Db
*pDb
; /* The specific table containing the indexed database */
2936 int iDb
; /* Index of the database that is being written */
2937 Token
*pName
= 0; /* Unqualified name of the index to create */
2938 struct ExprList_item
*pListItem
; /* For looping over pList */
2939 int nExtra
= 0; /* Space allocated for zExtra[] */
2940 int nExtraCol
; /* Number of extra columns needed */
2941 char *zExtra
= 0; /* Extra space after the Index object */
2942 Index
*pPk
= 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
2944 if( db
->mallocFailed
|| pParse
->nErr
>0 ){
2945 goto exit_create_index
;
2947 if( IN_DECLARE_VTAB
&& idxType
!=SQLITE_IDXTYPE_PRIMARYKEY
){
2948 goto exit_create_index
;
2950 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
2951 goto exit_create_index
;
2955 ** Find the table that is to be indexed. Return early if not found.
2959 /* Use the two-part index name to determine the database
2960 ** to search for the table. 'Fix' the table name to this db
2961 ** before looking up the table.
2963 assert( pName1
&& pName2
);
2964 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
2965 if( iDb
<0 ) goto exit_create_index
;
2966 assert( pName
&& pName
->z
);
2968 #ifndef SQLITE_OMIT_TEMPDB
2969 /* If the index name was unqualified, check if the table
2970 ** is a temp table. If so, set the database to 1. Do not do this
2971 ** if initialising a database schema.
2973 if( !db
->init
.busy
){
2974 pTab
= sqlite3SrcListLookup(pParse
, pTblName
);
2975 if( pName2
->n
==0 && pTab
&& pTab
->pSchema
==db
->aDb
[1].pSchema
){
2981 sqlite3FixInit(&sFix
, pParse
, iDb
, "index", pName
);
2982 if( sqlite3FixSrcList(&sFix
, pTblName
) ){
2983 /* Because the parser constructs pTblName from a single identifier,
2984 ** sqlite3FixSrcList can never fail. */
2987 pTab
= sqlite3LocateTableItem(pParse
, 0, &pTblName
->a
[0]);
2988 assert( db
->mallocFailed
==0 || pTab
==0 );
2989 if( pTab
==0 ) goto exit_create_index
;
2990 if( iDb
==1 && db
->aDb
[iDb
].pSchema
!=pTab
->pSchema
){
2991 sqlite3ErrorMsg(pParse
,
2992 "cannot create a TEMP index on non-TEMP table \"%s\"",
2994 goto exit_create_index
;
2996 if( !HasRowid(pTab
) ) pPk
= sqlite3PrimaryKeyIndex(pTab
);
2999 assert( pStart
==0 );
3000 pTab
= pParse
->pNewTable
;
3001 if( !pTab
) goto exit_create_index
;
3002 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
3004 pDb
= &db
->aDb
[iDb
];
3007 assert( pParse
->nErr
==0 );
3008 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0
3010 #if SQLITE_USER_AUTHENTICATION
3011 && sqlite3UserAuthTable(pTab
->zName
)==0
3013 && sqlite3StrNICmp(&pTab
->zName
[7],"altertab_",9)!=0 ){
3014 sqlite3ErrorMsg(pParse
, "table %s may not be indexed", pTab
->zName
);
3015 goto exit_create_index
;
3017 #ifndef SQLITE_OMIT_VIEW
3018 if( pTab
->pSelect
){
3019 sqlite3ErrorMsg(pParse
, "views may not be indexed");
3020 goto exit_create_index
;
3023 #ifndef SQLITE_OMIT_VIRTUALTABLE
3024 if( IsVirtual(pTab
) ){
3025 sqlite3ErrorMsg(pParse
, "virtual tables may not be indexed");
3026 goto exit_create_index
;
3031 ** Find the name of the index. Make sure there is not already another
3032 ** index or table with the same name.
3034 ** Exception: If we are reading the names of permanent indices from the
3035 ** sqlite_master table (because some other process changed the schema) and
3036 ** one of the index names collides with the name of a temporary table or
3037 ** index, then we will continue to process this index.
3039 ** If pName==0 it means that we are
3040 ** dealing with a primary key or UNIQUE constraint. We have to invent our
3044 zName
= sqlite3NameFromToken(db
, pName
);
3045 if( zName
==0 ) goto exit_create_index
;
3046 assert( pName
->z
!=0 );
3047 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
) ){
3048 goto exit_create_index
;
3050 if( !db
->init
.busy
){
3051 if( sqlite3FindTable(db
, zName
, 0)!=0 ){
3052 sqlite3ErrorMsg(pParse
, "there is already a table named %s", zName
);
3053 goto exit_create_index
;
3056 if( sqlite3FindIndex(db
, zName
, pDb
->zDbSName
)!=0 ){
3058 sqlite3ErrorMsg(pParse
, "index %s already exists", zName
);
3060 assert( !db
->init
.busy
);
3061 sqlite3CodeVerifySchema(pParse
, iDb
);
3063 goto exit_create_index
;
3068 for(pLoop
=pTab
->pIndex
, n
=1; pLoop
; pLoop
=pLoop
->pNext
, n
++){}
3069 zName
= sqlite3MPrintf(db
, "sqlite_autoindex_%s_%d", pTab
->zName
, n
);
3071 goto exit_create_index
;
3074 /* Automatic index names generated from within sqlite3_declare_vtab()
3075 ** must have names that are distinct from normal automatic index names.
3076 ** The following statement converts "sqlite3_autoindex..." into
3077 ** "sqlite3_butoindex..." in order to make the names distinct.
3078 ** The "vtab_err.test" test demonstrates the need of this statement. */
3079 if( IN_DECLARE_VTAB
) zName
[7]++;
3082 /* Check for authorization to create an index.
3084 #ifndef SQLITE_OMIT_AUTHORIZATION
3086 const char *zDb
= pDb
->zDbSName
;
3087 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(iDb
), 0, zDb
) ){
3088 goto exit_create_index
;
3090 i
= SQLITE_CREATE_INDEX
;
3091 if( !OMIT_TEMPDB
&& iDb
==1 ) i
= SQLITE_CREATE_TEMP_INDEX
;
3092 if( sqlite3AuthCheck(pParse
, i
, zName
, pTab
->zName
, zDb
) ){
3093 goto exit_create_index
;
3098 /* If pList==0, it means this routine was called to make a primary
3099 ** key out of the last column added to the table under construction.
3100 ** So create a fake list to simulate this.
3104 Column
*pCol
= &pTab
->aCol
[pTab
->nCol
-1];
3105 pCol
->colFlags
|= COLFLAG_UNIQUE
;
3106 sqlite3TokenInit(&prevCol
, pCol
->zName
);
3107 pList
= sqlite3ExprListAppend(pParse
, 0,
3108 sqlite3ExprAlloc(db
, TK_ID
, &prevCol
, 0));
3109 if( pList
==0 ) goto exit_create_index
;
3110 assert( pList
->nExpr
==1 );
3111 sqlite3ExprListSetSortOrder(pList
, sortOrder
);
3113 sqlite3ExprListCheckLength(pParse
, pList
, "index");
3116 /* Figure out how many bytes of space are required to store explicitly
3117 ** specified collation sequence names.
3119 for(i
=0; i
<pList
->nExpr
; i
++){
3120 Expr
*pExpr
= pList
->a
[i
].pExpr
;
3122 if( pExpr
->op
==TK_COLLATE
){
3123 nExtra
+= (1 + sqlite3Strlen30(pExpr
->u
.zToken
));
3128 ** Allocate the index structure.
3130 nName
= sqlite3Strlen30(zName
);
3131 nExtraCol
= pPk
? pPk
->nKeyCol
: 1;
3132 pIndex
= sqlite3AllocateIndexObject(db
, pList
->nExpr
+ nExtraCol
,
3133 nName
+ nExtra
+ 1, &zExtra
);
3134 if( db
->mallocFailed
){
3135 goto exit_create_index
;
3137 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->aiRowLogEst
) );
3138 assert( EIGHT_BYTE_ALIGNMENT(pIndex
->azColl
) );
3139 pIndex
->zName
= zExtra
;
3140 zExtra
+= nName
+ 1;
3141 memcpy(pIndex
->zName
, zName
, nName
+1);
3142 pIndex
->pTable
= pTab
;
3143 pIndex
->onError
= (u8
)onError
;
3144 pIndex
->uniqNotNull
= onError
!=OE_None
;
3145 pIndex
->idxType
= idxType
;
3146 pIndex
->pSchema
= db
->aDb
[iDb
].pSchema
;
3147 pIndex
->nKeyCol
= pList
->nExpr
;
3149 sqlite3ResolveSelfReference(pParse
, pTab
, NC_PartIdx
, pPIWhere
, 0);
3150 pIndex
->pPartIdxWhere
= pPIWhere
;
3153 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
3155 /* Check to see if we should honor DESC requests on index columns
3157 if( pDb
->pSchema
->file_format
>=4 ){
3158 sortOrderMask
= -1; /* Honor DESC */
3160 sortOrderMask
= 0; /* Ignore DESC */
3163 /* Analyze the list of expressions that form the terms of the index and
3164 ** report any errors. In the common case where the expression is exactly
3165 ** a table column, store that column in aiColumn[]. For general expressions,
3166 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
3168 ** TODO: Issue a warning if two or more columns of the index are identical.
3169 ** TODO: Issue a warning if the table primary key is used as part of the
3172 for(i
=0, pListItem
=pList
->a
; i
<pList
->nExpr
; i
++, pListItem
++){
3173 Expr
*pCExpr
; /* The i-th index expression */
3174 int requestedSortOrder
; /* ASC or DESC on the i-th expression */
3175 const char *zColl
; /* Collation sequence name */
3177 sqlite3StringToId(pListItem
->pExpr
);
3178 sqlite3ResolveSelfReference(pParse
, pTab
, NC_IdxExpr
, pListItem
->pExpr
, 0);
3179 if( pParse
->nErr
) goto exit_create_index
;
3180 pCExpr
= sqlite3ExprSkipCollate(pListItem
->pExpr
);
3181 if( pCExpr
->op
!=TK_COLUMN
){
3182 if( pTab
==pParse
->pNewTable
){
3183 sqlite3ErrorMsg(pParse
, "expressions prohibited in PRIMARY KEY and "
3184 "UNIQUE constraints");
3185 goto exit_create_index
;
3187 if( pIndex
->aColExpr
==0 ){
3188 ExprList
*pCopy
= sqlite3ExprListDup(db
, pList
, 0);
3189 pIndex
->aColExpr
= pCopy
;
3190 if( !db
->mallocFailed
){
3192 pListItem
= &pCopy
->a
[i
];
3196 pIndex
->aiColumn
[i
] = XN_EXPR
;
3197 pIndex
->uniqNotNull
= 0;
3199 j
= pCExpr
->iColumn
;
3200 assert( j
<=0x7fff );
3203 }else if( pTab
->aCol
[j
].notNull
==0 ){
3204 pIndex
->uniqNotNull
= 0;
3206 pIndex
->aiColumn
[i
] = (i16
)j
;
3209 if( pListItem
->pExpr
->op
==TK_COLLATE
){
3211 zColl
= pListItem
->pExpr
->u
.zToken
;
3212 nColl
= sqlite3Strlen30(zColl
) + 1;
3213 assert( nExtra
>=nColl
);
3214 memcpy(zExtra
, zColl
, nColl
);
3219 zColl
= pTab
->aCol
[j
].zColl
;
3221 if( !zColl
) zColl
= sqlite3StrBINARY
;
3222 if( !db
->init
.busy
&& !sqlite3LocateCollSeq(pParse
, zColl
) ){
3223 goto exit_create_index
;
3225 pIndex
->azColl
[i
] = zColl
;
3226 requestedSortOrder
= pListItem
->sortOrder
& sortOrderMask
;
3227 pIndex
->aSortOrder
[i
] = (u8
)requestedSortOrder
;
3230 /* Append the table key to the end of the index. For WITHOUT ROWID
3231 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
3232 ** normal tables (when pPk==0) this will be the rowid.
3235 for(j
=0; j
<pPk
->nKeyCol
; j
++){
3236 int x
= pPk
->aiColumn
[j
];
3238 if( hasColumn(pIndex
->aiColumn
, pIndex
->nKeyCol
, x
) ){
3241 pIndex
->aiColumn
[i
] = x
;
3242 pIndex
->azColl
[i
] = pPk
->azColl
[j
];
3243 pIndex
->aSortOrder
[i
] = pPk
->aSortOrder
[j
];
3247 assert( i
==pIndex
->nColumn
);
3249 pIndex
->aiColumn
[i
] = XN_ROWID
;
3250 pIndex
->azColl
[i
] = sqlite3StrBINARY
;
3252 sqlite3DefaultRowEst(pIndex
);
3253 if( pParse
->pNewTable
==0 ) estimateIndexWidth(pIndex
);
3255 /* If this index contains every column of its table, then mark
3256 ** it as a covering index */
3257 assert( HasRowid(pTab
)
3258 || pTab
->iPKey
<0 || sqlite3ColumnOfIndex(pIndex
, pTab
->iPKey
)>=0 );
3259 if( pTblName
!=0 && pIndex
->nColumn
>=pTab
->nCol
){
3260 pIndex
->isCovering
= 1;
3261 for(j
=0; j
<pTab
->nCol
; j
++){
3262 if( j
==pTab
->iPKey
) continue;
3263 if( sqlite3ColumnOfIndex(pIndex
,j
)>=0 ) continue;
3264 pIndex
->isCovering
= 0;
3269 if( pTab
==pParse
->pNewTable
){
3270 /* This routine has been called to create an automatic index as a
3271 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3272 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3275 ** CREATE TABLE t(x PRIMARY KEY, y);
3276 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3278 ** Either way, check to see if the table already has such an index. If
3279 ** so, don't bother creating this one. This only applies to
3280 ** automatically created indices. Users can do as they wish with
3281 ** explicit indices.
3283 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3284 ** (and thus suppressing the second one) even if they have different
3287 ** If there are different collating sequences or if the columns of
3288 ** the constraint occur in different orders, then the constraints are
3289 ** considered distinct and both result in separate indices.
3292 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
3294 assert( IsUniqueIndex(pIdx
) );
3295 assert( pIdx
->idxType
!=SQLITE_IDXTYPE_APPDEF
);
3296 assert( IsUniqueIndex(pIndex
) );
3298 if( pIdx
->nKeyCol
!=pIndex
->nKeyCol
) continue;
3299 for(k
=0; k
<pIdx
->nKeyCol
; k
++){
3302 assert( pIdx
->aiColumn
[k
]>=0 );
3303 if( pIdx
->aiColumn
[k
]!=pIndex
->aiColumn
[k
] ) break;
3304 z1
= pIdx
->azColl
[k
];
3305 z2
= pIndex
->azColl
[k
];
3306 if( sqlite3StrICmp(z1
, z2
) ) break;
3308 if( k
==pIdx
->nKeyCol
){
3309 if( pIdx
->onError
!=pIndex
->onError
){
3310 /* This constraint creates the same index as a previous
3311 ** constraint specified somewhere in the CREATE TABLE statement.
3312 ** However the ON CONFLICT clauses are different. If both this
3313 ** constraint and the previous equivalent constraint have explicit
3314 ** ON CONFLICT clauses this is an error. Otherwise, use the
3315 ** explicitly specified behavior for the index.
3317 if( !(pIdx
->onError
==OE_Default
|| pIndex
->onError
==OE_Default
) ){
3318 sqlite3ErrorMsg(pParse
,
3319 "conflicting ON CONFLICT clauses specified", 0);
3321 if( pIdx
->onError
==OE_Default
){
3322 pIdx
->onError
= pIndex
->onError
;
3325 if( idxType
==SQLITE_IDXTYPE_PRIMARYKEY
) pIdx
->idxType
= idxType
;
3326 goto exit_create_index
;
3331 /* Link the new Index structure to its table and to the other
3332 ** in-memory database structures.
3334 assert( pParse
->nErr
==0 );
3335 if( db
->init
.busy
){
3337 assert( !IN_DECLARE_VTAB
);
3338 assert( sqlite3SchemaMutexHeld(db
, 0, pIndex
->pSchema
) );
3339 p
= sqlite3HashInsert(&pIndex
->pSchema
->idxHash
,
3340 pIndex
->zName
, pIndex
);
3342 assert( p
==pIndex
); /* Malloc must have failed */
3343 sqlite3OomFault(db
);
3344 goto exit_create_index
;
3346 db
->mDbFlags
|= DBFLAG_SchemaChange
;
3348 pIndex
->tnum
= db
->init
.newTnum
;
3352 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3353 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3354 ** emit code to allocate the index rootpage on disk and make an entry for
3355 ** the index in the sqlite_master table and populate the index with
3356 ** content. But, do not do this if we are simply reading the sqlite_master
3357 ** table to parse the schema, or if this index is the PRIMARY KEY index
3358 ** of a WITHOUT ROWID table.
3360 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3361 ** or UNIQUE index in a CREATE TABLE statement. Since the table
3362 ** has just been created, it contains no data and the index initialization
3363 ** step can be skipped.
3365 else if( HasRowid(pTab
) || pTblName
!=0 ){
3368 int iMem
= ++pParse
->nMem
;
3370 v
= sqlite3GetVdbe(pParse
);
3371 if( v
==0 ) goto exit_create_index
;
3373 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3375 /* Create the rootpage for the index using CreateIndex. But before
3376 ** doing so, code a Noop instruction and store its address in
3377 ** Index.tnum. This is required in case this index is actually a
3378 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3379 ** that case the convertToWithoutRowidTable() routine will replace
3380 ** the Noop with a Goto to jump over the VDBE code generated below. */
3381 pIndex
->tnum
= sqlite3VdbeAddOp0(v
, OP_Noop
);
3382 sqlite3VdbeAddOp3(v
, OP_CreateBtree
, iDb
, iMem
, BTREE_BLOBKEY
);
3384 /* Gather the complete text of the CREATE INDEX statement into
3385 ** the zStmt variable
3388 int n
= (int)(pParse
->sLastToken
.z
- pName
->z
) + pParse
->sLastToken
.n
;
3389 if( pName
->z
[n
-1]==';' ) n
--;
3390 /* A named index with an explicit CREATE INDEX statement */
3391 zStmt
= sqlite3MPrintf(db
, "CREATE%s INDEX %.*s",
3392 onError
==OE_None
? "" : " UNIQUE", n
, pName
->z
);
3394 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
3395 /* zStmt = sqlite3MPrintf(""); */
3399 /* Add an entry in sqlite_master for this index
3401 sqlite3NestedParse(pParse
,
3402 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
3403 db
->aDb
[iDb
].zDbSName
, MASTER_NAME
,
3409 sqlite3DbFree(db
, zStmt
);
3411 /* Fill the index with data and reparse the schema. Code an OP_Expire
3412 ** to invalidate all pre-compiled statements.
3415 sqlite3RefillIndex(pParse
, pIndex
, iMem
);
3416 sqlite3ChangeCookie(pParse
, iDb
);
3417 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
3418 sqlite3MPrintf(db
, "name='%q' AND type='index'", pIndex
->zName
));
3419 sqlite3VdbeAddOp0(v
, OP_Expire
);
3422 sqlite3VdbeJumpHere(v
, pIndex
->tnum
);
3425 /* When adding an index to the list of indices for a table, make
3426 ** sure all indices labeled OE_Replace come after all those labeled
3427 ** OE_Ignore. This is necessary for the correct constraint check
3428 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3429 ** UPDATE and INSERT statements.
3431 if( db
->init
.busy
|| pTblName
==0 ){
3432 if( onError
!=OE_Replace
|| pTab
->pIndex
==0
3433 || pTab
->pIndex
->onError
==OE_Replace
){
3434 pIndex
->pNext
= pTab
->pIndex
;
3435 pTab
->pIndex
= pIndex
;
3437 Index
*pOther
= pTab
->pIndex
;
3438 while( pOther
->pNext
&& pOther
->pNext
->onError
!=OE_Replace
){
3439 pOther
= pOther
->pNext
;
3441 pIndex
->pNext
= pOther
->pNext
;
3442 pOther
->pNext
= pIndex
;
3447 /* Clean up before exiting */
3449 if( pIndex
) freeIndex(db
, pIndex
);
3450 sqlite3ExprDelete(db
, pPIWhere
);
3451 sqlite3ExprListDelete(db
, pList
);
3452 sqlite3SrcListDelete(db
, pTblName
);
3453 sqlite3DbFree(db
, zName
);
3457 ** Fill the Index.aiRowEst[] array with default information - information
3458 ** to be used when we have not run the ANALYZE command.
3460 ** aiRowEst[0] is supposed to contain the number of elements in the index.
3461 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3462 ** number of rows in the table that match any particular value of the
3463 ** first column of the index. aiRowEst[2] is an estimate of the number
3464 ** of rows that match any particular combination of the first 2 columns
3465 ** of the index. And so forth. It must always be the case that
3467 ** aiRowEst[N]<=aiRowEst[N-1]
3470 ** Apart from that, we have little to go on besides intuition as to
3471 ** how aiRowEst[] should be initialized. The numbers generated here
3472 ** are based on typical values found in actual indices.
3474 void sqlite3DefaultRowEst(Index
*pIdx
){
3475 /* 10, 9, 8, 7, 6 */
3476 LogEst aVal
[] = { 33, 32, 30, 28, 26 };
3477 LogEst
*a
= pIdx
->aiRowLogEst
;
3478 int nCopy
= MIN(ArraySize(aVal
), pIdx
->nKeyCol
);
3481 /* Indexes with default row estimates should not have stat1 data */
3482 assert( !pIdx
->hasStat1
);
3484 /* Set the first entry (number of rows in the index) to the estimated
3485 ** number of rows in the table, or half the number of rows in the table
3486 ** for a partial index. But do not let the estimate drop below 10. */
3487 a
[0] = pIdx
->pTable
->nRowLogEst
;
3488 if( pIdx
->pPartIdxWhere
!=0 ) a
[0] -= 10; assert( 10==sqlite3LogEst(2) );
3489 if( a
[0]<33 ) a
[0] = 33; assert( 33==sqlite3LogEst(10) );
3491 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3492 ** 6 and each subsequent value (if any) is 5. */
3493 memcpy(&a
[1], aVal
, nCopy
*sizeof(LogEst
));
3494 for(i
=nCopy
+1; i
<=pIdx
->nKeyCol
; i
++){
3495 a
[i
] = 23; assert( 23==sqlite3LogEst(5) );
3498 assert( 0==sqlite3LogEst(1) );
3499 if( IsUniqueIndex(pIdx
) ) a
[pIdx
->nKeyCol
] = 0;
3503 ** This routine will drop an existing named index. This routine
3504 ** implements the DROP INDEX statement.
3506 void sqlite3DropIndex(Parse
*pParse
, SrcList
*pName
, int ifExists
){
3509 sqlite3
*db
= pParse
->db
;
3512 assert( pParse
->nErr
==0 ); /* Never called with prior errors */
3513 if( db
->mallocFailed
){
3514 goto exit_drop_index
;
3516 assert( pName
->nSrc
==1 );
3517 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
3518 goto exit_drop_index
;
3520 pIndex
= sqlite3FindIndex(db
, pName
->a
[0].zName
, pName
->a
[0].zDatabase
);
3523 sqlite3ErrorMsg(pParse
, "no such index: %S", pName
, 0);
3525 sqlite3CodeVerifyNamedSchema(pParse
, pName
->a
[0].zDatabase
);
3527 pParse
->checkSchema
= 1;
3528 goto exit_drop_index
;
3530 if( pIndex
->idxType
!=SQLITE_IDXTYPE_APPDEF
){
3531 sqlite3ErrorMsg(pParse
, "index associated with UNIQUE "
3532 "or PRIMARY KEY constraint cannot be dropped", 0);
3533 goto exit_drop_index
;
3535 iDb
= sqlite3SchemaToIndex(db
, pIndex
->pSchema
);
3536 #ifndef SQLITE_OMIT_AUTHORIZATION
3538 int code
= SQLITE_DROP_INDEX
;
3539 Table
*pTab
= pIndex
->pTable
;
3540 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
3541 const char *zTab
= SCHEMA_TABLE(iDb
);
3542 if( sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
) ){
3543 goto exit_drop_index
;
3545 if( !OMIT_TEMPDB
&& iDb
) code
= SQLITE_DROP_TEMP_INDEX
;
3546 if( sqlite3AuthCheck(pParse
, code
, pIndex
->zName
, pTab
->zName
, zDb
) ){
3547 goto exit_drop_index
;
3552 /* Generate code to remove the index and from the master table */
3553 v
= sqlite3GetVdbe(pParse
);
3555 sqlite3BeginWriteOperation(pParse
, 1, iDb
);
3556 sqlite3NestedParse(pParse
,
3557 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3558 db
->aDb
[iDb
].zDbSName
, MASTER_NAME
, pIndex
->zName
3560 sqlite3ClearStatTables(pParse
, iDb
, "idx", pIndex
->zName
);
3561 sqlite3ChangeCookie(pParse
, iDb
);
3562 destroyRootPage(pParse
, pIndex
->tnum
, iDb
);
3563 sqlite3VdbeAddOp4(v
, OP_DropIndex
, iDb
, 0, 0, pIndex
->zName
, 0);
3567 sqlite3SrcListDelete(db
, pName
);
3571 ** pArray is a pointer to an array of objects. Each object in the
3572 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3573 ** to extend the array so that there is space for a new object at the end.
3575 ** When this function is called, *pnEntry contains the current size of
3576 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3579 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3580 ** space allocated for the new object is zeroed, *pnEntry updated to
3581 ** reflect the new size of the array and a pointer to the new allocation
3582 ** returned. *pIdx is set to the index of the new array entry in this case.
3584 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3585 ** unchanged and a copy of pArray returned.
3587 void *sqlite3ArrayAllocate(
3588 sqlite3
*db
, /* Connection to notify of malloc failures */
3589 void *pArray
, /* Array of objects. Might be reallocated */
3590 int szEntry
, /* Size of each object in the array */
3591 int *pnEntry
, /* Number of objects currently in use */
3592 int *pIdx
/* Write the index of a new slot here */
3596 if( (n
& (n
-1))==0 ){
3597 int sz
= (n
==0) ? 1 : 2*n
;
3598 void *pNew
= sqlite3DbRealloc(db
, pArray
, sz
*szEntry
);
3606 memset(&z
[n
* szEntry
], 0, szEntry
);
3613 ** Append a new element to the given IdList. Create a new IdList if
3616 ** A new IdList is returned, or NULL if malloc() fails.
3618 IdList
*sqlite3IdListAppend(sqlite3
*db
, IdList
*pList
, Token
*pToken
){
3621 pList
= sqlite3DbMallocZero(db
, sizeof(IdList
) );
3622 if( pList
==0 ) return 0;
3624 pList
->a
= sqlite3ArrayAllocate(
3627 sizeof(pList
->a
[0]),
3632 sqlite3IdListDelete(db
, pList
);
3635 pList
->a
[i
].zName
= sqlite3NameFromToken(db
, pToken
);
3640 ** Delete an IdList.
3642 void sqlite3IdListDelete(sqlite3
*db
, IdList
*pList
){
3644 if( pList
==0 ) return;
3645 for(i
=0; i
<pList
->nId
; i
++){
3646 sqlite3DbFree(db
, pList
->a
[i
].zName
);
3648 sqlite3DbFree(db
, pList
->a
);
3649 sqlite3DbFreeNN(db
, pList
);
3653 ** Return the index in pList of the identifier named zId. Return -1
3656 int sqlite3IdListIndex(IdList
*pList
, const char *zName
){
3658 if( pList
==0 ) return -1;
3659 for(i
=0; i
<pList
->nId
; i
++){
3660 if( sqlite3StrICmp(pList
->a
[i
].zName
, zName
)==0 ) return i
;
3666 ** Expand the space allocated for the given SrcList object by
3667 ** creating nExtra new slots beginning at iStart. iStart is zero based.
3668 ** New slots are zeroed.
3670 ** For example, suppose a SrcList initially contains two entries: A,B.
3671 ** To append 3 new entries onto the end, do this:
3673 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3675 ** After the call above it would contain: A, B, nil, nil, nil.
3676 ** If the iStart argument had been 1 instead of 2, then the result
3677 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
3678 ** the iStart value would be 0. The result then would
3679 ** be: nil, nil, nil, A, B.
3681 ** If a memory allocation fails the SrcList is unchanged. The
3682 ** db->mallocFailed flag will be set to true.
3684 SrcList
*sqlite3SrcListEnlarge(
3685 sqlite3
*db
, /* Database connection to notify of OOM errors */
3686 SrcList
*pSrc
, /* The SrcList to be enlarged */
3687 int nExtra
, /* Number of new slots to add to pSrc->a[] */
3688 int iStart
/* Index in pSrc->a[] of first new slot */
3692 /* Sanity checking on calling parameters */
3693 assert( iStart
>=0 );
3694 assert( nExtra
>=1 );
3696 assert( iStart
<=pSrc
->nSrc
);
3698 /* Allocate additional space if needed */
3699 if( (u32
)pSrc
->nSrc
+nExtra
>pSrc
->nAlloc
){
3701 int nAlloc
= pSrc
->nSrc
*2+nExtra
;
3703 pNew
= sqlite3DbRealloc(db
, pSrc
,
3704 sizeof(*pSrc
) + (nAlloc
-1)*sizeof(pSrc
->a
[0]) );
3706 assert( db
->mallocFailed
);
3710 nGot
= (sqlite3DbMallocSize(db
, pNew
) - sizeof(*pSrc
))/sizeof(pSrc
->a
[0])+1;
3711 pSrc
->nAlloc
= nGot
;
3714 /* Move existing slots that come after the newly inserted slots
3715 ** out of the way */
3716 for(i
=pSrc
->nSrc
-1; i
>=iStart
; i
--){
3717 pSrc
->a
[i
+nExtra
] = pSrc
->a
[i
];
3719 pSrc
->nSrc
+= nExtra
;
3721 /* Zero the newly allocated slots */
3722 memset(&pSrc
->a
[iStart
], 0, sizeof(pSrc
->a
[0])*nExtra
);
3723 for(i
=iStart
; i
<iStart
+nExtra
; i
++){
3724 pSrc
->a
[i
].iCursor
= -1;
3727 /* Return a pointer to the enlarged SrcList */
3733 ** Append a new table name to the given SrcList. Create a new SrcList if
3734 ** need be. A new entry is created in the SrcList even if pTable is NULL.
3736 ** A SrcList is returned, or NULL if there is an OOM error. The returned
3737 ** SrcList might be the same as the SrcList that was input or it might be
3738 ** a new one. If an OOM error does occurs, then the prior value of pList
3739 ** that is input to this routine is automatically freed.
3741 ** If pDatabase is not null, it means that the table has an optional
3742 ** database name prefix. Like this: "database.table". The pDatabase
3743 ** points to the table name and the pTable points to the database name.
3744 ** The SrcList.a[].zName field is filled with the table name which might
3745 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3746 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3747 ** or with NULL if no database is specified.
3749 ** In other words, if call like this:
3751 ** sqlite3SrcListAppend(D,A,B,0);
3753 ** Then B is a table name and the database name is unspecified. If called
3756 ** sqlite3SrcListAppend(D,A,B,C);
3758 ** Then C is the table name and B is the database name. If C is defined
3759 ** then so is B. In other words, we never have a case where:
3761 ** sqlite3SrcListAppend(D,A,0,C);
3763 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3764 ** before being added to the SrcList.
3766 SrcList
*sqlite3SrcListAppend(
3767 sqlite3
*db
, /* Connection to notify of malloc failures */
3768 SrcList
*pList
, /* Append to this SrcList. NULL creates a new SrcList */
3769 Token
*pTable
, /* Table to append */
3770 Token
*pDatabase
/* Database of the table */
3772 struct SrcList_item
*pItem
;
3773 assert( pDatabase
==0 || pTable
!=0 ); /* Cannot have C without B */
3776 pList
= sqlite3DbMallocRawNN(db
, sizeof(SrcList
) );
3777 if( pList
==0 ) return 0;
3780 memset(&pList
->a
[0], 0, sizeof(pList
->a
[0]));
3781 pList
->a
[0].iCursor
= -1;
3783 pList
= sqlite3SrcListEnlarge(db
, pList
, 1, pList
->nSrc
);
3785 if( db
->mallocFailed
){
3786 sqlite3SrcListDelete(db
, pList
);
3789 pItem
= &pList
->a
[pList
->nSrc
-1];
3790 if( pDatabase
&& pDatabase
->z
==0 ){
3794 pItem
->zName
= sqlite3NameFromToken(db
, pDatabase
);
3795 pItem
->zDatabase
= sqlite3NameFromToken(db
, pTable
);
3797 pItem
->zName
= sqlite3NameFromToken(db
, pTable
);
3798 pItem
->zDatabase
= 0;
3804 ** Assign VdbeCursor index numbers to all tables in a SrcList
3806 void sqlite3SrcListAssignCursors(Parse
*pParse
, SrcList
*pList
){
3808 struct SrcList_item
*pItem
;
3809 assert(pList
|| pParse
->db
->mallocFailed
);
3811 for(i
=0, pItem
=pList
->a
; i
<pList
->nSrc
; i
++, pItem
++){
3812 if( pItem
->iCursor
>=0 ) break;
3813 pItem
->iCursor
= pParse
->nTab
++;
3814 if( pItem
->pSelect
){
3815 sqlite3SrcListAssignCursors(pParse
, pItem
->pSelect
->pSrc
);
3822 ** Delete an entire SrcList including all its substructure.
3824 void sqlite3SrcListDelete(sqlite3
*db
, SrcList
*pList
){
3826 struct SrcList_item
*pItem
;
3827 if( pList
==0 ) return;
3828 for(pItem
=pList
->a
, i
=0; i
<pList
->nSrc
; i
++, pItem
++){
3829 sqlite3DbFree(db
, pItem
->zDatabase
);
3830 sqlite3DbFree(db
, pItem
->zName
);
3831 sqlite3DbFree(db
, pItem
->zAlias
);
3832 if( pItem
->fg
.isIndexedBy
) sqlite3DbFree(db
, pItem
->u1
.zIndexedBy
);
3833 if( pItem
->fg
.isTabFunc
) sqlite3ExprListDelete(db
, pItem
->u1
.pFuncArg
);
3834 sqlite3DeleteTable(db
, pItem
->pTab
);
3835 sqlite3SelectDelete(db
, pItem
->pSelect
);
3836 sqlite3ExprDelete(db
, pItem
->pOn
);
3837 sqlite3IdListDelete(db
, pItem
->pUsing
);
3839 sqlite3DbFreeNN(db
, pList
);
3843 ** This routine is called by the parser to add a new term to the
3844 ** end of a growing FROM clause. The "p" parameter is the part of
3845 ** the FROM clause that has already been constructed. "p" is NULL
3846 ** if this is the first term of the FROM clause. pTable and pDatabase
3847 ** are the name of the table and database named in the FROM clause term.
3848 ** pDatabase is NULL if the database name qualifier is missing - the
3849 ** usual case. If the term has an alias, then pAlias points to the
3850 ** alias token. If the term is a subquery, then pSubquery is the
3851 ** SELECT statement that the subquery encodes. The pTable and
3852 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3853 ** parameters are the content of the ON and USING clauses.
3855 ** Return a new SrcList which encodes is the FROM with the new
3858 SrcList
*sqlite3SrcListAppendFromTerm(
3859 Parse
*pParse
, /* Parsing context */
3860 SrcList
*p
, /* The left part of the FROM clause already seen */
3861 Token
*pTable
, /* Name of the table to add to the FROM clause */
3862 Token
*pDatabase
, /* Name of the database containing pTable */
3863 Token
*pAlias
, /* The right-hand side of the AS subexpression */
3864 Select
*pSubquery
, /* A subquery used in place of a table name */
3865 Expr
*pOn
, /* The ON clause of a join */
3866 IdList
*pUsing
/* The USING clause of a join */
3868 struct SrcList_item
*pItem
;
3869 sqlite3
*db
= pParse
->db
;
3870 if( !p
&& (pOn
|| pUsing
) ){
3871 sqlite3ErrorMsg(pParse
, "a JOIN clause is required before %s",
3872 (pOn
? "ON" : "USING")
3874 goto append_from_error
;
3876 p
= sqlite3SrcListAppend(db
, p
, pTable
, pDatabase
);
3878 goto append_from_error
;
3880 assert( p
->nSrc
>0 );
3881 pItem
= &p
->a
[p
->nSrc
-1];
3882 assert( pAlias
!=0 );
3884 pItem
->zAlias
= sqlite3NameFromToken(db
, pAlias
);
3886 pItem
->pSelect
= pSubquery
;
3888 pItem
->pUsing
= pUsing
;
3893 sqlite3ExprDelete(db
, pOn
);
3894 sqlite3IdListDelete(db
, pUsing
);
3895 sqlite3SelectDelete(db
, pSubquery
);
3900 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3901 ** element of the source-list passed as the second argument.
3903 void sqlite3SrcListIndexedBy(Parse
*pParse
, SrcList
*p
, Token
*pIndexedBy
){
3904 assert( pIndexedBy
!=0 );
3905 if( p
&& pIndexedBy
->n
>0 ){
3906 struct SrcList_item
*pItem
;
3907 assert( p
->nSrc
>0 );
3908 pItem
= &p
->a
[p
->nSrc
-1];
3909 assert( pItem
->fg
.notIndexed
==0 );
3910 assert( pItem
->fg
.isIndexedBy
==0 );
3911 assert( pItem
->fg
.isTabFunc
==0 );
3912 if( pIndexedBy
->n
==1 && !pIndexedBy
->z
){
3913 /* A "NOT INDEXED" clause was supplied. See parse.y
3914 ** construct "indexed_opt" for details. */
3915 pItem
->fg
.notIndexed
= 1;
3917 pItem
->u1
.zIndexedBy
= sqlite3NameFromToken(pParse
->db
, pIndexedBy
);
3918 pItem
->fg
.isIndexedBy
= 1;
3924 ** Add the list of function arguments to the SrcList entry for a
3925 ** table-valued-function.
3927 void sqlite3SrcListFuncArgs(Parse
*pParse
, SrcList
*p
, ExprList
*pList
){
3929 struct SrcList_item
*pItem
= &p
->a
[p
->nSrc
-1];
3930 assert( pItem
->fg
.notIndexed
==0 );
3931 assert( pItem
->fg
.isIndexedBy
==0 );
3932 assert( pItem
->fg
.isTabFunc
==0 );
3933 pItem
->u1
.pFuncArg
= pList
;
3934 pItem
->fg
.isTabFunc
= 1;
3936 sqlite3ExprListDelete(pParse
->db
, pList
);
3941 ** When building up a FROM clause in the parser, the join operator
3942 ** is initially attached to the left operand. But the code generator
3943 ** expects the join operator to be on the right operand. This routine
3944 ** Shifts all join operators from left to right for an entire FROM
3947 ** Example: Suppose the join is like this:
3949 ** A natural cross join B
3951 ** The operator is "natural cross join". The A and B operands are stored
3952 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
3953 ** operator with A. This routine shifts that operator over to B.
3955 void sqlite3SrcListShiftJoinType(SrcList
*p
){
3958 for(i
=p
->nSrc
-1; i
>0; i
--){
3959 p
->a
[i
].fg
.jointype
= p
->a
[i
-1].fg
.jointype
;
3961 p
->a
[0].fg
.jointype
= 0;
3966 ** Generate VDBE code for a BEGIN statement.
3968 void sqlite3BeginTransaction(Parse
*pParse
, int type
){
3973 assert( pParse
!=0 );
3976 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
, "BEGIN", 0, 0) ){
3979 v
= sqlite3GetVdbe(pParse
);
3981 if( type
!=TK_DEFERRED
){
3982 for(i
=0; i
<db
->nDb
; i
++){
3983 sqlite3VdbeAddOp2(v
, OP_Transaction
, i
, (type
==TK_EXCLUSIVE
)+1);
3984 sqlite3VdbeUsesBtree(v
, i
);
3987 sqlite3VdbeAddOp0(v
, OP_AutoCommit
);
3991 ** Generate VDBE code for a COMMIT or ROLLBACK statement.
3992 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
3993 ** code is generated for a COMMIT.
3995 void sqlite3EndTransaction(Parse
*pParse
, int eType
){
3999 assert( pParse
!=0 );
4000 assert( pParse
->db
!=0 );
4001 assert( eType
==TK_COMMIT
|| eType
==TK_END
|| eType
==TK_ROLLBACK
);
4002 isRollback
= eType
==TK_ROLLBACK
;
4003 if( sqlite3AuthCheck(pParse
, SQLITE_TRANSACTION
,
4004 isRollback
? "ROLLBACK" : "COMMIT", 0, 0) ){
4007 v
= sqlite3GetVdbe(pParse
);
4009 sqlite3VdbeAddOp2(v
, OP_AutoCommit
, 1, isRollback
);
4014 ** This function is called by the parser when it parses a command to create,
4015 ** release or rollback an SQL savepoint.
4017 void sqlite3Savepoint(Parse
*pParse
, int op
, Token
*pName
){
4018 char *zName
= sqlite3NameFromToken(pParse
->db
, pName
);
4020 Vdbe
*v
= sqlite3GetVdbe(pParse
);
4021 #ifndef SQLITE_OMIT_AUTHORIZATION
4022 static const char * const az
[] = { "BEGIN", "RELEASE", "ROLLBACK" };
4023 assert( !SAVEPOINT_BEGIN
&& SAVEPOINT_RELEASE
==1 && SAVEPOINT_ROLLBACK
==2 );
4025 if( !v
|| sqlite3AuthCheck(pParse
, SQLITE_SAVEPOINT
, az
[op
], zName
, 0) ){
4026 sqlite3DbFree(pParse
->db
, zName
);
4029 sqlite3VdbeAddOp4(v
, OP_Savepoint
, op
, 0, 0, zName
, P4_DYNAMIC
);
4034 ** Make sure the TEMP database is open and available for use. Return
4035 ** the number of errors. Leave any error messages in the pParse structure.
4037 int sqlite3OpenTempDatabase(Parse
*pParse
){
4038 sqlite3
*db
= pParse
->db
;
4039 if( db
->aDb
[1].pBt
==0 && !pParse
->explain
){
4042 static const int flags
=
4043 SQLITE_OPEN_READWRITE
|
4044 SQLITE_OPEN_CREATE
|
4045 SQLITE_OPEN_EXCLUSIVE
|
4046 SQLITE_OPEN_DELETEONCLOSE
|
4047 SQLITE_OPEN_TEMP_DB
;
4049 rc
= sqlite3BtreeOpen(db
->pVfs
, 0, db
, &pBt
, 0, flags
);
4050 if( rc
!=SQLITE_OK
){
4051 sqlite3ErrorMsg(pParse
, "unable to open a temporary database "
4052 "file for storing temporary tables");
4056 db
->aDb
[1].pBt
= pBt
;
4057 assert( db
->aDb
[1].pSchema
);
4058 if( SQLITE_NOMEM
==sqlite3BtreeSetPageSize(pBt
, db
->nextPagesize
, -1, 0) ){
4059 sqlite3OomFault(db
);
4067 ** Record the fact that the schema cookie will need to be verified
4068 ** for database iDb. The code to actually verify the schema cookie
4069 ** will occur at the end of the top-level VDBE and will be generated
4070 ** later, by sqlite3FinishCoding().
4072 void sqlite3CodeVerifySchema(Parse
*pParse
, int iDb
){
4073 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4075 assert( iDb
>=0 && iDb
<pParse
->db
->nDb
);
4076 assert( pParse
->db
->aDb
[iDb
].pBt
!=0 || iDb
==1 );
4077 assert( iDb
<SQLITE_MAX_ATTACHED
+2 );
4078 assert( sqlite3SchemaMutexHeld(pParse
->db
, iDb
, 0) );
4079 if( DbMaskTest(pToplevel
->cookieMask
, iDb
)==0 ){
4080 DbMaskSet(pToplevel
->cookieMask
, iDb
);
4081 if( !OMIT_TEMPDB
&& iDb
==1 ){
4082 sqlite3OpenTempDatabase(pToplevel
);
4088 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4089 ** attached database. Otherwise, invoke it for the database named zDb only.
4091 void sqlite3CodeVerifyNamedSchema(Parse
*pParse
, const char *zDb
){
4092 sqlite3
*db
= pParse
->db
;
4094 for(i
=0; i
<db
->nDb
; i
++){
4095 Db
*pDb
= &db
->aDb
[i
];
4096 if( pDb
->pBt
&& (!zDb
|| 0==sqlite3StrICmp(zDb
, pDb
->zDbSName
)) ){
4097 sqlite3CodeVerifySchema(pParse
, i
);
4103 ** Generate VDBE code that prepares for doing an operation that
4104 ** might change the database.
4106 ** This routine starts a new transaction if we are not already within
4107 ** a transaction. If we are already within a transaction, then a checkpoint
4108 ** is set if the setStatement parameter is true. A checkpoint should
4109 ** be set for operations that might fail (due to a constraint) part of
4110 ** the way through and which will need to undo some writes without having to
4111 ** rollback the whole transaction. For operations where all constraints
4112 ** can be checked before any changes are made to the database, it is never
4113 ** necessary to undo a write and the checkpoint should not be set.
4115 void sqlite3BeginWriteOperation(Parse
*pParse
, int setStatement
, int iDb
){
4116 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4117 sqlite3CodeVerifySchema(pParse
, iDb
);
4118 DbMaskSet(pToplevel
->writeMask
, iDb
);
4119 pToplevel
->isMultiWrite
|= setStatement
;
4123 ** Indicate that the statement currently under construction might write
4124 ** more than one entry (example: deleting one row then inserting another,
4125 ** inserting multiple rows in a table, or inserting a row and index entries.)
4126 ** If an abort occurs after some of these writes have completed, then it will
4127 ** be necessary to undo the completed writes.
4129 void sqlite3MultiWrite(Parse
*pParse
){
4130 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4131 pToplevel
->isMultiWrite
= 1;
4135 ** The code generator calls this routine if is discovers that it is
4136 ** possible to abort a statement prior to completion. In order to
4137 ** perform this abort without corrupting the database, we need to make
4138 ** sure that the statement is protected by a statement transaction.
4140 ** Technically, we only need to set the mayAbort flag if the
4141 ** isMultiWrite flag was previously set. There is a time dependency
4142 ** such that the abort must occur after the multiwrite. This makes
4143 ** some statements involving the REPLACE conflict resolution algorithm
4144 ** go a little faster. But taking advantage of this time dependency
4145 ** makes it more difficult to prove that the code is correct (in
4146 ** particular, it prevents us from writing an effective
4147 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
4148 ** to take the safe route and skip the optimization.
4150 void sqlite3MayAbort(Parse
*pParse
){
4151 Parse
*pToplevel
= sqlite3ParseToplevel(pParse
);
4152 pToplevel
->mayAbort
= 1;
4156 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4157 ** error. The onError parameter determines which (if any) of the statement
4158 ** and/or current transaction is rolled back.
4160 void sqlite3HaltConstraint(
4161 Parse
*pParse
, /* Parsing context */
4162 int errCode
, /* extended error code */
4163 int onError
, /* Constraint type */
4164 char *p4
, /* Error message */
4165 i8 p4type
, /* P4_STATIC or P4_TRANSIENT */
4166 u8 p5Errmsg
/* P5_ErrMsg type */
4168 Vdbe
*v
= sqlite3GetVdbe(pParse
);
4169 assert( (errCode
&0xff)==SQLITE_CONSTRAINT
);
4170 if( onError
==OE_Abort
){
4171 sqlite3MayAbort(pParse
);
4173 sqlite3VdbeAddOp4(v
, OP_Halt
, errCode
, onError
, 0, p4
, p4type
);
4174 sqlite3VdbeChangeP5(v
, p5Errmsg
);
4178 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4180 void sqlite3UniqueConstraint(
4181 Parse
*pParse
, /* Parsing context */
4182 int onError
, /* Constraint type */
4183 Index
*pIdx
/* The index that triggers the constraint */
4188 Table
*pTab
= pIdx
->pTable
;
4190 sqlite3StrAccumInit(&errMsg
, pParse
->db
, 0, 0, 200);
4191 if( pIdx
->aColExpr
){
4192 sqlite3XPrintf(&errMsg
, "index '%q'", pIdx
->zName
);
4194 for(j
=0; j
<pIdx
->nKeyCol
; j
++){
4196 assert( pIdx
->aiColumn
[j
]>=0 );
4197 zCol
= pTab
->aCol
[pIdx
->aiColumn
[j
]].zName
;
4198 if( j
) sqlite3StrAccumAppend(&errMsg
, ", ", 2);
4199 sqlite3StrAccumAppendAll(&errMsg
, pTab
->zName
);
4200 sqlite3StrAccumAppend(&errMsg
, ".", 1);
4201 sqlite3StrAccumAppendAll(&errMsg
, zCol
);
4204 zErr
= sqlite3StrAccumFinish(&errMsg
);
4205 sqlite3HaltConstraint(pParse
,
4206 IsPrimaryKeyIndex(pIdx
) ? SQLITE_CONSTRAINT_PRIMARYKEY
4207 : SQLITE_CONSTRAINT_UNIQUE
,
4208 onError
, zErr
, P4_DYNAMIC
, P5_ConstraintUnique
);
4213 ** Code an OP_Halt due to non-unique rowid.
4215 void sqlite3RowidConstraint(
4216 Parse
*pParse
, /* Parsing context */
4217 int onError
, /* Conflict resolution algorithm */
4218 Table
*pTab
/* The table with the non-unique rowid */
4222 if( pTab
->iPKey
>=0 ){
4223 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.%s", pTab
->zName
,
4224 pTab
->aCol
[pTab
->iPKey
].zName
);
4225 rc
= SQLITE_CONSTRAINT_PRIMARYKEY
;
4227 zMsg
= sqlite3MPrintf(pParse
->db
, "%s.rowid", pTab
->zName
);
4228 rc
= SQLITE_CONSTRAINT_ROWID
;
4230 sqlite3HaltConstraint(pParse
, rc
, onError
, zMsg
, P4_DYNAMIC
,
4231 P5_ConstraintUnique
);
4235 ** Check to see if pIndex uses the collating sequence pColl. Return
4236 ** true if it does and false if it does not.
4238 #ifndef SQLITE_OMIT_REINDEX
4239 static int collationMatch(const char *zColl
, Index
*pIndex
){
4242 for(i
=0; i
<pIndex
->nColumn
; i
++){
4243 const char *z
= pIndex
->azColl
[i
];
4244 assert( z
!=0 || pIndex
->aiColumn
[i
]<0 );
4245 if( pIndex
->aiColumn
[i
]>=0 && 0==sqlite3StrICmp(z
, zColl
) ){
4254 ** Recompute all indices of pTab that use the collating sequence pColl.
4255 ** If pColl==0 then recompute all indices of pTab.
4257 #ifndef SQLITE_OMIT_REINDEX
4258 static void reindexTable(Parse
*pParse
, Table
*pTab
, char const *zColl
){
4259 Index
*pIndex
; /* An index associated with pTab */
4261 for(pIndex
=pTab
->pIndex
; pIndex
; pIndex
=pIndex
->pNext
){
4262 if( zColl
==0 || collationMatch(zColl
, pIndex
) ){
4263 int iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
4264 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
4265 sqlite3RefillIndex(pParse
, pIndex
, -1);
4272 ** Recompute all indices of all tables in all databases where the
4273 ** indices use the collating sequence pColl. If pColl==0 then recompute
4274 ** all indices everywhere.
4276 #ifndef SQLITE_OMIT_REINDEX
4277 static void reindexDatabases(Parse
*pParse
, char const *zColl
){
4278 Db
*pDb
; /* A single database */
4279 int iDb
; /* The database index number */
4280 sqlite3
*db
= pParse
->db
; /* The database connection */
4281 HashElem
*k
; /* For looping over tables in pDb */
4282 Table
*pTab
; /* A table in the database */
4284 assert( sqlite3BtreeHoldsAllMutexes(db
) ); /* Needed for schema access */
4285 for(iDb
=0, pDb
=db
->aDb
; iDb
<db
->nDb
; iDb
++, pDb
++){
4287 for(k
=sqliteHashFirst(&pDb
->pSchema
->tblHash
); k
; k
=sqliteHashNext(k
)){
4288 pTab
= (Table
*)sqliteHashData(k
);
4289 reindexTable(pParse
, pTab
, zColl
);
4296 ** Generate code for the REINDEX command.
4299 ** REINDEX <collation> -- 2
4300 ** REINDEX ?<database>.?<tablename> -- 3
4301 ** REINDEX ?<database>.?<indexname> -- 4
4303 ** Form 1 causes all indices in all attached databases to be rebuilt.
4304 ** Form 2 rebuilds all indices in all databases that use the named
4305 ** collating function. Forms 3 and 4 rebuild the named index or all
4306 ** indices associated with the named table.
4308 #ifndef SQLITE_OMIT_REINDEX
4309 void sqlite3Reindex(Parse
*pParse
, Token
*pName1
, Token
*pName2
){
4310 CollSeq
*pColl
; /* Collating sequence to be reindexed, or NULL */
4311 char *z
; /* Name of a table or index */
4312 const char *zDb
; /* Name of the database */
4313 Table
*pTab
; /* A table in the database */
4314 Index
*pIndex
; /* An index associated with pTab */
4315 int iDb
; /* The database index number */
4316 sqlite3
*db
= pParse
->db
; /* The database connection */
4317 Token
*pObjName
; /* Name of the table or index to be reindexed */
4319 /* Read the database schema. If an error occurs, leave an error message
4320 ** and code in pParse and return NULL. */
4321 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
4326 reindexDatabases(pParse
, 0);
4328 }else if( NEVER(pName2
==0) || pName2
->z
==0 ){
4330 assert( pName1
->z
);
4331 zColl
= sqlite3NameFromToken(pParse
->db
, pName1
);
4332 if( !zColl
) return;
4333 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
4335 reindexDatabases(pParse
, zColl
);
4336 sqlite3DbFree(db
, zColl
);
4339 sqlite3DbFree(db
, zColl
);
4341 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pObjName
);
4343 z
= sqlite3NameFromToken(db
, pObjName
);
4345 zDb
= db
->aDb
[iDb
].zDbSName
;
4346 pTab
= sqlite3FindTable(db
, z
, zDb
);
4348 reindexTable(pParse
, pTab
, 0);
4349 sqlite3DbFree(db
, z
);
4352 pIndex
= sqlite3FindIndex(db
, z
, zDb
);
4353 sqlite3DbFree(db
, z
);
4355 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
4356 sqlite3RefillIndex(pParse
, pIndex
, -1);
4359 sqlite3ErrorMsg(pParse
, "unable to identify the object to be reindexed");
4364 ** Return a KeyInfo structure that is appropriate for the given Index.
4366 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4367 ** when it has finished using it.
4369 KeyInfo
*sqlite3KeyInfoOfIndex(Parse
*pParse
, Index
*pIdx
){
4371 int nCol
= pIdx
->nColumn
;
4372 int nKey
= pIdx
->nKeyCol
;
4374 if( pParse
->nErr
) return 0;
4375 if( pIdx
->uniqNotNull
){
4376 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nKey
, nCol
-nKey
);
4378 pKey
= sqlite3KeyInfoAlloc(pParse
->db
, nCol
, 0);
4381 assert( sqlite3KeyInfoIsWriteable(pKey
) );
4382 for(i
=0; i
<nCol
; i
++){
4383 const char *zColl
= pIdx
->azColl
[i
];
4384 pKey
->aColl
[i
] = zColl
==sqlite3StrBINARY
? 0 :
4385 sqlite3LocateCollSeq(pParse
, zColl
);
4386 pKey
->aSortOrder
[i
] = pIdx
->aSortOrder
[i
];
4389 assert( pParse
->rc
==SQLITE_ERROR_MISSING_COLLSEQ
);
4390 if( pIdx
->bNoQuery
==0 ){
4391 /* Deactivate the index because it contains an unknown collating
4392 ** sequence. The only way to reactive the index is to reload the
4393 ** schema. Adding the missing collating sequence later does not
4394 ** reactive the index. The application had the chance to register
4395 ** the missing index using the collation-needed callback. For
4396 ** simplicity, SQLite will not give the application a second chance.
4399 pParse
->rc
= SQLITE_ERROR_RETRY
;
4401 sqlite3KeyInfoUnref(pKey
);
4408 #ifndef SQLITE_OMIT_CTE
4410 ** This routine is invoked once per CTE by the parser while parsing a
4413 With
*sqlite3WithAdd(
4414 Parse
*pParse
, /* Parsing context */
4415 With
*pWith
, /* Existing WITH clause, or NULL */
4416 Token
*pName
, /* Name of the common-table */
4417 ExprList
*pArglist
, /* Optional column name list for the table */
4418 Select
*pQuery
/* Query used to initialize the table */
4420 sqlite3
*db
= pParse
->db
;
4424 /* Check that the CTE name is unique within this WITH clause. If
4425 ** not, store an error in the Parse structure. */
4426 zName
= sqlite3NameFromToken(pParse
->db
, pName
);
4427 if( zName
&& pWith
){
4429 for(i
=0; i
<pWith
->nCte
; i
++){
4430 if( sqlite3StrICmp(zName
, pWith
->a
[i
].zName
)==0 ){
4431 sqlite3ErrorMsg(pParse
, "duplicate WITH table name: %s", zName
);
4437 int nByte
= sizeof(*pWith
) + (sizeof(pWith
->a
[1]) * pWith
->nCte
);
4438 pNew
= sqlite3DbRealloc(db
, pWith
, nByte
);
4440 pNew
= sqlite3DbMallocZero(db
, sizeof(*pWith
));
4442 assert( (pNew
!=0 && zName
!=0) || db
->mallocFailed
);
4444 if( db
->mallocFailed
){
4445 sqlite3ExprListDelete(db
, pArglist
);
4446 sqlite3SelectDelete(db
, pQuery
);
4447 sqlite3DbFree(db
, zName
);
4450 pNew
->a
[pNew
->nCte
].pSelect
= pQuery
;
4451 pNew
->a
[pNew
->nCte
].pCols
= pArglist
;
4452 pNew
->a
[pNew
->nCte
].zName
= zName
;
4453 pNew
->a
[pNew
->nCte
].zCteErr
= 0;
4461 ** Free the contents of the With object passed as the second argument.
4463 void sqlite3WithDelete(sqlite3
*db
, With
*pWith
){
4466 for(i
=0; i
<pWith
->nCte
; i
++){
4467 struct Cte
*pCte
= &pWith
->a
[i
];
4468 sqlite3ExprListDelete(db
, pCte
->pCols
);
4469 sqlite3SelectDelete(db
, pCte
->pSelect
);
4470 sqlite3DbFree(db
, pCte
->zName
);
4472 sqlite3DbFree(db
, pWith
);
4475 #endif /* !defined(SQLITE_OMIT_CTE) */