add pragma cipher_default_use_hmac to toggle global HMAC setting
[sqlcipher.git] / src / build.c
blobe23aab6b19115b496999667f6365dae77e95bacb
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains C code routines that are called by the SQLite parser
13 ** when syntax rules are reduced. The routines in this file handle the
14 ** following kinds of SQL syntax:
16 ** CREATE TABLE
17 ** DROP TABLE
18 ** CREATE INDEX
19 ** DROP INDEX
20 ** creating ID lists
21 ** BEGIN TRANSACTION
22 ** COMMIT
23 ** ROLLBACK
25 #include "sqliteInt.h"
28 ** This routine is called when a new SQL statement is beginning to
29 ** be parsed. Initialize the pParse structure as needed.
31 void sqlite3BeginParse(Parse *pParse, int explainFlag){
32 pParse->explain = (u8)explainFlag;
33 pParse->nVar = 0;
36 #ifndef SQLITE_OMIT_SHARED_CACHE
38 ** The TableLock structure is only used by the sqlite3TableLock() and
39 ** codeTableLocks() functions.
41 struct TableLock {
42 int iDb; /* The database containing the table to be locked */
43 int iTab; /* The root page of the table to be locked */
44 u8 isWriteLock; /* True for write lock. False for a read lock */
45 const char *zName; /* Name of the table */
49 ** Record the fact that we want to lock a table at run-time.
51 ** The table to be locked has root page iTab and is found in database iDb.
52 ** A read or a write lock can be taken depending on isWritelock.
54 ** This routine just records the fact that the lock is desired. The
55 ** code to make the lock occur is generated by a later call to
56 ** codeTableLocks() which occurs during sqlite3FinishCoding().
58 void sqlite3TableLock(
59 Parse *pParse, /* Parsing context */
60 int iDb, /* Index of the database containing the table to lock */
61 int iTab, /* Root page number of the table to be locked */
62 u8 isWriteLock, /* True for a write lock */
63 const char *zName /* Name of the table to be locked */
65 Parse *pToplevel = sqlite3ParseToplevel(pParse);
66 int i;
67 int nBytes;
68 TableLock *p;
69 assert( iDb>=0 );
71 for(i=0; i<pToplevel->nTableLock; i++){
72 p = &pToplevel->aTableLock[i];
73 if( p->iDb==iDb && p->iTab==iTab ){
74 p->isWriteLock = (p->isWriteLock || isWriteLock);
75 return;
79 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80 pToplevel->aTableLock =
81 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82 if( pToplevel->aTableLock ){
83 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
84 p->iDb = iDb;
85 p->iTab = iTab;
86 p->isWriteLock = isWriteLock;
87 p->zName = zName;
88 }else{
89 pToplevel->nTableLock = 0;
90 pToplevel->db->mallocFailed = 1;
95 ** Code an OP_TableLock instruction for each table locked by the
96 ** statement (configured by calls to sqlite3TableLock()).
98 static void codeTableLocks(Parse *pParse){
99 int i;
100 Vdbe *pVdbe;
102 pVdbe = sqlite3GetVdbe(pParse);
103 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
105 for(i=0; i<pParse->nTableLock; i++){
106 TableLock *p = &pParse->aTableLock[i];
107 int p1 = p->iDb;
108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
109 p->zName, P4_STATIC);
112 #else
113 #define codeTableLocks(x)
114 #endif
117 ** This routine is called after a single SQL statement has been
118 ** parsed and a VDBE program to execute that statement has been
119 ** prepared. This routine puts the finishing touches on the
120 ** VDBE program and resets the pParse structure for the next
121 ** parse.
123 ** Note that if an error occurred, it might be the case that
124 ** no VDBE code was generated.
126 void sqlite3FinishCoding(Parse *pParse){
127 sqlite3 *db;
128 Vdbe *v;
130 db = pParse->db;
131 if( db->mallocFailed ) return;
132 if( pParse->nested ) return;
133 if( pParse->nErr ) return;
135 /* Begin by generating some termination code at the end of the
136 ** vdbe program
138 v = sqlite3GetVdbe(pParse);
139 assert( !pParse->isMultiWrite
140 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
141 if( v ){
142 sqlite3VdbeAddOp0(v, OP_Halt);
144 /* The cookie mask contains one bit for each database file open.
145 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
146 ** set for each database that is used. Generate code to start a
147 ** transaction on each used database and to verify the schema cookie
148 ** on each used database.
150 if( pParse->cookieGoto>0 ){
151 yDbMask mask;
152 int iDb;
153 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
154 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
155 if( (mask & pParse->cookieMask)==0 ) continue;
156 sqlite3VdbeUsesBtree(v, iDb);
157 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
158 if( db->init.busy==0 ){
159 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
160 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
161 iDb, pParse->cookieValue[iDb],
162 db->aDb[iDb].pSchema->iGeneration);
165 #ifndef SQLITE_OMIT_VIRTUALTABLE
167 int i;
168 for(i=0; i<pParse->nVtabLock; i++){
169 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
170 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
172 pParse->nVtabLock = 0;
174 #endif
176 /* Once all the cookies have been verified and transactions opened,
177 ** obtain the required table-locks. This is a no-op unless the
178 ** shared-cache feature is enabled.
180 codeTableLocks(pParse);
182 /* Initialize any AUTOINCREMENT data structures required.
184 sqlite3AutoincrementBegin(pParse);
186 /* Finally, jump back to the beginning of the executable code. */
187 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
192 /* Get the VDBE program ready for execution
194 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
195 #ifdef SQLITE_DEBUG
196 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
197 sqlite3VdbeTrace(v, trace);
198 #endif
199 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
200 /* A minimum of one cursor is required if autoincrement is used
201 * See ticket [a696379c1f08866] */
202 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
203 sqlite3VdbeMakeReady(v, pParse);
204 pParse->rc = SQLITE_DONE;
205 pParse->colNamesSet = 0;
206 }else{
207 pParse->rc = SQLITE_ERROR;
209 pParse->nTab = 0;
210 pParse->nMem = 0;
211 pParse->nSet = 0;
212 pParse->nVar = 0;
213 pParse->cookieMask = 0;
214 pParse->cookieGoto = 0;
218 ** Run the parser and code generator recursively in order to generate
219 ** code for the SQL statement given onto the end of the pParse context
220 ** currently under construction. When the parser is run recursively
221 ** this way, the final OP_Halt is not appended and other initialization
222 ** and finalization steps are omitted because those are handling by the
223 ** outermost parser.
225 ** Not everything is nestable. This facility is designed to permit
226 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
227 ** care if you decide to try to use this routine for some other purposes.
229 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
230 va_list ap;
231 char *zSql;
232 char *zErrMsg = 0;
233 sqlite3 *db = pParse->db;
234 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
235 char saveBuf[SAVE_SZ];
237 if( pParse->nErr ) return;
238 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
239 va_start(ap, zFormat);
240 zSql = sqlite3VMPrintf(db, zFormat, ap);
241 va_end(ap);
242 if( zSql==0 ){
243 return; /* A malloc must have failed */
245 pParse->nested++;
246 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
247 memset(&pParse->nVar, 0, SAVE_SZ);
248 sqlite3RunParser(pParse, zSql, &zErrMsg);
249 sqlite3DbFree(db, zErrMsg);
250 sqlite3DbFree(db, zSql);
251 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
252 pParse->nested--;
256 ** Locate the in-memory structure that describes a particular database
257 ** table given the name of that table and (optionally) the name of the
258 ** database containing the table. Return NULL if not found.
260 ** If zDatabase is 0, all databases are searched for the table and the
261 ** first matching table is returned. (No checking for duplicate table
262 ** names is done.) The search order is TEMP first, then MAIN, then any
263 ** auxiliary databases added using the ATTACH command.
265 ** See also sqlite3LocateTable().
267 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
268 Table *p = 0;
269 int i;
270 int nName;
271 assert( zName!=0 );
272 nName = sqlite3Strlen30(zName);
273 /* All mutexes are required for schema access. Make sure we hold them. */
274 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
275 for(i=OMIT_TEMPDB; i<db->nDb; i++){
276 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
277 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
278 assert( sqlite3SchemaMutexHeld(db, j, 0) );
279 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
280 if( p ) break;
282 return p;
286 ** Locate the in-memory structure that describes a particular database
287 ** table given the name of that table and (optionally) the name of the
288 ** database containing the table. Return NULL if not found. Also leave an
289 ** error message in pParse->zErrMsg.
291 ** The difference between this routine and sqlite3FindTable() is that this
292 ** routine leaves an error message in pParse->zErrMsg where
293 ** sqlite3FindTable() does not.
295 Table *sqlite3LocateTable(
296 Parse *pParse, /* context in which to report errors */
297 int isView, /* True if looking for a VIEW rather than a TABLE */
298 const char *zName, /* Name of the table we are looking for */
299 const char *zDbase /* Name of the database. Might be NULL */
301 Table *p;
303 /* Read the database schema. If an error occurs, leave an error message
304 ** and code in pParse and return NULL. */
305 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
306 return 0;
309 p = sqlite3FindTable(pParse->db, zName, zDbase);
310 if( p==0 ){
311 const char *zMsg = isView ? "no such view" : "no such table";
312 if( zDbase ){
313 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
314 }else{
315 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
317 pParse->checkSchema = 1;
319 return p;
323 ** Locate the in-memory structure that describes
324 ** a particular index given the name of that index
325 ** and the name of the database that contains the index.
326 ** Return NULL if not found.
328 ** If zDatabase is 0, all databases are searched for the
329 ** table and the first matching index is returned. (No checking
330 ** for duplicate index names is done.) The search order is
331 ** TEMP first, then MAIN, then any auxiliary databases added
332 ** using the ATTACH command.
334 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
335 Index *p = 0;
336 int i;
337 int nName = sqlite3Strlen30(zName);
338 /* All mutexes are required for schema access. Make sure we hold them. */
339 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
340 for(i=OMIT_TEMPDB; i<db->nDb; i++){
341 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
342 Schema *pSchema = db->aDb[j].pSchema;
343 assert( pSchema );
344 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
345 assert( sqlite3SchemaMutexHeld(db, j, 0) );
346 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
347 if( p ) break;
349 return p;
353 ** Reclaim the memory used by an index
355 static void freeIndex(sqlite3 *db, Index *p){
356 #ifndef SQLITE_OMIT_ANALYZE
357 sqlite3DeleteIndexSamples(db, p);
358 #endif
359 sqlite3DbFree(db, p->zColAff);
360 sqlite3DbFree(db, p);
364 ** For the index called zIdxName which is found in the database iDb,
365 ** unlike that index from its Table then remove the index from
366 ** the index hash table and free all memory structures associated
367 ** with the index.
369 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
370 Index *pIndex;
371 int len;
372 Hash *pHash;
374 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
375 pHash = &db->aDb[iDb].pSchema->idxHash;
376 len = sqlite3Strlen30(zIdxName);
377 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
378 if( ALWAYS(pIndex) ){
379 if( pIndex->pTable->pIndex==pIndex ){
380 pIndex->pTable->pIndex = pIndex->pNext;
381 }else{
382 Index *p;
383 /* Justification of ALWAYS(); The index must be on the list of
384 ** indices. */
385 p = pIndex->pTable->pIndex;
386 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
387 if( ALWAYS(p && p->pNext==pIndex) ){
388 p->pNext = pIndex->pNext;
391 freeIndex(db, pIndex);
393 db->flags |= SQLITE_InternChanges;
397 ** Erase all schema information from the in-memory hash tables of
398 ** a single database. This routine is called to reclaim memory
399 ** before the database closes. It is also called during a rollback
400 ** if there were schema changes during the transaction or if a
401 ** schema-cookie mismatch occurs.
403 ** If iDb<0 then reset the internal schema tables for all database
404 ** files. If iDb>=0 then reset the internal schema for only the
405 ** single file indicated.
407 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
408 int i, j;
409 assert( iDb<db->nDb );
411 if( iDb>=0 ){
412 /* Case 1: Reset the single schema identified by iDb */
413 Db *pDb = &db->aDb[iDb];
414 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
415 assert( pDb->pSchema!=0 );
416 sqlite3SchemaClear(pDb->pSchema);
418 /* If any database other than TEMP is reset, then also reset TEMP
419 ** since TEMP might be holding triggers that reference tables in the
420 ** other database.
422 if( iDb!=1 ){
423 pDb = &db->aDb[1];
424 assert( pDb->pSchema!=0 );
425 sqlite3SchemaClear(pDb->pSchema);
427 return;
429 /* Case 2 (from here to the end): Reset all schemas for all attached
430 ** databases. */
431 assert( iDb<0 );
432 sqlite3BtreeEnterAll(db);
433 for(i=0; i<db->nDb; i++){
434 Db *pDb = &db->aDb[i];
435 if( pDb->pSchema ){
436 sqlite3SchemaClear(pDb->pSchema);
439 db->flags &= ~SQLITE_InternChanges;
440 sqlite3VtabUnlockList(db);
441 sqlite3BtreeLeaveAll(db);
443 /* If one or more of the auxiliary database files has been closed,
444 ** then remove them from the auxiliary database list. We take the
445 ** opportunity to do this here since we have just deleted all of the
446 ** schema hash tables and therefore do not have to make any changes
447 ** to any of those tables.
449 for(i=j=2; i<db->nDb; i++){
450 struct Db *pDb = &db->aDb[i];
451 if( pDb->pBt==0 ){
452 sqlite3DbFree(db, pDb->zName);
453 pDb->zName = 0;
454 continue;
456 if( j<i ){
457 db->aDb[j] = db->aDb[i];
459 j++;
461 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
462 db->nDb = j;
463 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
464 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
465 sqlite3DbFree(db, db->aDb);
466 db->aDb = db->aDbStatic;
471 ** This routine is called when a commit occurs.
473 void sqlite3CommitInternalChanges(sqlite3 *db){
474 db->flags &= ~SQLITE_InternChanges;
478 ** Delete memory allocated for the column names of a table or view (the
479 ** Table.aCol[] array).
481 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
482 int i;
483 Column *pCol;
484 assert( pTable!=0 );
485 if( (pCol = pTable->aCol)!=0 ){
486 for(i=0; i<pTable->nCol; i++, pCol++){
487 sqlite3DbFree(db, pCol->zName);
488 sqlite3ExprDelete(db, pCol->pDflt);
489 sqlite3DbFree(db, pCol->zDflt);
490 sqlite3DbFree(db, pCol->zType);
491 sqlite3DbFree(db, pCol->zColl);
493 sqlite3DbFree(db, pTable->aCol);
498 ** Remove the memory data structures associated with the given
499 ** Table. No changes are made to disk by this routine.
501 ** This routine just deletes the data structure. It does not unlink
502 ** the table data structure from the hash table. But it does destroy
503 ** memory structures of the indices and foreign keys associated with
504 ** the table.
506 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
507 Index *pIndex, *pNext;
509 assert( !pTable || pTable->nRef>0 );
511 /* Do not delete the table until the reference count reaches zero. */
512 if( !pTable ) return;
513 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
515 /* Delete all indices associated with this table. */
516 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
517 pNext = pIndex->pNext;
518 assert( pIndex->pSchema==pTable->pSchema );
519 if( !db || db->pnBytesFreed==0 ){
520 char *zName = pIndex->zName;
521 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
522 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
524 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
525 assert( pOld==pIndex || pOld==0 );
527 freeIndex(db, pIndex);
530 /* Delete any foreign keys attached to this table. */
531 sqlite3FkDelete(db, pTable);
533 /* Delete the Table structure itself.
535 sqliteDeleteColumnNames(db, pTable);
536 sqlite3DbFree(db, pTable->zName);
537 sqlite3DbFree(db, pTable->zColAff);
538 sqlite3SelectDelete(db, pTable->pSelect);
539 #ifndef SQLITE_OMIT_CHECK
540 sqlite3ExprDelete(db, pTable->pCheck);
541 #endif
542 #ifndef SQLITE_OMIT_VIRTUALTABLE
543 sqlite3VtabClear(db, pTable);
544 #endif
545 sqlite3DbFree(db, pTable);
549 ** Unlink the given table from the hash tables and the delete the
550 ** table structure with all its indices and foreign keys.
552 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
553 Table *p;
554 Db *pDb;
556 assert( db!=0 );
557 assert( iDb>=0 && iDb<db->nDb );
558 assert( zTabName );
559 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
560 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
561 pDb = &db->aDb[iDb];
562 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
563 sqlite3Strlen30(zTabName),0);
564 sqlite3DeleteTable(db, p);
565 db->flags |= SQLITE_InternChanges;
569 ** Given a token, return a string that consists of the text of that
570 ** token. Space to hold the returned string
571 ** is obtained from sqliteMalloc() and must be freed by the calling
572 ** function.
574 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
575 ** surround the body of the token are removed.
577 ** Tokens are often just pointers into the original SQL text and so
578 ** are not \000 terminated and are not persistent. The returned string
579 ** is \000 terminated and is persistent.
581 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
582 char *zName;
583 if( pName ){
584 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
585 sqlite3Dequote(zName);
586 }else{
587 zName = 0;
589 return zName;
593 ** Open the sqlite_master table stored in database number iDb for
594 ** writing. The table is opened using cursor 0.
596 void sqlite3OpenMasterTable(Parse *p, int iDb){
597 Vdbe *v = sqlite3GetVdbe(p);
598 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
599 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
600 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
601 if( p->nTab==0 ){
602 p->nTab = 1;
607 ** Parameter zName points to a nul-terminated buffer containing the name
608 ** of a database ("main", "temp" or the name of an attached db). This
609 ** function returns the index of the named database in db->aDb[], or
610 ** -1 if the named db cannot be found.
612 int sqlite3FindDbName(sqlite3 *db, const char *zName){
613 int i = -1; /* Database number */
614 if( zName ){
615 Db *pDb;
616 int n = sqlite3Strlen30(zName);
617 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
618 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
619 0==sqlite3StrICmp(pDb->zName, zName) ){
620 break;
624 return i;
628 ** The token *pName contains the name of a database (either "main" or
629 ** "temp" or the name of an attached db). This routine returns the
630 ** index of the named database in db->aDb[], or -1 if the named db
631 ** does not exist.
633 int sqlite3FindDb(sqlite3 *db, Token *pName){
634 int i; /* Database number */
635 char *zName; /* Name we are searching for */
636 zName = sqlite3NameFromToken(db, pName);
637 i = sqlite3FindDbName(db, zName);
638 sqlite3DbFree(db, zName);
639 return i;
642 /* The table or view or trigger name is passed to this routine via tokens
643 ** pName1 and pName2. If the table name was fully qualified, for example:
645 ** CREATE TABLE xxx.yyy (...);
647 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
648 ** the table name is not fully qualified, i.e.:
650 ** CREATE TABLE yyy(...);
652 ** Then pName1 is set to "yyy" and pName2 is "".
654 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
655 ** pName2) that stores the unqualified table name. The index of the
656 ** database "xxx" is returned.
658 int sqlite3TwoPartName(
659 Parse *pParse, /* Parsing and code generating context */
660 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
661 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
662 Token **pUnqual /* Write the unqualified object name here */
664 int iDb; /* Database holding the object */
665 sqlite3 *db = pParse->db;
667 if( ALWAYS(pName2!=0) && pName2->n>0 ){
668 if( db->init.busy ) {
669 sqlite3ErrorMsg(pParse, "corrupt database");
670 pParse->nErr++;
671 return -1;
673 *pUnqual = pName2;
674 iDb = sqlite3FindDb(db, pName1);
675 if( iDb<0 ){
676 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
677 pParse->nErr++;
678 return -1;
680 }else{
681 assert( db->init.iDb==0 || db->init.busy );
682 iDb = db->init.iDb;
683 *pUnqual = pName1;
685 return iDb;
689 ** This routine is used to check if the UTF-8 string zName is a legal
690 ** unqualified name for a new schema object (table, index, view or
691 ** trigger). All names are legal except those that begin with the string
692 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
693 ** is reserved for internal use.
695 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
696 if( !pParse->db->init.busy && pParse->nested==0
697 && (pParse->db->flags & SQLITE_WriteSchema)==0
698 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
699 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
700 return SQLITE_ERROR;
702 return SQLITE_OK;
706 ** Begin constructing a new table representation in memory. This is
707 ** the first of several action routines that get called in response
708 ** to a CREATE TABLE statement. In particular, this routine is called
709 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
710 ** flag is true if the table should be stored in the auxiliary database
711 ** file instead of in the main database file. This is normally the case
712 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
713 ** CREATE and TABLE.
715 ** The new table record is initialized and put in pParse->pNewTable.
716 ** As more of the CREATE TABLE statement is parsed, additional action
717 ** routines will be called to add more information to this record.
718 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
719 ** is called to complete the construction of the new table record.
721 void sqlite3StartTable(
722 Parse *pParse, /* Parser context */
723 Token *pName1, /* First part of the name of the table or view */
724 Token *pName2, /* Second part of the name of the table or view */
725 int isTemp, /* True if this is a TEMP table */
726 int isView, /* True if this is a VIEW */
727 int isVirtual, /* True if this is a VIRTUAL table */
728 int noErr /* Do nothing if table already exists */
730 Table *pTable;
731 char *zName = 0; /* The name of the new table */
732 sqlite3 *db = pParse->db;
733 Vdbe *v;
734 int iDb; /* Database number to create the table in */
735 Token *pName; /* Unqualified name of the table to create */
737 /* The table or view name to create is passed to this routine via tokens
738 ** pName1 and pName2. If the table name was fully qualified, for example:
740 ** CREATE TABLE xxx.yyy (...);
742 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
743 ** the table name is not fully qualified, i.e.:
745 ** CREATE TABLE yyy(...);
747 ** Then pName1 is set to "yyy" and pName2 is "".
749 ** The call below sets the pName pointer to point at the token (pName1 or
750 ** pName2) that stores the unqualified table name. The variable iDb is
751 ** set to the index of the database that the table or view is to be
752 ** created in.
754 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
755 if( iDb<0 ) return;
756 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
757 /* If creating a temp table, the name may not be qualified. Unless
758 ** the database name is "temp" anyway. */
759 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
760 return;
762 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
764 pParse->sNameToken = *pName;
765 zName = sqlite3NameFromToken(db, pName);
766 if( zName==0 ) return;
767 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
768 goto begin_table_error;
770 if( db->init.iDb==1 ) isTemp = 1;
771 #ifndef SQLITE_OMIT_AUTHORIZATION
772 assert( (isTemp & 1)==isTemp );
774 int code;
775 char *zDb = db->aDb[iDb].zName;
776 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
777 goto begin_table_error;
779 if( isView ){
780 if( !OMIT_TEMPDB && isTemp ){
781 code = SQLITE_CREATE_TEMP_VIEW;
782 }else{
783 code = SQLITE_CREATE_VIEW;
785 }else{
786 if( !OMIT_TEMPDB && isTemp ){
787 code = SQLITE_CREATE_TEMP_TABLE;
788 }else{
789 code = SQLITE_CREATE_TABLE;
792 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
793 goto begin_table_error;
796 #endif
798 /* Make sure the new table name does not collide with an existing
799 ** index or table name in the same database. Issue an error message if
800 ** it does. The exception is if the statement being parsed was passed
801 ** to an sqlite3_declare_vtab() call. In that case only the column names
802 ** and types will be used, so there is no need to test for namespace
803 ** collisions.
805 if( !IN_DECLARE_VTAB ){
806 char *zDb = db->aDb[iDb].zName;
807 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
808 goto begin_table_error;
810 pTable = sqlite3FindTable(db, zName, zDb);
811 if( pTable ){
812 if( !noErr ){
813 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
814 }else{
815 assert( !db->init.busy );
816 sqlite3CodeVerifySchema(pParse, iDb);
818 goto begin_table_error;
820 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
821 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
822 goto begin_table_error;
826 pTable = sqlite3DbMallocZero(db, sizeof(Table));
827 if( pTable==0 ){
828 db->mallocFailed = 1;
829 pParse->rc = SQLITE_NOMEM;
830 pParse->nErr++;
831 goto begin_table_error;
833 pTable->zName = zName;
834 pTable->iPKey = -1;
835 pTable->pSchema = db->aDb[iDb].pSchema;
836 pTable->nRef = 1;
837 pTable->nRowEst = 1000000;
838 assert( pParse->pNewTable==0 );
839 pParse->pNewTable = pTable;
841 /* If this is the magic sqlite_sequence table used by autoincrement,
842 ** then record a pointer to this table in the main database structure
843 ** so that INSERT can find the table easily.
845 #ifndef SQLITE_OMIT_AUTOINCREMENT
846 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
847 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
848 pTable->pSchema->pSeqTab = pTable;
850 #endif
852 /* Begin generating the code that will insert the table record into
853 ** the SQLITE_MASTER table. Note in particular that we must go ahead
854 ** and allocate the record number for the table entry now. Before any
855 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
856 ** indices to be created and the table record must come before the
857 ** indices. Hence, the record number for the table must be allocated
858 ** now.
860 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
861 int j1;
862 int fileFormat;
863 int reg1, reg2, reg3;
864 sqlite3BeginWriteOperation(pParse, 0, iDb);
866 #ifndef SQLITE_OMIT_VIRTUALTABLE
867 if( isVirtual ){
868 sqlite3VdbeAddOp0(v, OP_VBegin);
870 #endif
872 /* If the file format and encoding in the database have not been set,
873 ** set them now.
875 reg1 = pParse->regRowid = ++pParse->nMem;
876 reg2 = pParse->regRoot = ++pParse->nMem;
877 reg3 = ++pParse->nMem;
878 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
879 sqlite3VdbeUsesBtree(v, iDb);
880 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
881 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
882 1 : SQLITE_MAX_FILE_FORMAT;
883 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
884 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
885 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
886 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
887 sqlite3VdbeJumpHere(v, j1);
889 /* This just creates a place-holder record in the sqlite_master table.
890 ** The record created does not contain anything yet. It will be replaced
891 ** by the real entry in code generated at sqlite3EndTable().
893 ** The rowid for the new entry is left in register pParse->regRowid.
894 ** The root page number of the new table is left in reg pParse->regRoot.
895 ** The rowid and root page number values are needed by the code that
896 ** sqlite3EndTable will generate.
898 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
899 if( isView || isVirtual ){
900 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
901 }else
902 #endif
904 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
906 sqlite3OpenMasterTable(pParse, iDb);
907 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
908 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
909 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
910 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
911 sqlite3VdbeAddOp0(v, OP_Close);
914 /* Normal (non-error) return. */
915 return;
917 /* If an error occurs, we jump here */
918 begin_table_error:
919 sqlite3DbFree(db, zName);
920 return;
924 ** This macro is used to compare two strings in a case-insensitive manner.
925 ** It is slightly faster than calling sqlite3StrICmp() directly, but
926 ** produces larger code.
928 ** WARNING: This macro is not compatible with the strcmp() family. It
929 ** returns true if the two strings are equal, otherwise false.
931 #define STRICMP(x, y) (\
932 sqlite3UpperToLower[*(unsigned char *)(x)]== \
933 sqlite3UpperToLower[*(unsigned char *)(y)] \
934 && sqlite3StrICmp((x)+1,(y)+1)==0 )
937 ** Add a new column to the table currently being constructed.
939 ** The parser calls this routine once for each column declaration
940 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
941 ** first to get things going. Then this routine is called for each
942 ** column.
944 void sqlite3AddColumn(Parse *pParse, Token *pName){
945 Table *p;
946 int i;
947 char *z;
948 Column *pCol;
949 sqlite3 *db = pParse->db;
950 if( (p = pParse->pNewTable)==0 ) return;
951 #if SQLITE_MAX_COLUMN
952 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
953 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
954 return;
956 #endif
957 z = sqlite3NameFromToken(db, pName);
958 if( z==0 ) return;
959 for(i=0; i<p->nCol; i++){
960 if( STRICMP(z, p->aCol[i].zName) ){
961 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
962 sqlite3DbFree(db, z);
963 return;
966 if( (p->nCol & 0x7)==0 ){
967 Column *aNew;
968 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
969 if( aNew==0 ){
970 sqlite3DbFree(db, z);
971 return;
973 p->aCol = aNew;
975 pCol = &p->aCol[p->nCol];
976 memset(pCol, 0, sizeof(p->aCol[0]));
977 pCol->zName = z;
979 /* If there is no type specified, columns have the default affinity
980 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
981 ** be called next to set pCol->affinity correctly.
983 pCol->affinity = SQLITE_AFF_NONE;
984 p->nCol++;
988 ** This routine is called by the parser while in the middle of
989 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
990 ** been seen on a column. This routine sets the notNull flag on
991 ** the column currently under construction.
993 void sqlite3AddNotNull(Parse *pParse, int onError){
994 Table *p;
995 p = pParse->pNewTable;
996 if( p==0 || NEVER(p->nCol<1) ) return;
997 p->aCol[p->nCol-1].notNull = (u8)onError;
1001 ** Scan the column type name zType (length nType) and return the
1002 ** associated affinity type.
1004 ** This routine does a case-independent search of zType for the
1005 ** substrings in the following table. If one of the substrings is
1006 ** found, the corresponding affinity is returned. If zType contains
1007 ** more than one of the substrings, entries toward the top of
1008 ** the table take priority. For example, if zType is 'BLOBINT',
1009 ** SQLITE_AFF_INTEGER is returned.
1011 ** Substring | Affinity
1012 ** --------------------------------
1013 ** 'INT' | SQLITE_AFF_INTEGER
1014 ** 'CHAR' | SQLITE_AFF_TEXT
1015 ** 'CLOB' | SQLITE_AFF_TEXT
1016 ** 'TEXT' | SQLITE_AFF_TEXT
1017 ** 'BLOB' | SQLITE_AFF_NONE
1018 ** 'REAL' | SQLITE_AFF_REAL
1019 ** 'FLOA' | SQLITE_AFF_REAL
1020 ** 'DOUB' | SQLITE_AFF_REAL
1022 ** If none of the substrings in the above table are found,
1023 ** SQLITE_AFF_NUMERIC is returned.
1025 char sqlite3AffinityType(const char *zIn){
1026 u32 h = 0;
1027 char aff = SQLITE_AFF_NUMERIC;
1029 if( zIn ) while( zIn[0] ){
1030 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1031 zIn++;
1032 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1033 aff = SQLITE_AFF_TEXT;
1034 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1035 aff = SQLITE_AFF_TEXT;
1036 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1037 aff = SQLITE_AFF_TEXT;
1038 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1039 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1040 aff = SQLITE_AFF_NONE;
1041 #ifndef SQLITE_OMIT_FLOATING_POINT
1042 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1043 && aff==SQLITE_AFF_NUMERIC ){
1044 aff = SQLITE_AFF_REAL;
1045 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1046 && aff==SQLITE_AFF_NUMERIC ){
1047 aff = SQLITE_AFF_REAL;
1048 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1049 && aff==SQLITE_AFF_NUMERIC ){
1050 aff = SQLITE_AFF_REAL;
1051 #endif
1052 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1053 aff = SQLITE_AFF_INTEGER;
1054 break;
1058 return aff;
1062 ** This routine is called by the parser while in the middle of
1063 ** parsing a CREATE TABLE statement. The pFirst token is the first
1064 ** token in the sequence of tokens that describe the type of the
1065 ** column currently under construction. pLast is the last token
1066 ** in the sequence. Use this information to construct a string
1067 ** that contains the typename of the column and store that string
1068 ** in zType.
1070 void sqlite3AddColumnType(Parse *pParse, Token *pType){
1071 Table *p;
1072 Column *pCol;
1074 p = pParse->pNewTable;
1075 if( p==0 || NEVER(p->nCol<1) ) return;
1076 pCol = &p->aCol[p->nCol-1];
1077 assert( pCol->zType==0 );
1078 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
1079 pCol->affinity = sqlite3AffinityType(pCol->zType);
1083 ** The expression is the default value for the most recently added column
1084 ** of the table currently under construction.
1086 ** Default value expressions must be constant. Raise an exception if this
1087 ** is not the case.
1089 ** This routine is called by the parser while in the middle of
1090 ** parsing a CREATE TABLE statement.
1092 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
1093 Table *p;
1094 Column *pCol;
1095 sqlite3 *db = pParse->db;
1096 p = pParse->pNewTable;
1097 if( p!=0 ){
1098 pCol = &(p->aCol[p->nCol-1]);
1099 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
1100 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1101 pCol->zName);
1102 }else{
1103 /* A copy of pExpr is used instead of the original, as pExpr contains
1104 ** tokens that point to volatile memory. The 'span' of the expression
1105 ** is required by pragma table_info.
1107 sqlite3ExprDelete(db, pCol->pDflt);
1108 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1109 sqlite3DbFree(db, pCol->zDflt);
1110 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1111 (int)(pSpan->zEnd - pSpan->zStart));
1114 sqlite3ExprDelete(db, pSpan->pExpr);
1118 ** Designate the PRIMARY KEY for the table. pList is a list of names
1119 ** of columns that form the primary key. If pList is NULL, then the
1120 ** most recently added column of the table is the primary key.
1122 ** A table can have at most one primary key. If the table already has
1123 ** a primary key (and this is the second primary key) then create an
1124 ** error.
1126 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1127 ** then we will try to use that column as the rowid. Set the Table.iPKey
1128 ** field of the table under construction to be the index of the
1129 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1130 ** no INTEGER PRIMARY KEY.
1132 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1133 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
1135 void sqlite3AddPrimaryKey(
1136 Parse *pParse, /* Parsing context */
1137 ExprList *pList, /* List of field names to be indexed */
1138 int onError, /* What to do with a uniqueness conflict */
1139 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1140 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1142 Table *pTab = pParse->pNewTable;
1143 char *zType = 0;
1144 int iCol = -1, i;
1145 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
1146 if( pTab->tabFlags & TF_HasPrimaryKey ){
1147 sqlite3ErrorMsg(pParse,
1148 "table \"%s\" has more than one primary key", pTab->zName);
1149 goto primary_key_exit;
1151 pTab->tabFlags |= TF_HasPrimaryKey;
1152 if( pList==0 ){
1153 iCol = pTab->nCol - 1;
1154 pTab->aCol[iCol].isPrimKey = 1;
1155 }else{
1156 for(i=0; i<pList->nExpr; i++){
1157 for(iCol=0; iCol<pTab->nCol; iCol++){
1158 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1159 break;
1162 if( iCol<pTab->nCol ){
1163 pTab->aCol[iCol].isPrimKey = 1;
1166 if( pList->nExpr>1 ) iCol = -1;
1168 if( iCol>=0 && iCol<pTab->nCol ){
1169 zType = pTab->aCol[iCol].zType;
1171 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1172 && sortOrder==SQLITE_SO_ASC ){
1173 pTab->iPKey = iCol;
1174 pTab->keyConf = (u8)onError;
1175 assert( autoInc==0 || autoInc==1 );
1176 pTab->tabFlags |= autoInc*TF_Autoincrement;
1177 }else if( autoInc ){
1178 #ifndef SQLITE_OMIT_AUTOINCREMENT
1179 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1180 "INTEGER PRIMARY KEY");
1181 #endif
1182 }else{
1183 Index *p;
1184 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1185 if( p ){
1186 p->autoIndex = 2;
1188 pList = 0;
1191 primary_key_exit:
1192 sqlite3ExprListDelete(pParse->db, pList);
1193 return;
1197 ** Add a new CHECK constraint to the table currently under construction.
1199 void sqlite3AddCheckConstraint(
1200 Parse *pParse, /* Parsing context */
1201 Expr *pCheckExpr /* The check expression */
1203 sqlite3 *db = pParse->db;
1204 #ifndef SQLITE_OMIT_CHECK
1205 Table *pTab = pParse->pNewTable;
1206 if( pTab && !IN_DECLARE_VTAB ){
1207 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1208 }else
1209 #endif
1211 sqlite3ExprDelete(db, pCheckExpr);
1216 ** Set the collation function of the most recently parsed table column
1217 ** to the CollSeq given.
1219 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1220 Table *p;
1221 int i;
1222 char *zColl; /* Dequoted name of collation sequence */
1223 sqlite3 *db;
1225 if( (p = pParse->pNewTable)==0 ) return;
1226 i = p->nCol-1;
1227 db = pParse->db;
1228 zColl = sqlite3NameFromToken(db, pToken);
1229 if( !zColl ) return;
1231 if( sqlite3LocateCollSeq(pParse, zColl) ){
1232 Index *pIdx;
1233 p->aCol[i].zColl = zColl;
1235 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1236 ** then an index may have been created on this column before the
1237 ** collation type was added. Correct this if it is the case.
1239 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1240 assert( pIdx->nColumn==1 );
1241 if( pIdx->aiColumn[0]==i ){
1242 pIdx->azColl[0] = p->aCol[i].zColl;
1245 }else{
1246 sqlite3DbFree(db, zColl);
1251 ** This function returns the collation sequence for database native text
1252 ** encoding identified by the string zName, length nName.
1254 ** If the requested collation sequence is not available, or not available
1255 ** in the database native encoding, the collation factory is invoked to
1256 ** request it. If the collation factory does not supply such a sequence,
1257 ** and the sequence is available in another text encoding, then that is
1258 ** returned instead.
1260 ** If no versions of the requested collations sequence are available, or
1261 ** another error occurs, NULL is returned and an error message written into
1262 ** pParse.
1264 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1265 ** invokes the collation factory if the named collation cannot be found
1266 ** and generates an error message.
1268 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1270 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
1271 sqlite3 *db = pParse->db;
1272 u8 enc = ENC(db);
1273 u8 initbusy = db->init.busy;
1274 CollSeq *pColl;
1276 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
1277 if( !initbusy && (!pColl || !pColl->xCmp) ){
1278 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
1279 if( !pColl ){
1280 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
1284 return pColl;
1289 ** Generate code that will increment the schema cookie.
1291 ** The schema cookie is used to determine when the schema for the
1292 ** database changes. After each schema change, the cookie value
1293 ** changes. When a process first reads the schema it records the
1294 ** cookie. Thereafter, whenever it goes to access the database,
1295 ** it checks the cookie to make sure the schema has not changed
1296 ** since it was last read.
1298 ** This plan is not completely bullet-proof. It is possible for
1299 ** the schema to change multiple times and for the cookie to be
1300 ** set back to prior value. But schema changes are infrequent
1301 ** and the probability of hitting the same cookie value is only
1302 ** 1 chance in 2^32. So we're safe enough.
1304 void sqlite3ChangeCookie(Parse *pParse, int iDb){
1305 int r1 = sqlite3GetTempReg(pParse);
1306 sqlite3 *db = pParse->db;
1307 Vdbe *v = pParse->pVdbe;
1308 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1309 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
1310 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
1311 sqlite3ReleaseTempReg(pParse, r1);
1315 ** Measure the number of characters needed to output the given
1316 ** identifier. The number returned includes any quotes used
1317 ** but does not include the null terminator.
1319 ** The estimate is conservative. It might be larger that what is
1320 ** really needed.
1322 static int identLength(const char *z){
1323 int n;
1324 for(n=0; *z; n++, z++){
1325 if( *z=='"' ){ n++; }
1327 return n + 2;
1331 ** The first parameter is a pointer to an output buffer. The second
1332 ** parameter is a pointer to an integer that contains the offset at
1333 ** which to write into the output buffer. This function copies the
1334 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1335 ** to the specified offset in the buffer and updates *pIdx to refer
1336 ** to the first byte after the last byte written before returning.
1338 ** If the string zSignedIdent consists entirely of alpha-numeric
1339 ** characters, does not begin with a digit and is not an SQL keyword,
1340 ** then it is copied to the output buffer exactly as it is. Otherwise,
1341 ** it is quoted using double-quotes.
1343 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1344 unsigned char *zIdent = (unsigned char*)zSignedIdent;
1345 int i, j, needQuote;
1346 i = *pIdx;
1348 for(j=0; zIdent[j]; j++){
1349 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1351 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1352 if( !needQuote ){
1353 needQuote = zIdent[j];
1356 if( needQuote ) z[i++] = '"';
1357 for(j=0; zIdent[j]; j++){
1358 z[i++] = zIdent[j];
1359 if( zIdent[j]=='"' ) z[i++] = '"';
1361 if( needQuote ) z[i++] = '"';
1362 z[i] = 0;
1363 *pIdx = i;
1367 ** Generate a CREATE TABLE statement appropriate for the given
1368 ** table. Memory to hold the text of the statement is obtained
1369 ** from sqliteMalloc() and must be freed by the calling function.
1371 static char *createTableStmt(sqlite3 *db, Table *p){
1372 int i, k, n;
1373 char *zStmt;
1374 char *zSep, *zSep2, *zEnd;
1375 Column *pCol;
1376 n = 0;
1377 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1378 n += identLength(pCol->zName) + 5;
1380 n += identLength(p->zName);
1381 if( n<50 ){
1382 zSep = "";
1383 zSep2 = ",";
1384 zEnd = ")";
1385 }else{
1386 zSep = "\n ";
1387 zSep2 = ",\n ";
1388 zEnd = "\n)";
1390 n += 35 + 6*p->nCol;
1391 zStmt = sqlite3DbMallocRaw(0, n);
1392 if( zStmt==0 ){
1393 db->mallocFailed = 1;
1394 return 0;
1396 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1397 k = sqlite3Strlen30(zStmt);
1398 identPut(zStmt, &k, p->zName);
1399 zStmt[k++] = '(';
1400 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1401 static const char * const azType[] = {
1402 /* SQLITE_AFF_TEXT */ " TEXT",
1403 /* SQLITE_AFF_NONE */ "",
1404 /* SQLITE_AFF_NUMERIC */ " NUM",
1405 /* SQLITE_AFF_INTEGER */ " INT",
1406 /* SQLITE_AFF_REAL */ " REAL"
1408 int len;
1409 const char *zType;
1411 sqlite3_snprintf(n-k, &zStmt[k], zSep);
1412 k += sqlite3Strlen30(&zStmt[k]);
1413 zSep = zSep2;
1414 identPut(zStmt, &k, pCol->zName);
1415 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1416 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
1417 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1418 testcase( pCol->affinity==SQLITE_AFF_NONE );
1419 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1420 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1421 testcase( pCol->affinity==SQLITE_AFF_REAL );
1423 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1424 len = sqlite3Strlen30(zType);
1425 assert( pCol->affinity==SQLITE_AFF_NONE
1426 || pCol->affinity==sqlite3AffinityType(zType) );
1427 memcpy(&zStmt[k], zType, len);
1428 k += len;
1429 assert( k<=n );
1431 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1432 return zStmt;
1436 ** This routine is called to report the final ")" that terminates
1437 ** a CREATE TABLE statement.
1439 ** The table structure that other action routines have been building
1440 ** is added to the internal hash tables, assuming no errors have
1441 ** occurred.
1443 ** An entry for the table is made in the master table on disk, unless
1444 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1445 ** it means we are reading the sqlite_master table because we just
1446 ** connected to the database or because the sqlite_master table has
1447 ** recently changed, so the entry for this table already exists in
1448 ** the sqlite_master table. We do not want to create it again.
1450 ** If the pSelect argument is not NULL, it means that this routine
1451 ** was called to create a table generated from a
1452 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1453 ** the new table will match the result set of the SELECT.
1455 void sqlite3EndTable(
1456 Parse *pParse, /* Parse context */
1457 Token *pCons, /* The ',' token after the last column defn. */
1458 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1459 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1461 Table *p;
1462 sqlite3 *db = pParse->db;
1463 int iDb;
1465 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1466 return;
1468 p = pParse->pNewTable;
1469 if( p==0 ) return;
1471 assert( !db->init.busy || !pSelect );
1473 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1475 #ifndef SQLITE_OMIT_CHECK
1476 /* Resolve names in all CHECK constraint expressions.
1478 if( p->pCheck ){
1479 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1480 NameContext sNC; /* Name context for pParse->pNewTable */
1482 memset(&sNC, 0, sizeof(sNC));
1483 memset(&sSrc, 0, sizeof(sSrc));
1484 sSrc.nSrc = 1;
1485 sSrc.a[0].zName = p->zName;
1486 sSrc.a[0].pTab = p;
1487 sSrc.a[0].iCursor = -1;
1488 sNC.pParse = pParse;
1489 sNC.pSrcList = &sSrc;
1490 sNC.isCheck = 1;
1491 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
1492 return;
1495 #endif /* !defined(SQLITE_OMIT_CHECK) */
1497 /* If the db->init.busy is 1 it means we are reading the SQL off the
1498 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1499 ** So do not write to the disk again. Extract the root page number
1500 ** for the table from the db->init.newTnum field. (The page number
1501 ** should have been put there by the sqliteOpenCb routine.)
1503 if( db->init.busy ){
1504 p->tnum = db->init.newTnum;
1507 /* If not initializing, then create a record for the new table
1508 ** in the SQLITE_MASTER table of the database.
1510 ** If this is a TEMPORARY table, write the entry into the auxiliary
1511 ** file instead of into the main database file.
1513 if( !db->init.busy ){
1514 int n;
1515 Vdbe *v;
1516 char *zType; /* "view" or "table" */
1517 char *zType2; /* "VIEW" or "TABLE" */
1518 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
1520 v = sqlite3GetVdbe(pParse);
1521 if( NEVER(v==0) ) return;
1523 sqlite3VdbeAddOp1(v, OP_Close, 0);
1526 ** Initialize zType for the new view or table.
1528 if( p->pSelect==0 ){
1529 /* A regular table */
1530 zType = "table";
1531 zType2 = "TABLE";
1532 #ifndef SQLITE_OMIT_VIEW
1533 }else{
1534 /* A view */
1535 zType = "view";
1536 zType2 = "VIEW";
1537 #endif
1540 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1541 ** statement to populate the new table. The root-page number for the
1542 ** new table is in register pParse->regRoot.
1544 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1545 ** suitable state to query for the column names and types to be used
1546 ** by the new table.
1548 ** A shared-cache write-lock is not required to write to the new table,
1549 ** as a schema-lock must have already been obtained to create it. Since
1550 ** a schema-lock excludes all other database users, the write-lock would
1551 ** be redundant.
1553 if( pSelect ){
1554 SelectDest dest;
1555 Table *pSelTab;
1557 assert(pParse->nTab==1);
1558 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
1559 sqlite3VdbeChangeP5(v, 1);
1560 pParse->nTab = 2;
1561 sqlite3SelectDestInit(&dest, SRT_Table, 1);
1562 sqlite3Select(pParse, pSelect, &dest);
1563 sqlite3VdbeAddOp1(v, OP_Close, 1);
1564 if( pParse->nErr==0 ){
1565 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1566 if( pSelTab==0 ) return;
1567 assert( p->aCol==0 );
1568 p->nCol = pSelTab->nCol;
1569 p->aCol = pSelTab->aCol;
1570 pSelTab->nCol = 0;
1571 pSelTab->aCol = 0;
1572 sqlite3DeleteTable(db, pSelTab);
1576 /* Compute the complete text of the CREATE statement */
1577 if( pSelect ){
1578 zStmt = createTableStmt(db, p);
1579 }else{
1580 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
1581 zStmt = sqlite3MPrintf(db,
1582 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1586 /* A slot for the record has already been allocated in the
1587 ** SQLITE_MASTER table. We just need to update that slot with all
1588 ** the information we've collected.
1590 sqlite3NestedParse(pParse,
1591 "UPDATE %Q.%s "
1592 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1593 "WHERE rowid=#%d",
1594 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1595 zType,
1596 p->zName,
1597 p->zName,
1598 pParse->regRoot,
1599 zStmt,
1600 pParse->regRowid
1602 sqlite3DbFree(db, zStmt);
1603 sqlite3ChangeCookie(pParse, iDb);
1605 #ifndef SQLITE_OMIT_AUTOINCREMENT
1606 /* Check to see if we need to create an sqlite_sequence table for
1607 ** keeping track of autoincrement keys.
1609 if( p->tabFlags & TF_Autoincrement ){
1610 Db *pDb = &db->aDb[iDb];
1611 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1612 if( pDb->pSchema->pSeqTab==0 ){
1613 sqlite3NestedParse(pParse,
1614 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1615 pDb->zName
1619 #endif
1621 /* Reparse everything to update our internal data structures */
1622 sqlite3VdbeAddParseSchemaOp(v, iDb,
1623 sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
1627 /* Add the table to the in-memory representation of the database.
1629 if( db->init.busy ){
1630 Table *pOld;
1631 Schema *pSchema = p->pSchema;
1632 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1633 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
1634 sqlite3Strlen30(p->zName),p);
1635 if( pOld ){
1636 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1637 db->mallocFailed = 1;
1638 return;
1640 pParse->pNewTable = 0;
1641 db->nTable++;
1642 db->flags |= SQLITE_InternChanges;
1644 #ifndef SQLITE_OMIT_ALTERTABLE
1645 if( !p->pSelect ){
1646 const char *zName = (const char *)pParse->sNameToken.z;
1647 int nName;
1648 assert( !pSelect && pCons && pEnd );
1649 if( pCons->z==0 ){
1650 pCons = pEnd;
1652 nName = (int)((const char *)pCons->z - zName);
1653 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
1655 #endif
1659 #ifndef SQLITE_OMIT_VIEW
1661 ** The parser calls this routine in order to create a new VIEW
1663 void sqlite3CreateView(
1664 Parse *pParse, /* The parsing context */
1665 Token *pBegin, /* The CREATE token that begins the statement */
1666 Token *pName1, /* The token that holds the name of the view */
1667 Token *pName2, /* The token that holds the name of the view */
1668 Select *pSelect, /* A SELECT statement that will become the new view */
1669 int isTemp, /* TRUE for a TEMPORARY view */
1670 int noErr /* Suppress error messages if VIEW already exists */
1672 Table *p;
1673 int n;
1674 const char *z;
1675 Token sEnd;
1676 DbFixer sFix;
1677 Token *pName = 0;
1678 int iDb;
1679 sqlite3 *db = pParse->db;
1681 if( pParse->nVar>0 ){
1682 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1683 sqlite3SelectDelete(db, pSelect);
1684 return;
1686 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
1687 p = pParse->pNewTable;
1688 if( p==0 || pParse->nErr ){
1689 sqlite3SelectDelete(db, pSelect);
1690 return;
1692 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1693 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1694 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
1695 && sqlite3FixSelect(&sFix, pSelect)
1697 sqlite3SelectDelete(db, pSelect);
1698 return;
1701 /* Make a copy of the entire SELECT statement that defines the view.
1702 ** This will force all the Expr.token.z values to be dynamically
1703 ** allocated rather than point to the input string - which means that
1704 ** they will persist after the current sqlite3_exec() call returns.
1706 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
1707 sqlite3SelectDelete(db, pSelect);
1708 if( db->mallocFailed ){
1709 return;
1711 if( !db->init.busy ){
1712 sqlite3ViewGetColumnNames(pParse, p);
1715 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1716 ** the end.
1718 sEnd = pParse->sLastToken;
1719 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
1720 sEnd.z += sEnd.n;
1722 sEnd.n = 0;
1723 n = (int)(sEnd.z - pBegin->z);
1724 z = pBegin->z;
1725 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
1726 sEnd.z = &z[n-1];
1727 sEnd.n = 1;
1729 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1730 sqlite3EndTable(pParse, 0, &sEnd, 0);
1731 return;
1733 #endif /* SQLITE_OMIT_VIEW */
1735 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1737 ** The Table structure pTable is really a VIEW. Fill in the names of
1738 ** the columns of the view in the pTable structure. Return the number
1739 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
1741 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1742 Table *pSelTab; /* A fake table from which we get the result set */
1743 Select *pSel; /* Copy of the SELECT that implements the view */
1744 int nErr = 0; /* Number of errors encountered */
1745 int n; /* Temporarily holds the number of cursors assigned */
1746 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
1747 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
1749 assert( pTable );
1751 #ifndef SQLITE_OMIT_VIRTUALTABLE
1752 if( sqlite3VtabCallConnect(pParse, pTable) ){
1753 return SQLITE_ERROR;
1755 if( IsVirtual(pTable) ) return 0;
1756 #endif
1758 #ifndef SQLITE_OMIT_VIEW
1759 /* A positive nCol means the columns names for this view are
1760 ** already known.
1762 if( pTable->nCol>0 ) return 0;
1764 /* A negative nCol is a special marker meaning that we are currently
1765 ** trying to compute the column names. If we enter this routine with
1766 ** a negative nCol, it means two or more views form a loop, like this:
1768 ** CREATE VIEW one AS SELECT * FROM two;
1769 ** CREATE VIEW two AS SELECT * FROM one;
1771 ** Actually, the error above is now caught prior to reaching this point.
1772 ** But the following test is still important as it does come up
1773 ** in the following:
1775 ** CREATE TABLE main.ex1(a);
1776 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1777 ** SELECT * FROM temp.ex1;
1779 if( pTable->nCol<0 ){
1780 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1781 return 1;
1783 assert( pTable->nCol>=0 );
1785 /* If we get this far, it means we need to compute the table names.
1786 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1787 ** "*" elements in the results set of the view and will assign cursors
1788 ** to the elements of the FROM clause. But we do not want these changes
1789 ** to be permanent. So the computation is done on a copy of the SELECT
1790 ** statement that defines the view.
1792 assert( pTable->pSelect );
1793 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
1794 if( pSel ){
1795 u8 enableLookaside = db->lookaside.bEnabled;
1796 n = pParse->nTab;
1797 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1798 pTable->nCol = -1;
1799 db->lookaside.bEnabled = 0;
1800 #ifndef SQLITE_OMIT_AUTHORIZATION
1801 xAuth = db->xAuth;
1802 db->xAuth = 0;
1803 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
1804 db->xAuth = xAuth;
1805 #else
1806 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
1807 #endif
1808 db->lookaside.bEnabled = enableLookaside;
1809 pParse->nTab = n;
1810 if( pSelTab ){
1811 assert( pTable->aCol==0 );
1812 pTable->nCol = pSelTab->nCol;
1813 pTable->aCol = pSelTab->aCol;
1814 pSelTab->nCol = 0;
1815 pSelTab->aCol = 0;
1816 sqlite3DeleteTable(db, pSelTab);
1817 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
1818 pTable->pSchema->flags |= DB_UnresetViews;
1819 }else{
1820 pTable->nCol = 0;
1821 nErr++;
1823 sqlite3SelectDelete(db, pSel);
1824 } else {
1825 nErr++;
1827 #endif /* SQLITE_OMIT_VIEW */
1828 return nErr;
1830 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
1832 #ifndef SQLITE_OMIT_VIEW
1834 ** Clear the column names from every VIEW in database idx.
1836 static void sqliteViewResetAll(sqlite3 *db, int idx){
1837 HashElem *i;
1838 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
1839 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1840 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
1841 Table *pTab = sqliteHashData(i);
1842 if( pTab->pSelect ){
1843 sqliteDeleteColumnNames(db, pTab);
1844 pTab->aCol = 0;
1845 pTab->nCol = 0;
1848 DbClearProperty(db, idx, DB_UnresetViews);
1850 #else
1851 # define sqliteViewResetAll(A,B)
1852 #endif /* SQLITE_OMIT_VIEW */
1855 ** This function is called by the VDBE to adjust the internal schema
1856 ** used by SQLite when the btree layer moves a table root page. The
1857 ** root-page of a table or index in database iDb has changed from iFrom
1858 ** to iTo.
1860 ** Ticket #1728: The symbol table might still contain information
1861 ** on tables and/or indices that are the process of being deleted.
1862 ** If you are unlucky, one of those deleted indices or tables might
1863 ** have the same rootpage number as the real table or index that is
1864 ** being moved. So we cannot stop searching after the first match
1865 ** because the first match might be for one of the deleted indices
1866 ** or tables and not the table/index that is actually being moved.
1867 ** We must continue looping until all tables and indices with
1868 ** rootpage==iFrom have been converted to have a rootpage of iTo
1869 ** in order to be certain that we got the right one.
1871 #ifndef SQLITE_OMIT_AUTOVACUUM
1872 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
1873 HashElem *pElem;
1874 Hash *pHash;
1875 Db *pDb;
1877 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1878 pDb = &db->aDb[iDb];
1879 pHash = &pDb->pSchema->tblHash;
1880 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1881 Table *pTab = sqliteHashData(pElem);
1882 if( pTab->tnum==iFrom ){
1883 pTab->tnum = iTo;
1886 pHash = &pDb->pSchema->idxHash;
1887 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1888 Index *pIdx = sqliteHashData(pElem);
1889 if( pIdx->tnum==iFrom ){
1890 pIdx->tnum = iTo;
1894 #endif
1897 ** Write code to erase the table with root-page iTable from database iDb.
1898 ** Also write code to modify the sqlite_master table and internal schema
1899 ** if a root-page of another table is moved by the btree-layer whilst
1900 ** erasing iTable (this can happen with an auto-vacuum database).
1902 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1903 Vdbe *v = sqlite3GetVdbe(pParse);
1904 int r1 = sqlite3GetTempReg(pParse);
1905 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
1906 sqlite3MayAbort(pParse);
1907 #ifndef SQLITE_OMIT_AUTOVACUUM
1908 /* OP_Destroy stores an in integer r1. If this integer
1909 ** is non-zero, then it is the root page number of a table moved to
1910 ** location iTable. The following code modifies the sqlite_master table to
1911 ** reflect this.
1913 ** The "#NNN" in the SQL is a special constant that means whatever value
1914 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1915 ** token for additional information.
1917 sqlite3NestedParse(pParse,
1918 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1919 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
1920 #endif
1921 sqlite3ReleaseTempReg(pParse, r1);
1925 ** Write VDBE code to erase table pTab and all associated indices on disk.
1926 ** Code to update the sqlite_master tables and internal schema definitions
1927 ** in case a root-page belonging to another table is moved by the btree layer
1928 ** is also added (this can happen with an auto-vacuum database).
1930 static void destroyTable(Parse *pParse, Table *pTab){
1931 #ifdef SQLITE_OMIT_AUTOVACUUM
1932 Index *pIdx;
1933 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1934 destroyRootPage(pParse, pTab->tnum, iDb);
1935 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1936 destroyRootPage(pParse, pIdx->tnum, iDb);
1938 #else
1939 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1940 ** is not defined), then it is important to call OP_Destroy on the
1941 ** table and index root-pages in order, starting with the numerically
1942 ** largest root-page number. This guarantees that none of the root-pages
1943 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1944 ** following were coded:
1946 ** OP_Destroy 4 0
1947 ** ...
1948 ** OP_Destroy 5 0
1950 ** and root page 5 happened to be the largest root-page number in the
1951 ** database, then root page 5 would be moved to page 4 by the
1952 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1953 ** a free-list page.
1955 int iTab = pTab->tnum;
1956 int iDestroyed = 0;
1958 while( 1 ){
1959 Index *pIdx;
1960 int iLargest = 0;
1962 if( iDestroyed==0 || iTab<iDestroyed ){
1963 iLargest = iTab;
1965 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1966 int iIdx = pIdx->tnum;
1967 assert( pIdx->pSchema==pTab->pSchema );
1968 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1969 iLargest = iIdx;
1972 if( iLargest==0 ){
1973 return;
1974 }else{
1975 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1976 destroyRootPage(pParse, iLargest, iDb);
1977 iDestroyed = iLargest;
1980 #endif
1984 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
1985 ** after a DROP INDEX or DROP TABLE command.
1987 static void sqlite3ClearStatTables(
1988 Parse *pParse, /* The parsing context */
1989 int iDb, /* The database number */
1990 const char *zType, /* "idx" or "tbl" */
1991 const char *zName /* Name of index or table */
1993 int i;
1994 const char *zDbName = pParse->db->aDb[iDb].zName;
1995 for(i=1; i<=3; i++){
1996 char zTab[24];
1997 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
1998 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
1999 sqlite3NestedParse(pParse,
2000 "DELETE FROM %Q.%s WHERE %s=%Q",
2001 zDbName, zTab, zType, zName
2008 ** Generate code to drop a table.
2010 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2011 Vdbe *v;
2012 sqlite3 *db = pParse->db;
2013 Trigger *pTrigger;
2014 Db *pDb = &db->aDb[iDb];
2016 v = sqlite3GetVdbe(pParse);
2017 assert( v!=0 );
2018 sqlite3BeginWriteOperation(pParse, 1, iDb);
2020 #ifndef SQLITE_OMIT_VIRTUALTABLE
2021 if( IsVirtual(pTab) ){
2022 sqlite3VdbeAddOp0(v, OP_VBegin);
2024 #endif
2026 /* Drop all triggers associated with the table being dropped. Code
2027 ** is generated to remove entries from sqlite_master and/or
2028 ** sqlite_temp_master if required.
2030 pTrigger = sqlite3TriggerList(pParse, pTab);
2031 while( pTrigger ){
2032 assert( pTrigger->pSchema==pTab->pSchema ||
2033 pTrigger->pSchema==db->aDb[1].pSchema );
2034 sqlite3DropTriggerPtr(pParse, pTrigger);
2035 pTrigger = pTrigger->pNext;
2038 #ifndef SQLITE_OMIT_AUTOINCREMENT
2039 /* Remove any entries of the sqlite_sequence table associated with
2040 ** the table being dropped. This is done before the table is dropped
2041 ** at the btree level, in case the sqlite_sequence table needs to
2042 ** move as a result of the drop (can happen in auto-vacuum mode).
2044 if( pTab->tabFlags & TF_Autoincrement ){
2045 sqlite3NestedParse(pParse,
2046 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2047 pDb->zName, pTab->zName
2050 #endif
2052 /* Drop all SQLITE_MASTER table and index entries that refer to the
2053 ** table. The program name loops through the master table and deletes
2054 ** every row that refers to a table of the same name as the one being
2055 ** dropped. Triggers are handled seperately because a trigger can be
2056 ** created in the temp database that refers to a table in another
2057 ** database.
2059 sqlite3NestedParse(pParse,
2060 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2061 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2062 if( !isView && !IsVirtual(pTab) ){
2063 destroyTable(pParse, pTab);
2066 /* Remove the table entry from SQLite's internal schema and modify
2067 ** the schema cookie.
2069 if( IsVirtual(pTab) ){
2070 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2072 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2073 sqlite3ChangeCookie(pParse, iDb);
2074 sqliteViewResetAll(db, iDb);
2078 ** This routine is called to do the work of a DROP TABLE statement.
2079 ** pName is the name of the table to be dropped.
2081 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
2082 Table *pTab;
2083 Vdbe *v;
2084 sqlite3 *db = pParse->db;
2085 int iDb;
2087 if( db->mallocFailed ){
2088 goto exit_drop_table;
2090 assert( pParse->nErr==0 );
2091 assert( pName->nSrc==1 );
2092 if( noErr ) db->suppressErr++;
2093 pTab = sqlite3LocateTable(pParse, isView,
2094 pName->a[0].zName, pName->a[0].zDatabase);
2095 if( noErr ) db->suppressErr--;
2097 if( pTab==0 ){
2098 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2099 goto exit_drop_table;
2101 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2102 assert( iDb>=0 && iDb<db->nDb );
2104 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2105 ** it is initialized.
2107 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2108 goto exit_drop_table;
2110 #ifndef SQLITE_OMIT_AUTHORIZATION
2112 int code;
2113 const char *zTab = SCHEMA_TABLE(iDb);
2114 const char *zDb = db->aDb[iDb].zName;
2115 const char *zArg2 = 0;
2116 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
2117 goto exit_drop_table;
2119 if( isView ){
2120 if( !OMIT_TEMPDB && iDb==1 ){
2121 code = SQLITE_DROP_TEMP_VIEW;
2122 }else{
2123 code = SQLITE_DROP_VIEW;
2125 #ifndef SQLITE_OMIT_VIRTUALTABLE
2126 }else if( IsVirtual(pTab) ){
2127 code = SQLITE_DROP_VTABLE;
2128 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
2129 #endif
2130 }else{
2131 if( !OMIT_TEMPDB && iDb==1 ){
2132 code = SQLITE_DROP_TEMP_TABLE;
2133 }else{
2134 code = SQLITE_DROP_TABLE;
2137 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2138 goto exit_drop_table;
2140 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2141 goto exit_drop_table;
2144 #endif
2145 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2146 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
2147 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2148 goto exit_drop_table;
2151 #ifndef SQLITE_OMIT_VIEW
2152 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2153 ** on a table.
2155 if( isView && pTab->pSelect==0 ){
2156 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2157 goto exit_drop_table;
2159 if( !isView && pTab->pSelect ){
2160 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2161 goto exit_drop_table;
2163 #endif
2165 /* Generate code to remove the table from the master table
2166 ** on disk.
2168 v = sqlite3GetVdbe(pParse);
2169 if( v ){
2170 sqlite3BeginWriteOperation(pParse, 1, iDb);
2171 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
2172 sqlite3FkDropTable(pParse, pName, pTab);
2173 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
2176 exit_drop_table:
2177 sqlite3SrcListDelete(db, pName);
2181 ** This routine is called to create a new foreign key on the table
2182 ** currently under construction. pFromCol determines which columns
2183 ** in the current table point to the foreign key. If pFromCol==0 then
2184 ** connect the key to the last column inserted. pTo is the name of
2185 ** the table referred to. pToCol is a list of tables in the other
2186 ** pTo table that the foreign key points to. flags contains all
2187 ** information about the conflict resolution algorithms specified
2188 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2190 ** An FKey structure is created and added to the table currently
2191 ** under construction in the pParse->pNewTable field.
2193 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2194 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2196 void sqlite3CreateForeignKey(
2197 Parse *pParse, /* Parsing context */
2198 ExprList *pFromCol, /* Columns in this table that point to other table */
2199 Token *pTo, /* Name of the other table */
2200 ExprList *pToCol, /* Columns in the other table */
2201 int flags /* Conflict resolution algorithms. */
2203 sqlite3 *db = pParse->db;
2204 #ifndef SQLITE_OMIT_FOREIGN_KEY
2205 FKey *pFKey = 0;
2206 FKey *pNextTo;
2207 Table *p = pParse->pNewTable;
2208 int nByte;
2209 int i;
2210 int nCol;
2211 char *z;
2213 assert( pTo!=0 );
2214 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2215 if( pFromCol==0 ){
2216 int iCol = p->nCol-1;
2217 if( NEVER(iCol<0) ) goto fk_end;
2218 if( pToCol && pToCol->nExpr!=1 ){
2219 sqlite3ErrorMsg(pParse, "foreign key on %s"
2220 " should reference only one column of table %T",
2221 p->aCol[iCol].zName, pTo);
2222 goto fk_end;
2224 nCol = 1;
2225 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2226 sqlite3ErrorMsg(pParse,
2227 "number of columns in foreign key does not match the number of "
2228 "columns in the referenced table");
2229 goto fk_end;
2230 }else{
2231 nCol = pFromCol->nExpr;
2233 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2234 if( pToCol ){
2235 for(i=0; i<pToCol->nExpr; i++){
2236 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2239 pFKey = sqlite3DbMallocZero(db, nByte );
2240 if( pFKey==0 ){
2241 goto fk_end;
2243 pFKey->pFrom = p;
2244 pFKey->pNextFrom = p->pFKey;
2245 z = (char*)&pFKey->aCol[nCol];
2246 pFKey->zTo = z;
2247 memcpy(z, pTo->z, pTo->n);
2248 z[pTo->n] = 0;
2249 sqlite3Dequote(z);
2250 z += pTo->n+1;
2251 pFKey->nCol = nCol;
2252 if( pFromCol==0 ){
2253 pFKey->aCol[0].iFrom = p->nCol-1;
2254 }else{
2255 for(i=0; i<nCol; i++){
2256 int j;
2257 for(j=0; j<p->nCol; j++){
2258 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2259 pFKey->aCol[i].iFrom = j;
2260 break;
2263 if( j>=p->nCol ){
2264 sqlite3ErrorMsg(pParse,
2265 "unknown column \"%s\" in foreign key definition",
2266 pFromCol->a[i].zName);
2267 goto fk_end;
2271 if( pToCol ){
2272 for(i=0; i<nCol; i++){
2273 int n = sqlite3Strlen30(pToCol->a[i].zName);
2274 pFKey->aCol[i].zCol = z;
2275 memcpy(z, pToCol->a[i].zName, n);
2276 z[n] = 0;
2277 z += n+1;
2280 pFKey->isDeferred = 0;
2281 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2282 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
2284 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2285 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2286 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2288 if( pNextTo==pFKey ){
2289 db->mallocFailed = 1;
2290 goto fk_end;
2292 if( pNextTo ){
2293 assert( pNextTo->pPrevTo==0 );
2294 pFKey->pNextTo = pNextTo;
2295 pNextTo->pPrevTo = pFKey;
2298 /* Link the foreign key to the table as the last step.
2300 p->pFKey = pFKey;
2301 pFKey = 0;
2303 fk_end:
2304 sqlite3DbFree(db, pFKey);
2305 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2306 sqlite3ExprListDelete(db, pFromCol);
2307 sqlite3ExprListDelete(db, pToCol);
2311 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2312 ** clause is seen as part of a foreign key definition. The isDeferred
2313 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2314 ** The behavior of the most recently created foreign key is adjusted
2315 ** accordingly.
2317 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2318 #ifndef SQLITE_OMIT_FOREIGN_KEY
2319 Table *pTab;
2320 FKey *pFKey;
2321 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2322 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
2323 pFKey->isDeferred = (u8)isDeferred;
2324 #endif
2328 ** Generate code that will erase and refill index *pIdx. This is
2329 ** used to initialize a newly created index or to recompute the
2330 ** content of an index in response to a REINDEX command.
2332 ** if memRootPage is not negative, it means that the index is newly
2333 ** created. The register specified by memRootPage contains the
2334 ** root page number of the index. If memRootPage is negative, then
2335 ** the index already exists and must be cleared before being refilled and
2336 ** the root page number of the index is taken from pIndex->tnum.
2338 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2339 Table *pTab = pIndex->pTable; /* The table that is indexed */
2340 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2341 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
2342 int iSorter; /* Cursor opened by OpenSorter (if in use) */
2343 int addr1; /* Address of top of loop */
2344 int addr2; /* Address to jump to for next iteration */
2345 int tnum; /* Root page of index */
2346 Vdbe *v; /* Generate code into this virtual machine */
2347 KeyInfo *pKey; /* KeyInfo for index */
2348 #ifdef SQLITE_OMIT_MERGE_SORT
2349 int regIdxKey; /* Registers containing the index key */
2350 #endif
2351 int regRecord; /* Register holding assemblied index record */
2352 sqlite3 *db = pParse->db; /* The database connection */
2353 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2355 #ifndef SQLITE_OMIT_AUTHORIZATION
2356 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2357 db->aDb[iDb].zName ) ){
2358 return;
2360 #endif
2362 /* Require a write-lock on the table to perform this operation */
2363 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2365 v = sqlite3GetVdbe(pParse);
2366 if( v==0 ) return;
2367 if( memRootPage>=0 ){
2368 tnum = memRootPage;
2369 }else{
2370 tnum = pIndex->tnum;
2371 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2373 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2374 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
2375 (char *)pKey, P4_KEYINFO_HANDOFF);
2376 if( memRootPage>=0 ){
2377 sqlite3VdbeChangeP5(v, 1);
2380 #ifndef SQLITE_OMIT_MERGE_SORT
2381 /* Open the sorter cursor if we are to use one. */
2382 iSorter = pParse->nTab++;
2383 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
2384 #else
2385 iSorter = iTab;
2386 #endif
2388 /* Open the table. Loop through all rows of the table, inserting index
2389 ** records into the sorter. */
2390 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2391 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
2392 regRecord = sqlite3GetTempReg(pParse);
2394 #ifndef SQLITE_OMIT_MERGE_SORT
2395 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2396 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
2397 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2398 sqlite3VdbeJumpHere(v, addr1);
2399 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
2400 if( pIndex->onError!=OE_None ){
2401 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2402 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2403 addr2 = sqlite3VdbeCurrentAddr(v);
2404 sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
2405 sqlite3HaltConstraint(
2406 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
2408 }else{
2409 addr2 = sqlite3VdbeCurrentAddr(v);
2411 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2412 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2413 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2414 #else
2415 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2416 addr2 = addr1 + 1;
2417 if( pIndex->onError!=OE_None ){
2418 const int regRowid = regIdxKey + pIndex->nColumn;
2419 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2420 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
2422 /* The registers accessed by the OP_IsUnique opcode were allocated
2423 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2424 ** call above. Just before that function was freed they were released
2425 ** (made available to the compiler for reuse) using
2426 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2427 ** opcode use the values stored within seems dangerous. However, since
2428 ** we can be sure that no other temp registers have been allocated
2429 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2431 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
2432 sqlite3HaltConstraint(
2433 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
2435 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
2436 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2437 #endif
2438 sqlite3ReleaseTempReg(pParse, regRecord);
2439 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
2440 sqlite3VdbeJumpHere(v, addr1);
2442 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2443 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
2444 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
2448 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2449 ** and pTblList is the name of the table that is to be indexed. Both will
2450 ** be NULL for a primary key or an index that is created to satisfy a
2451 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2452 ** as the table to be indexed. pParse->pNewTable is a table that is
2453 ** currently being constructed by a CREATE TABLE statement.
2455 ** pList is a list of columns to be indexed. pList will be NULL if this
2456 ** is a primary key or unique-constraint on the most recent column added
2457 ** to the table currently under construction.
2459 ** If the index is created successfully, return a pointer to the new Index
2460 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2461 ** as the tables primary key (Index.autoIndex==2).
2463 Index *sqlite3CreateIndex(
2464 Parse *pParse, /* All information about this parse */
2465 Token *pName1, /* First part of index name. May be NULL */
2466 Token *pName2, /* Second part of index name. May be NULL */
2467 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2468 ExprList *pList, /* A list of columns to be indexed */
2469 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2470 Token *pStart, /* The CREATE token that begins this statement */
2471 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
2472 int sortOrder, /* Sort order of primary key when pList==NULL */
2473 int ifNotExist /* Omit error if index already exists */
2475 Index *pRet = 0; /* Pointer to return */
2476 Table *pTab = 0; /* Table to be indexed */
2477 Index *pIndex = 0; /* The index to be created */
2478 char *zName = 0; /* Name of the index */
2479 int nName; /* Number of characters in zName */
2480 int i, j;
2481 Token nullId; /* Fake token for an empty ID list */
2482 DbFixer sFix; /* For assigning database names to pTable */
2483 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
2484 sqlite3 *db = pParse->db;
2485 Db *pDb; /* The specific table containing the indexed database */
2486 int iDb; /* Index of the database that is being written */
2487 Token *pName = 0; /* Unqualified name of the index to create */
2488 struct ExprList_item *pListItem; /* For looping over pList */
2489 int nCol;
2490 int nExtra = 0;
2491 char *zExtra;
2493 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
2494 assert( pParse->nErr==0 ); /* Never called with prior errors */
2495 if( db->mallocFailed || IN_DECLARE_VTAB ){
2496 goto exit_create_index;
2498 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2499 goto exit_create_index;
2503 ** Find the table that is to be indexed. Return early if not found.
2505 if( pTblName!=0 ){
2507 /* Use the two-part index name to determine the database
2508 ** to search for the table. 'Fix' the table name to this db
2509 ** before looking up the table.
2511 assert( pName1 && pName2 );
2512 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2513 if( iDb<0 ) goto exit_create_index;
2514 assert( pName && pName->z );
2516 #ifndef SQLITE_OMIT_TEMPDB
2517 /* If the index name was unqualified, check if the the table
2518 ** is a temp table. If so, set the database to 1. Do not do this
2519 ** if initialising a database schema.
2521 if( !db->init.busy ){
2522 pTab = sqlite3SrcListLookup(pParse, pTblName);
2523 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2524 iDb = 1;
2527 #endif
2529 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2530 sqlite3FixSrcList(&sFix, pTblName)
2532 /* Because the parser constructs pTblName from a single identifier,
2533 ** sqlite3FixSrcList can never fail. */
2534 assert(0);
2536 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
2537 pTblName->a[0].zDatabase);
2538 if( !pTab || db->mallocFailed ) goto exit_create_index;
2539 assert( db->aDb[iDb].pSchema==pTab->pSchema );
2540 }else{
2541 assert( pName==0 );
2542 assert( pStart==0 );
2543 pTab = pParse->pNewTable;
2544 if( !pTab ) goto exit_create_index;
2545 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2547 pDb = &db->aDb[iDb];
2549 assert( pTab!=0 );
2550 assert( pParse->nErr==0 );
2551 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2552 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
2553 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2554 goto exit_create_index;
2556 #ifndef SQLITE_OMIT_VIEW
2557 if( pTab->pSelect ){
2558 sqlite3ErrorMsg(pParse, "views may not be indexed");
2559 goto exit_create_index;
2561 #endif
2562 #ifndef SQLITE_OMIT_VIRTUALTABLE
2563 if( IsVirtual(pTab) ){
2564 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2565 goto exit_create_index;
2567 #endif
2570 ** Find the name of the index. Make sure there is not already another
2571 ** index or table with the same name.
2573 ** Exception: If we are reading the names of permanent indices from the
2574 ** sqlite_master table (because some other process changed the schema) and
2575 ** one of the index names collides with the name of a temporary table or
2576 ** index, then we will continue to process this index.
2578 ** If pName==0 it means that we are
2579 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2580 ** own name.
2582 if( pName ){
2583 zName = sqlite3NameFromToken(db, pName);
2584 if( zName==0 ) goto exit_create_index;
2585 assert( pName->z!=0 );
2586 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2587 goto exit_create_index;
2589 if( !db->init.busy ){
2590 if( sqlite3FindTable(db, zName, 0)!=0 ){
2591 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2592 goto exit_create_index;
2595 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2596 if( !ifNotExist ){
2597 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2598 }else{
2599 assert( !db->init.busy );
2600 sqlite3CodeVerifySchema(pParse, iDb);
2602 goto exit_create_index;
2604 }else{
2605 int n;
2606 Index *pLoop;
2607 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2608 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
2609 if( zName==0 ){
2610 goto exit_create_index;
2614 /* Check for authorization to create an index.
2616 #ifndef SQLITE_OMIT_AUTHORIZATION
2618 const char *zDb = pDb->zName;
2619 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
2620 goto exit_create_index;
2622 i = SQLITE_CREATE_INDEX;
2623 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2624 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
2625 goto exit_create_index;
2628 #endif
2630 /* If pList==0, it means this routine was called to make a primary
2631 ** key out of the last column added to the table under construction.
2632 ** So create a fake list to simulate this.
2634 if( pList==0 ){
2635 nullId.z = pTab->aCol[pTab->nCol-1].zName;
2636 nullId.n = sqlite3Strlen30((char*)nullId.z);
2637 pList = sqlite3ExprListAppend(pParse, 0, 0);
2638 if( pList==0 ) goto exit_create_index;
2639 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
2640 pList->a[0].sortOrder = (u8)sortOrder;
2643 /* Figure out how many bytes of space are required to store explicitly
2644 ** specified collation sequence names.
2646 for(i=0; i<pList->nExpr; i++){
2647 Expr *pExpr = pList->a[i].pExpr;
2648 if( pExpr ){
2649 CollSeq *pColl = pExpr->pColl;
2650 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2651 ** failure we have quit before reaching this point. */
2652 if( ALWAYS(pColl) ){
2653 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2659 ** Allocate the index structure.
2661 nName = sqlite3Strlen30(zName);
2662 nCol = pList->nExpr;
2663 pIndex = sqlite3DbMallocZero(db,
2664 sizeof(Index) + /* Index structure */
2665 sizeof(tRowcnt)*(nCol+1) + /* Index.aiRowEst */
2666 sizeof(int)*nCol + /* Index.aiColumn */
2667 sizeof(char *)*nCol + /* Index.azColl */
2668 sizeof(u8)*nCol + /* Index.aSortOrder */
2669 nName + 1 + /* Index.zName */
2670 nExtra /* Collation sequence names */
2672 if( db->mallocFailed ){
2673 goto exit_create_index;
2675 pIndex->aiRowEst = (tRowcnt*)(&pIndex[1]);
2676 pIndex->azColl = (char**)(&pIndex->aiRowEst[nCol+1]);
2677 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
2678 pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
2679 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2680 zExtra = (char *)(&pIndex->zName[nName+1]);
2681 memcpy(pIndex->zName, zName, nName+1);
2682 pIndex->pTable = pTab;
2683 pIndex->nColumn = pList->nExpr;
2684 pIndex->onError = (u8)onError;
2685 pIndex->autoIndex = (u8)(pName==0);
2686 pIndex->pSchema = db->aDb[iDb].pSchema;
2687 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2689 /* Check to see if we should honor DESC requests on index columns
2691 if( pDb->pSchema->file_format>=4 ){
2692 sortOrderMask = -1; /* Honor DESC */
2693 }else{
2694 sortOrderMask = 0; /* Ignore DESC */
2697 /* Scan the names of the columns of the table to be indexed and
2698 ** load the column indices into the Index structure. Report an error
2699 ** if any column is not found.
2701 ** TODO: Add a test to make sure that the same column is not named
2702 ** more than once within the same index. Only the first instance of
2703 ** the column will ever be used by the optimizer. Note that using the
2704 ** same column more than once cannot be an error because that would
2705 ** break backwards compatibility - it needs to be a warning.
2707 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2708 const char *zColName = pListItem->zName;
2709 Column *pTabCol;
2710 int requestedSortOrder;
2711 char *zColl; /* Collation sequence name */
2713 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2714 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
2716 if( j>=pTab->nCol ){
2717 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2718 pTab->zName, zColName);
2719 pParse->checkSchema = 1;
2720 goto exit_create_index;
2722 pIndex->aiColumn[i] = j;
2723 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2724 ** the way the "idxlist" non-terminal is constructed by the parser,
2725 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2726 ** must exist or else there must have been an OOM error. But if there
2727 ** was an OOM error, we would never reach this point. */
2728 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2729 int nColl;
2730 zColl = pListItem->pExpr->pColl->zName;
2731 nColl = sqlite3Strlen30(zColl) + 1;
2732 assert( nExtra>=nColl );
2733 memcpy(zExtra, zColl, nColl);
2734 zColl = zExtra;
2735 zExtra += nColl;
2736 nExtra -= nColl;
2737 }else{
2738 zColl = pTab->aCol[j].zColl;
2739 if( !zColl ){
2740 zColl = db->pDfltColl->zName;
2743 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
2744 goto exit_create_index;
2746 pIndex->azColl[i] = zColl;
2747 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
2748 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
2750 sqlite3DefaultRowEst(pIndex);
2752 if( pTab==pParse->pNewTable ){
2753 /* This routine has been called to create an automatic index as a
2754 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2755 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2756 ** i.e. one of:
2758 ** CREATE TABLE t(x PRIMARY KEY, y);
2759 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2761 ** Either way, check to see if the table already has such an index. If
2762 ** so, don't bother creating this one. This only applies to
2763 ** automatically created indices. Users can do as they wish with
2764 ** explicit indices.
2766 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2767 ** (and thus suppressing the second one) even if they have different
2768 ** sort orders.
2770 ** If there are different collating sequences or if the columns of
2771 ** the constraint occur in different orders, then the constraints are
2772 ** considered distinct and both result in separate indices.
2774 Index *pIdx;
2775 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2776 int k;
2777 assert( pIdx->onError!=OE_None );
2778 assert( pIdx->autoIndex );
2779 assert( pIndex->onError!=OE_None );
2781 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2782 for(k=0; k<pIdx->nColumn; k++){
2783 const char *z1;
2784 const char *z2;
2785 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2786 z1 = pIdx->azColl[k];
2787 z2 = pIndex->azColl[k];
2788 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
2790 if( k==pIdx->nColumn ){
2791 if( pIdx->onError!=pIndex->onError ){
2792 /* This constraint creates the same index as a previous
2793 ** constraint specified somewhere in the CREATE TABLE statement.
2794 ** However the ON CONFLICT clauses are different. If both this
2795 ** constraint and the previous equivalent constraint have explicit
2796 ** ON CONFLICT clauses this is an error. Otherwise, use the
2797 ** explicitly specified behaviour for the index.
2799 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2800 sqlite3ErrorMsg(pParse,
2801 "conflicting ON CONFLICT clauses specified", 0);
2803 if( pIdx->onError==OE_Default ){
2804 pIdx->onError = pIndex->onError;
2807 goto exit_create_index;
2812 /* Link the new Index structure to its table and to the other
2813 ** in-memory database structures.
2815 if( db->init.busy ){
2816 Index *p;
2817 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
2818 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
2819 pIndex->zName, sqlite3Strlen30(pIndex->zName),
2820 pIndex);
2821 if( p ){
2822 assert( p==pIndex ); /* Malloc must have failed */
2823 db->mallocFailed = 1;
2824 goto exit_create_index;
2826 db->flags |= SQLITE_InternChanges;
2827 if( pTblName!=0 ){
2828 pIndex->tnum = db->init.newTnum;
2832 /* If the db->init.busy is 0 then create the index on disk. This
2833 ** involves writing the index into the master table and filling in the
2834 ** index with the current table contents.
2836 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2837 ** command. db->init.busy is 1 when a database is opened and
2838 ** CREATE INDEX statements are read out of the master table. In
2839 ** the latter case the index already exists on disk, which is why
2840 ** we don't want to recreate it.
2842 ** If pTblName==0 it means this index is generated as a primary key
2843 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2844 ** has just been created, it contains no data and the index initialization
2845 ** step can be skipped.
2847 else{ /* if( db->init.busy==0 ) */
2848 Vdbe *v;
2849 char *zStmt;
2850 int iMem = ++pParse->nMem;
2852 v = sqlite3GetVdbe(pParse);
2853 if( v==0 ) goto exit_create_index;
2856 /* Create the rootpage for the index
2858 sqlite3BeginWriteOperation(pParse, 1, iDb);
2859 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
2861 /* Gather the complete text of the CREATE INDEX statement into
2862 ** the zStmt variable
2864 if( pStart ){
2865 assert( pEnd!=0 );
2866 /* A named index with an explicit CREATE INDEX statement */
2867 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
2868 onError==OE_None ? "" : " UNIQUE",
2869 (int)(pEnd->z - pName->z) + 1,
2870 pName->z);
2871 }else{
2872 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
2873 /* zStmt = sqlite3MPrintf(""); */
2874 zStmt = 0;
2877 /* Add an entry in sqlite_master for this index
2879 sqlite3NestedParse(pParse,
2880 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
2881 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2882 pIndex->zName,
2883 pTab->zName,
2884 iMem,
2885 zStmt
2887 sqlite3DbFree(db, zStmt);
2889 /* Fill the index with data and reparse the schema. Code an OP_Expire
2890 ** to invalidate all pre-compiled statements.
2892 if( pTblName ){
2893 sqlite3RefillIndex(pParse, pIndex, iMem);
2894 sqlite3ChangeCookie(pParse, iDb);
2895 sqlite3VdbeAddParseSchemaOp(v, iDb,
2896 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
2897 sqlite3VdbeAddOp1(v, OP_Expire, 0);
2901 /* When adding an index to the list of indices for a table, make
2902 ** sure all indices labeled OE_Replace come after all those labeled
2903 ** OE_Ignore. This is necessary for the correct constraint check
2904 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2905 ** UPDATE and INSERT statements.
2907 if( db->init.busy || pTblName==0 ){
2908 if( onError!=OE_Replace || pTab->pIndex==0
2909 || pTab->pIndex->onError==OE_Replace){
2910 pIndex->pNext = pTab->pIndex;
2911 pTab->pIndex = pIndex;
2912 }else{
2913 Index *pOther = pTab->pIndex;
2914 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2915 pOther = pOther->pNext;
2917 pIndex->pNext = pOther->pNext;
2918 pOther->pNext = pIndex;
2920 pRet = pIndex;
2921 pIndex = 0;
2924 /* Clean up before exiting */
2925 exit_create_index:
2926 if( pIndex ){
2927 sqlite3DbFree(db, pIndex->zColAff);
2928 sqlite3DbFree(db, pIndex);
2930 sqlite3ExprListDelete(db, pList);
2931 sqlite3SrcListDelete(db, pTblName);
2932 sqlite3DbFree(db, zName);
2933 return pRet;
2937 ** Fill the Index.aiRowEst[] array with default information - information
2938 ** to be used when we have not run the ANALYZE command.
2940 ** aiRowEst[0] is suppose to contain the number of elements in the index.
2941 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2942 ** number of rows in the table that match any particular value of the
2943 ** first column of the index. aiRowEst[2] is an estimate of the number
2944 ** of rows that match any particular combiniation of the first 2 columns
2945 ** of the index. And so forth. It must always be the case that
2947 ** aiRowEst[N]<=aiRowEst[N-1]
2948 ** aiRowEst[N]>=1
2950 ** Apart from that, we have little to go on besides intuition as to
2951 ** how aiRowEst[] should be initialized. The numbers generated here
2952 ** are based on typical values found in actual indices.
2954 void sqlite3DefaultRowEst(Index *pIdx){
2955 tRowcnt *a = pIdx->aiRowEst;
2956 int i;
2957 tRowcnt n;
2958 assert( a!=0 );
2959 a[0] = pIdx->pTable->nRowEst;
2960 if( a[0]<10 ) a[0] = 10;
2961 n = 10;
2962 for(i=1; i<=pIdx->nColumn; i++){
2963 a[i] = n;
2964 if( n>5 ) n--;
2966 if( pIdx->onError!=OE_None ){
2967 a[pIdx->nColumn] = 1;
2972 ** This routine will drop an existing named index. This routine
2973 ** implements the DROP INDEX statement.
2975 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
2976 Index *pIndex;
2977 Vdbe *v;
2978 sqlite3 *db = pParse->db;
2979 int iDb;
2981 assert( pParse->nErr==0 ); /* Never called with prior errors */
2982 if( db->mallocFailed ){
2983 goto exit_drop_index;
2985 assert( pName->nSrc==1 );
2986 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2987 goto exit_drop_index;
2989 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2990 if( pIndex==0 ){
2991 if( !ifExists ){
2992 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2993 }else{
2994 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2996 pParse->checkSchema = 1;
2997 goto exit_drop_index;
2999 if( pIndex->autoIndex ){
3000 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
3001 "or PRIMARY KEY constraint cannot be dropped", 0);
3002 goto exit_drop_index;
3004 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3005 #ifndef SQLITE_OMIT_AUTHORIZATION
3007 int code = SQLITE_DROP_INDEX;
3008 Table *pTab = pIndex->pTable;
3009 const char *zDb = db->aDb[iDb].zName;
3010 const char *zTab = SCHEMA_TABLE(iDb);
3011 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
3012 goto exit_drop_index;
3014 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
3015 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
3016 goto exit_drop_index;
3019 #endif
3021 /* Generate code to remove the index and from the master table */
3022 v = sqlite3GetVdbe(pParse);
3023 if( v ){
3024 sqlite3BeginWriteOperation(pParse, 1, iDb);
3025 sqlite3NestedParse(pParse,
3026 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
3027 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
3029 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
3030 sqlite3ChangeCookie(pParse, iDb);
3031 destroyRootPage(pParse, pIndex->tnum, iDb);
3032 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
3035 exit_drop_index:
3036 sqlite3SrcListDelete(db, pName);
3040 ** pArray is a pointer to an array of objects. Each object in the
3041 ** array is szEntry bytes in size. This routine allocates a new
3042 ** object on the end of the array.
3044 ** *pnEntry is the number of entries already in use. *pnAlloc is
3045 ** the previously allocated size of the array. initSize is the
3046 ** suggested initial array size allocation.
3048 ** The index of the new entry is returned in *pIdx.
3050 ** This routine returns a pointer to the array of objects. This
3051 ** might be the same as the pArray parameter or it might be a different
3052 ** pointer if the array was resized.
3054 void *sqlite3ArrayAllocate(
3055 sqlite3 *db, /* Connection to notify of malloc failures */
3056 void *pArray, /* Array of objects. Might be reallocated */
3057 int szEntry, /* Size of each object in the array */
3058 int initSize, /* Suggested initial allocation, in elements */
3059 int *pnEntry, /* Number of objects currently in use */
3060 int *pnAlloc, /* Current size of the allocation, in elements */
3061 int *pIdx /* Write the index of a new slot here */
3063 char *z;
3064 if( *pnEntry >= *pnAlloc ){
3065 void *pNew;
3066 int newSize;
3067 newSize = (*pnAlloc)*2 + initSize;
3068 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
3069 if( pNew==0 ){
3070 *pIdx = -1;
3071 return pArray;
3073 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
3074 pArray = pNew;
3076 z = (char*)pArray;
3077 memset(&z[*pnEntry * szEntry], 0, szEntry);
3078 *pIdx = *pnEntry;
3079 ++*pnEntry;
3080 return pArray;
3084 ** Append a new element to the given IdList. Create a new IdList if
3085 ** need be.
3087 ** A new IdList is returned, or NULL if malloc() fails.
3089 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
3090 int i;
3091 if( pList==0 ){
3092 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3093 if( pList==0 ) return 0;
3094 pList->nAlloc = 0;
3096 pList->a = sqlite3ArrayAllocate(
3098 pList->a,
3099 sizeof(pList->a[0]),
3101 &pList->nId,
3102 &pList->nAlloc,
3105 if( i<0 ){
3106 sqlite3IdListDelete(db, pList);
3107 return 0;
3109 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3110 return pList;
3114 ** Delete an IdList.
3116 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
3117 int i;
3118 if( pList==0 ) return;
3119 for(i=0; i<pList->nId; i++){
3120 sqlite3DbFree(db, pList->a[i].zName);
3122 sqlite3DbFree(db, pList->a);
3123 sqlite3DbFree(db, pList);
3127 ** Return the index in pList of the identifier named zId. Return -1
3128 ** if not found.
3130 int sqlite3IdListIndex(IdList *pList, const char *zName){
3131 int i;
3132 if( pList==0 ) return -1;
3133 for(i=0; i<pList->nId; i++){
3134 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3136 return -1;
3140 ** Expand the space allocated for the given SrcList object by
3141 ** creating nExtra new slots beginning at iStart. iStart is zero based.
3142 ** New slots are zeroed.
3144 ** For example, suppose a SrcList initially contains two entries: A,B.
3145 ** To append 3 new entries onto the end, do this:
3147 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3149 ** After the call above it would contain: A, B, nil, nil, nil.
3150 ** If the iStart argument had been 1 instead of 2, then the result
3151 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
3152 ** the iStart value would be 0. The result then would
3153 ** be: nil, nil, nil, A, B.
3155 ** If a memory allocation fails the SrcList is unchanged. The
3156 ** db->mallocFailed flag will be set to true.
3158 SrcList *sqlite3SrcListEnlarge(
3159 sqlite3 *db, /* Database connection to notify of OOM errors */
3160 SrcList *pSrc, /* The SrcList to be enlarged */
3161 int nExtra, /* Number of new slots to add to pSrc->a[] */
3162 int iStart /* Index in pSrc->a[] of first new slot */
3164 int i;
3166 /* Sanity checking on calling parameters */
3167 assert( iStart>=0 );
3168 assert( nExtra>=1 );
3169 assert( pSrc!=0 );
3170 assert( iStart<=pSrc->nSrc );
3172 /* Allocate additional space if needed */
3173 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3174 SrcList *pNew;
3175 int nAlloc = pSrc->nSrc+nExtra;
3176 int nGot;
3177 pNew = sqlite3DbRealloc(db, pSrc,
3178 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3179 if( pNew==0 ){
3180 assert( db->mallocFailed );
3181 return pSrc;
3183 pSrc = pNew;
3184 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3185 pSrc->nAlloc = (u16)nGot;
3188 /* Move existing slots that come after the newly inserted slots
3189 ** out of the way */
3190 for(i=pSrc->nSrc-1; i>=iStart; i--){
3191 pSrc->a[i+nExtra] = pSrc->a[i];
3193 pSrc->nSrc += (i16)nExtra;
3195 /* Zero the newly allocated slots */
3196 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3197 for(i=iStart; i<iStart+nExtra; i++){
3198 pSrc->a[i].iCursor = -1;
3201 /* Return a pointer to the enlarged SrcList */
3202 return pSrc;
3207 ** Append a new table name to the given SrcList. Create a new SrcList if
3208 ** need be. A new entry is created in the SrcList even if pTable is NULL.
3210 ** A SrcList is returned, or NULL if there is an OOM error. The returned
3211 ** SrcList might be the same as the SrcList that was input or it might be
3212 ** a new one. If an OOM error does occurs, then the prior value of pList
3213 ** that is input to this routine is automatically freed.
3215 ** If pDatabase is not null, it means that the table has an optional
3216 ** database name prefix. Like this: "database.table". The pDatabase
3217 ** points to the table name and the pTable points to the database name.
3218 ** The SrcList.a[].zName field is filled with the table name which might
3219 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3220 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3221 ** or with NULL if no database is specified.
3223 ** In other words, if call like this:
3225 ** sqlite3SrcListAppend(D,A,B,0);
3227 ** Then B is a table name and the database name is unspecified. If called
3228 ** like this:
3230 ** sqlite3SrcListAppend(D,A,B,C);
3232 ** Then C is the table name and B is the database name. If C is defined
3233 ** then so is B. In other words, we never have a case where:
3235 ** sqlite3SrcListAppend(D,A,0,C);
3237 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3238 ** before being added to the SrcList.
3240 SrcList *sqlite3SrcListAppend(
3241 sqlite3 *db, /* Connection to notify of malloc failures */
3242 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3243 Token *pTable, /* Table to append */
3244 Token *pDatabase /* Database of the table */
3246 struct SrcList_item *pItem;
3247 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
3248 if( pList==0 ){
3249 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
3250 if( pList==0 ) return 0;
3251 pList->nAlloc = 1;
3253 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3254 if( db->mallocFailed ){
3255 sqlite3SrcListDelete(db, pList);
3256 return 0;
3258 pItem = &pList->a[pList->nSrc-1];
3259 if( pDatabase && pDatabase->z==0 ){
3260 pDatabase = 0;
3262 if( pDatabase ){
3263 Token *pTemp = pDatabase;
3264 pDatabase = pTable;
3265 pTable = pTemp;
3267 pItem->zName = sqlite3NameFromToken(db, pTable);
3268 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
3269 return pList;
3273 ** Assign VdbeCursor index numbers to all tables in a SrcList
3275 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
3276 int i;
3277 struct SrcList_item *pItem;
3278 assert(pList || pParse->db->mallocFailed );
3279 if( pList ){
3280 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3281 if( pItem->iCursor>=0 ) break;
3282 pItem->iCursor = pParse->nTab++;
3283 if( pItem->pSelect ){
3284 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3291 ** Delete an entire SrcList including all its substructure.
3293 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
3294 int i;
3295 struct SrcList_item *pItem;
3296 if( pList==0 ) return;
3297 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
3298 sqlite3DbFree(db, pItem->zDatabase);
3299 sqlite3DbFree(db, pItem->zName);
3300 sqlite3DbFree(db, pItem->zAlias);
3301 sqlite3DbFree(db, pItem->zIndex);
3302 sqlite3DeleteTable(db, pItem->pTab);
3303 sqlite3SelectDelete(db, pItem->pSelect);
3304 sqlite3ExprDelete(db, pItem->pOn);
3305 sqlite3IdListDelete(db, pItem->pUsing);
3307 sqlite3DbFree(db, pList);
3311 ** This routine is called by the parser to add a new term to the
3312 ** end of a growing FROM clause. The "p" parameter is the part of
3313 ** the FROM clause that has already been constructed. "p" is NULL
3314 ** if this is the first term of the FROM clause. pTable and pDatabase
3315 ** are the name of the table and database named in the FROM clause term.
3316 ** pDatabase is NULL if the database name qualifier is missing - the
3317 ** usual case. If the term has a alias, then pAlias points to the
3318 ** alias token. If the term is a subquery, then pSubquery is the
3319 ** SELECT statement that the subquery encodes. The pTable and
3320 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3321 ** parameters are the content of the ON and USING clauses.
3323 ** Return a new SrcList which encodes is the FROM with the new
3324 ** term added.
3326 SrcList *sqlite3SrcListAppendFromTerm(
3327 Parse *pParse, /* Parsing context */
3328 SrcList *p, /* The left part of the FROM clause already seen */
3329 Token *pTable, /* Name of the table to add to the FROM clause */
3330 Token *pDatabase, /* Name of the database containing pTable */
3331 Token *pAlias, /* The right-hand side of the AS subexpression */
3332 Select *pSubquery, /* A subquery used in place of a table name */
3333 Expr *pOn, /* The ON clause of a join */
3334 IdList *pUsing /* The USING clause of a join */
3336 struct SrcList_item *pItem;
3337 sqlite3 *db = pParse->db;
3338 if( !p && (pOn || pUsing) ){
3339 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3340 (pOn ? "ON" : "USING")
3342 goto append_from_error;
3344 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
3345 if( p==0 || NEVER(p->nSrc==0) ){
3346 goto append_from_error;
3348 pItem = &p->a[p->nSrc-1];
3349 assert( pAlias!=0 );
3350 if( pAlias->n ){
3351 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
3353 pItem->pSelect = pSubquery;
3354 pItem->pOn = pOn;
3355 pItem->pUsing = pUsing;
3356 return p;
3358 append_from_error:
3359 assert( p==0 );
3360 sqlite3ExprDelete(db, pOn);
3361 sqlite3IdListDelete(db, pUsing);
3362 sqlite3SelectDelete(db, pSubquery);
3363 return 0;
3367 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3368 ** element of the source-list passed as the second argument.
3370 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3371 assert( pIndexedBy!=0 );
3372 if( p && ALWAYS(p->nSrc>0) ){
3373 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3374 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3375 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3376 /* A "NOT INDEXED" clause was supplied. See parse.y
3377 ** construct "indexed_opt" for details. */
3378 pItem->notIndexed = 1;
3379 }else{
3380 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3386 ** When building up a FROM clause in the parser, the join operator
3387 ** is initially attached to the left operand. But the code generator
3388 ** expects the join operator to be on the right operand. This routine
3389 ** Shifts all join operators from left to right for an entire FROM
3390 ** clause.
3392 ** Example: Suppose the join is like this:
3394 ** A natural cross join B
3396 ** The operator is "natural cross join". The A and B operands are stored
3397 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
3398 ** operator with A. This routine shifts that operator over to B.
3400 void sqlite3SrcListShiftJoinType(SrcList *p){
3401 if( p ){
3402 int i;
3403 assert( p->a || p->nSrc==0 );
3404 for(i=p->nSrc-1; i>0; i--){
3405 p->a[i].jointype = p->a[i-1].jointype;
3407 p->a[0].jointype = 0;
3412 ** Begin a transaction
3414 void sqlite3BeginTransaction(Parse *pParse, int type){
3415 sqlite3 *db;
3416 Vdbe *v;
3417 int i;
3419 assert( pParse!=0 );
3420 db = pParse->db;
3421 assert( db!=0 );
3422 /* if( db->aDb[0].pBt==0 ) return; */
3423 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3424 return;
3426 v = sqlite3GetVdbe(pParse);
3427 if( !v ) return;
3428 if( type!=TK_DEFERRED ){
3429 for(i=0; i<db->nDb; i++){
3430 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
3431 sqlite3VdbeUsesBtree(v, i);
3434 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
3438 ** Commit a transaction
3440 void sqlite3CommitTransaction(Parse *pParse){
3441 Vdbe *v;
3443 assert( pParse!=0 );
3444 assert( pParse->db!=0 );
3445 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3446 return;
3448 v = sqlite3GetVdbe(pParse);
3449 if( v ){
3450 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
3455 ** Rollback a transaction
3457 void sqlite3RollbackTransaction(Parse *pParse){
3458 Vdbe *v;
3460 assert( pParse!=0 );
3461 assert( pParse->db!=0 );
3462 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3463 return;
3465 v = sqlite3GetVdbe(pParse);
3466 if( v ){
3467 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
3472 ** This function is called by the parser when it parses a command to create,
3473 ** release or rollback an SQL savepoint.
3475 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
3476 char *zName = sqlite3NameFromToken(pParse->db, pName);
3477 if( zName ){
3478 Vdbe *v = sqlite3GetVdbe(pParse);
3479 #ifndef SQLITE_OMIT_AUTHORIZATION
3480 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3481 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3482 #endif
3483 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3484 sqlite3DbFree(pParse->db, zName);
3485 return;
3487 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
3492 ** Make sure the TEMP database is open and available for use. Return
3493 ** the number of errors. Leave any error messages in the pParse structure.
3495 int sqlite3OpenTempDatabase(Parse *pParse){
3496 sqlite3 *db = pParse->db;
3497 if( db->aDb[1].pBt==0 && !pParse->explain ){
3498 int rc;
3499 Btree *pBt;
3500 static const int flags =
3501 SQLITE_OPEN_READWRITE |
3502 SQLITE_OPEN_CREATE |
3503 SQLITE_OPEN_EXCLUSIVE |
3504 SQLITE_OPEN_DELETEONCLOSE |
3505 SQLITE_OPEN_TEMP_DB;
3507 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
3508 if( rc!=SQLITE_OK ){
3509 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3510 "file for storing temporary tables");
3511 pParse->rc = rc;
3512 return 1;
3514 db->aDb[1].pBt = pBt;
3515 assert( db->aDb[1].pSchema );
3516 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3517 db->mallocFailed = 1;
3518 return 1;
3521 return 0;
3525 ** Generate VDBE code that will verify the schema cookie and start
3526 ** a read-transaction for all named database files.
3528 ** It is important that all schema cookies be verified and all
3529 ** read transactions be started before anything else happens in
3530 ** the VDBE program. But this routine can be called after much other
3531 ** code has been generated. So here is what we do:
3533 ** The first time this routine is called, we code an OP_Goto that
3534 ** will jump to a subroutine at the end of the program. Then we
3535 ** record every database that needs its schema verified in the
3536 ** pParse->cookieMask field. Later, after all other code has been
3537 ** generated, the subroutine that does the cookie verifications and
3538 ** starts the transactions will be coded and the OP_Goto P2 value
3539 ** will be made to point to that subroutine. The generation of the
3540 ** cookie verification subroutine code happens in sqlite3FinishCoding().
3542 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3543 ** schema on any databases. This can be used to position the OP_Goto
3544 ** early in the code, before we know if any database tables will be used.
3546 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3547 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3549 if( pToplevel->cookieGoto==0 ){
3550 Vdbe *v = sqlite3GetVdbe(pToplevel);
3551 if( v==0 ) return; /* This only happens if there was a prior error */
3552 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
3554 if( iDb>=0 ){
3555 sqlite3 *db = pToplevel->db;
3556 yDbMask mask;
3558 assert( iDb<db->nDb );
3559 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3560 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3561 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3562 mask = ((yDbMask)1)<<iDb;
3563 if( (pToplevel->cookieMask & mask)==0 ){
3564 pToplevel->cookieMask |= mask;
3565 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3566 if( !OMIT_TEMPDB && iDb==1 ){
3567 sqlite3OpenTempDatabase(pToplevel);
3574 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3575 ** attached database. Otherwise, invoke it for the database named zDb only.
3577 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3578 sqlite3 *db = pParse->db;
3579 int i;
3580 for(i=0; i<db->nDb; i++){
3581 Db *pDb = &db->aDb[i];
3582 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3583 sqlite3CodeVerifySchema(pParse, i);
3589 ** Generate VDBE code that prepares for doing an operation that
3590 ** might change the database.
3592 ** This routine starts a new transaction if we are not already within
3593 ** a transaction. If we are already within a transaction, then a checkpoint
3594 ** is set if the setStatement parameter is true. A checkpoint should
3595 ** be set for operations that might fail (due to a constraint) part of
3596 ** the way through and which will need to undo some writes without having to
3597 ** rollback the whole transaction. For operations where all constraints
3598 ** can be checked before any changes are made to the database, it is never
3599 ** necessary to undo a write and the checkpoint should not be set.
3601 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3602 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3603 sqlite3CodeVerifySchema(pParse, iDb);
3604 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
3605 pToplevel->isMultiWrite |= setStatement;
3609 ** Indicate that the statement currently under construction might write
3610 ** more than one entry (example: deleting one row then inserting another,
3611 ** inserting multiple rows in a table, or inserting a row and index entries.)
3612 ** If an abort occurs after some of these writes have completed, then it will
3613 ** be necessary to undo the completed writes.
3615 void sqlite3MultiWrite(Parse *pParse){
3616 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3617 pToplevel->isMultiWrite = 1;
3621 ** The code generator calls this routine if is discovers that it is
3622 ** possible to abort a statement prior to completion. In order to
3623 ** perform this abort without corrupting the database, we need to make
3624 ** sure that the statement is protected by a statement transaction.
3626 ** Technically, we only need to set the mayAbort flag if the
3627 ** isMultiWrite flag was previously set. There is a time dependency
3628 ** such that the abort must occur after the multiwrite. This makes
3629 ** some statements involving the REPLACE conflict resolution algorithm
3630 ** go a little faster. But taking advantage of this time dependency
3631 ** makes it more difficult to prove that the code is correct (in
3632 ** particular, it prevents us from writing an effective
3633 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
3634 ** to take the safe route and skip the optimization.
3636 void sqlite3MayAbort(Parse *pParse){
3637 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3638 pToplevel->mayAbort = 1;
3642 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3643 ** error. The onError parameter determines which (if any) of the statement
3644 ** and/or current transaction is rolled back.
3646 void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3647 Vdbe *v = sqlite3GetVdbe(pParse);
3648 if( onError==OE_Abort ){
3649 sqlite3MayAbort(pParse);
3651 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
3655 ** Check to see if pIndex uses the collating sequence pColl. Return
3656 ** true if it does and false if it does not.
3658 #ifndef SQLITE_OMIT_REINDEX
3659 static int collationMatch(const char *zColl, Index *pIndex){
3660 int i;
3661 assert( zColl!=0 );
3662 for(i=0; i<pIndex->nColumn; i++){
3663 const char *z = pIndex->azColl[i];
3664 assert( z!=0 );
3665 if( 0==sqlite3StrICmp(z, zColl) ){
3666 return 1;
3669 return 0;
3671 #endif
3674 ** Recompute all indices of pTab that use the collating sequence pColl.
3675 ** If pColl==0 then recompute all indices of pTab.
3677 #ifndef SQLITE_OMIT_REINDEX
3678 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
3679 Index *pIndex; /* An index associated with pTab */
3681 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
3682 if( zColl==0 || collationMatch(zColl, pIndex) ){
3683 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3684 sqlite3BeginWriteOperation(pParse, 0, iDb);
3685 sqlite3RefillIndex(pParse, pIndex, -1);
3689 #endif
3692 ** Recompute all indices of all tables in all databases where the
3693 ** indices use the collating sequence pColl. If pColl==0 then recompute
3694 ** all indices everywhere.
3696 #ifndef SQLITE_OMIT_REINDEX
3697 static void reindexDatabases(Parse *pParse, char const *zColl){
3698 Db *pDb; /* A single database */
3699 int iDb; /* The database index number */
3700 sqlite3 *db = pParse->db; /* The database connection */
3701 HashElem *k; /* For looping over tables in pDb */
3702 Table *pTab; /* A table in the database */
3704 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
3705 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3706 assert( pDb!=0 );
3707 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
3708 pTab = (Table*)sqliteHashData(k);
3709 reindexTable(pParse, pTab, zColl);
3713 #endif
3716 ** Generate code for the REINDEX command.
3718 ** REINDEX -- 1
3719 ** REINDEX <collation> -- 2
3720 ** REINDEX ?<database>.?<tablename> -- 3
3721 ** REINDEX ?<database>.?<indexname> -- 4
3723 ** Form 1 causes all indices in all attached databases to be rebuilt.
3724 ** Form 2 rebuilds all indices in all databases that use the named
3725 ** collating function. Forms 3 and 4 rebuild the named index or all
3726 ** indices associated with the named table.
3728 #ifndef SQLITE_OMIT_REINDEX
3729 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3730 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3731 char *z; /* Name of a table or index */
3732 const char *zDb; /* Name of the database */
3733 Table *pTab; /* A table in the database */
3734 Index *pIndex; /* An index associated with pTab */
3735 int iDb; /* The database index number */
3736 sqlite3 *db = pParse->db; /* The database connection */
3737 Token *pObjName; /* Name of the table or index to be reindexed */
3739 /* Read the database schema. If an error occurs, leave an error message
3740 ** and code in pParse and return NULL. */
3741 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3742 return;
3745 if( pName1==0 ){
3746 reindexDatabases(pParse, 0);
3747 return;
3748 }else if( NEVER(pName2==0) || pName2->z==0 ){
3749 char *zColl;
3750 assert( pName1->z );
3751 zColl = sqlite3NameFromToken(pParse->db, pName1);
3752 if( !zColl ) return;
3753 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
3754 if( pColl ){
3755 reindexDatabases(pParse, zColl);
3756 sqlite3DbFree(db, zColl);
3757 return;
3759 sqlite3DbFree(db, zColl);
3761 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3762 if( iDb<0 ) return;
3763 z = sqlite3NameFromToken(db, pObjName);
3764 if( z==0 ) return;
3765 zDb = db->aDb[iDb].zName;
3766 pTab = sqlite3FindTable(db, z, zDb);
3767 if( pTab ){
3768 reindexTable(pParse, pTab, 0);
3769 sqlite3DbFree(db, z);
3770 return;
3772 pIndex = sqlite3FindIndex(db, z, zDb);
3773 sqlite3DbFree(db, z);
3774 if( pIndex ){
3775 sqlite3BeginWriteOperation(pParse, 0, iDb);
3776 sqlite3RefillIndex(pParse, pIndex, -1);
3777 return;
3779 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3781 #endif
3784 ** Return a dynamicly allocated KeyInfo structure that can be used
3785 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3787 ** If successful, a pointer to the new structure is returned. In this case
3788 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
3789 ** pointer. If an error occurs (out of memory or missing collation
3790 ** sequence), NULL is returned and the state of pParse updated to reflect
3791 ** the error.
3793 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3794 int i;
3795 int nCol = pIdx->nColumn;
3796 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3797 sqlite3 *db = pParse->db;
3798 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
3800 if( pKey ){
3801 pKey->db = pParse->db;
3802 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3803 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3804 for(i=0; i<nCol; i++){
3805 char *zColl = pIdx->azColl[i];
3806 assert( zColl );
3807 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
3808 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3810 pKey->nField = (u16)nCol;
3813 if( pParse->nErr ){
3814 sqlite3DbFree(db, pKey);
3815 pKey = 0;
3817 return pKey;