00001 /* 00002 ** 2001 September 15 00003 ** 00004 ** The author disclaims copyright to this source code. In place of 00005 ** a legal notice, here is a blessing: 00006 ** 00007 ** May you do good and not evil. 00008 ** May you find forgiveness for yourself and forgive others. 00009 ** May you share freely, never taking more than you give. 00010 ** 00011 ************************************************************************* 00012 ** This file contains C code routines that are called by the SQLite parser 00013 ** when syntax rules are reduced. The routines in this file handle the 00014 ** following kinds of SQL syntax: 00015 ** 00016 ** CREATE TABLE 00017 ** DROP TABLE 00018 ** CREATE INDEX 00019 ** DROP INDEX 00020 ** creating ID lists 00021 ** BEGIN TRANSACTION 00022 ** COMMIT 00023 ** ROLLBACK 00024 ** 00025 ** $Id: build.c,v 1.501 2008/11/11 18:28:59 drh Exp $ 00026 */ 00027 #include "sqliteInt.h" 00028 #include <ctype.h> 00029 00030 /* 00031 ** This routine is called when a new SQL statement is beginning to 00032 ** be parsed. Initialize the pParse structure as needed. 00033 */ 00034 void sqlite3BeginParse(Parse *pParse, int explainFlag){ 00035 pParse->explain = explainFlag; 00036 pParse->nVar = 0; 00037 } 00038 00039 #ifndef SQLITE_OMIT_SHARED_CACHE 00040 /* 00041 ** The TableLock structure is only used by the sqlite3TableLock() and 00042 ** codeTableLocks() functions. 00043 */ 00044 struct TableLock { 00045 int iDb; /* The database containing the table to be locked */ 00046 int iTab; /* The root page of the table to be locked */ 00047 u8 isWriteLock; /* True for write lock. False for a read lock */ 00048 const char *zName; /* Name of the table */ 00049 }; 00050 00051 /* 00052 ** Record the fact that we want to lock a table at run-time. 00053 ** 00054 ** The table to be locked has root page iTab and is found in database iDb. 00055 ** A read or a write lock can be taken depending on isWritelock. 00056 ** 00057 ** This routine just records the fact that the lock is desired. The 00058 ** code to make the lock occur is generated by a later call to 00059 ** codeTableLocks() which occurs during sqlite3FinishCoding(). 00060 */ 00061 void sqlite3TableLock( 00062 Parse *pParse, /* Parsing context */ 00063 int iDb, /* Index of the database containing the table to lock */ 00064 int iTab, /* Root page number of the table to be locked */ 00065 u8 isWriteLock, /* True for a write lock */ 00066 const char *zName /* Name of the table to be locked */ 00067 ){ 00068 int i; 00069 int nBytes; 00070 TableLock *p; 00071 00072 if( iDb<0 ){ 00073 return; 00074 } 00075 00076 for(i=0; i<pParse->nTableLock; i++){ 00077 p = &pParse->aTableLock[i]; 00078 if( p->iDb==iDb && p->iTab==iTab ){ 00079 p->isWriteLock = (p->isWriteLock || isWriteLock); 00080 return; 00081 } 00082 } 00083 00084 nBytes = sizeof(TableLock) * (pParse->nTableLock+1); 00085 pParse->aTableLock = 00086 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes); 00087 if( pParse->aTableLock ){ 00088 p = &pParse->aTableLock[pParse->nTableLock++]; 00089 p->iDb = iDb; 00090 p->iTab = iTab; 00091 p->isWriteLock = isWriteLock; 00092 p->zName = zName; 00093 }else{ 00094 pParse->nTableLock = 0; 00095 pParse->db->mallocFailed = 1; 00096 } 00097 } 00098 00099 /* 00100 ** Code an OP_TableLock instruction for each table locked by the 00101 ** statement (configured by calls to sqlite3TableLock()). 00102 */ 00103 static void codeTableLocks(Parse *pParse){ 00104 int i; 00105 Vdbe *pVdbe; 00106 00107 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){ 00108 return; 00109 } 00110 00111 for(i=0; i<pParse->nTableLock; i++){ 00112 TableLock *p = &pParse->aTableLock[i]; 00113 int p1 = p->iDb; 00114 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 00115 p->zName, P4_STATIC); 00116 } 00117 } 00118 #else 00119 #define codeTableLocks(x) 00120 #endif 00121 00122 /* 00123 ** This routine is called after a single SQL statement has been 00124 ** parsed and a VDBE program to execute that statement has been 00125 ** prepared. This routine puts the finishing touches on the 00126 ** VDBE program and resets the pParse structure for the next 00127 ** parse. 00128 ** 00129 ** Note that if an error occurred, it might be the case that 00130 ** no VDBE code was generated. 00131 */ 00132 void sqlite3FinishCoding(Parse *pParse){ 00133 sqlite3 *db; 00134 Vdbe *v; 00135 00136 db = pParse->db; 00137 if( db->mallocFailed ) return; 00138 if( pParse->nested ) return; 00139 if( pParse->nErr ) return; 00140 00141 /* Begin by generating some termination code at the end of the 00142 ** vdbe program 00143 */ 00144 v = sqlite3GetVdbe(pParse); 00145 if( v ){ 00146 sqlite3VdbeAddOp0(v, OP_Halt); 00147 00148 /* The cookie mask contains one bit for each database file open. 00149 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 00150 ** set for each database that is used. Generate code to start a 00151 ** transaction on each used database and to verify the schema cookie 00152 ** on each used database. 00153 */ 00154 if( pParse->cookieGoto>0 ){ 00155 u32 mask; 00156 int iDb; 00157 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); 00158 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){ 00159 if( (mask & pParse->cookieMask)==0 ) continue; 00160 sqlite3VdbeUsesBtree(v, iDb); 00161 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); 00162 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); 00163 } 00164 #ifndef SQLITE_OMIT_VIRTUALTABLE 00165 { 00166 int i; 00167 for(i=0; i<pParse->nVtabLock; i++){ 00168 char *vtab = (char *)pParse->apVtabLock[i]->pVtab; 00169 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 00170 } 00171 pParse->nVtabLock = 0; 00172 } 00173 #endif 00174 00175 /* Once all the cookies have been verified and transactions opened, 00176 ** obtain the required table-locks. This is a no-op unless the 00177 ** shared-cache feature is enabled. 00178 */ 00179 codeTableLocks(pParse); 00180 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); 00181 } 00182 00183 #ifndef SQLITE_OMIT_TRACE 00184 if( !db->init.busy ){ 00185 /* Change the P4 argument of the first opcode (which will always be 00186 ** an OP_Trace) to be the complete text of the current SQL statement. 00187 */ 00188 VdbeOp *pOp = sqlite3VdbeGetOp(v, 0); 00189 if( pOp && pOp->opcode==OP_Trace ){ 00190 sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql); 00191 } 00192 } 00193 #endif /* SQLITE_OMIT_TRACE */ 00194 } 00195 00196 00197 /* Get the VDBE program ready for execution 00198 */ 00199 if( v && pParse->nErr==0 && !db->mallocFailed ){ 00200 #ifdef SQLITE_DEBUG 00201 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; 00202 sqlite3VdbeTrace(v, trace); 00203 #endif 00204 assert( pParse->disableColCache==0 ); /* Disables and re-enables match */ 00205 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3, 00206 pParse->nTab+3, pParse->explain); 00207 pParse->rc = SQLITE_DONE; 00208 pParse->colNamesSet = 0; 00209 }else if( pParse->rc==SQLITE_OK ){ 00210 pParse->rc = SQLITE_ERROR; 00211 } 00212 pParse->nTab = 0; 00213 pParse->nMem = 0; 00214 pParse->nSet = 0; 00215 pParse->nVar = 0; 00216 pParse->cookieMask = 0; 00217 pParse->cookieGoto = 0; 00218 } 00219 00220 /* 00221 ** Run the parser and code generator recursively in order to generate 00222 ** code for the SQL statement given onto the end of the pParse context 00223 ** currently under construction. When the parser is run recursively 00224 ** this way, the final OP_Halt is not appended and other initialization 00225 ** and finalization steps are omitted because those are handling by the 00226 ** outermost parser. 00227 ** 00228 ** Not everything is nestable. This facility is designed to permit 00229 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use 00230 ** care if you decide to try to use this routine for some other purposes. 00231 */ 00232 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 00233 va_list ap; 00234 char *zSql; 00235 char *zErrMsg = 0; 00236 sqlite3 *db = pParse->db; 00237 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) 00238 char saveBuf[SAVE_SZ]; 00239 00240 if( pParse->nErr ) return; 00241 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 00242 va_start(ap, zFormat); 00243 zSql = sqlite3VMPrintf(db, zFormat, ap); 00244 va_end(ap); 00245 if( zSql==0 ){ 00246 return; /* A malloc must have failed */ 00247 } 00248 pParse->nested++; 00249 memcpy(saveBuf, &pParse->nVar, SAVE_SZ); 00250 memset(&pParse->nVar, 0, SAVE_SZ); 00251 sqlite3RunParser(pParse, zSql, &zErrMsg); 00252 sqlite3DbFree(db, zErrMsg); 00253 sqlite3DbFree(db, zSql); 00254 memcpy(&pParse->nVar, saveBuf, SAVE_SZ); 00255 pParse->nested--; 00256 } 00257 00258 /* 00259 ** Locate the in-memory structure that describes a particular database 00260 ** table given the name of that table and (optionally) the name of the 00261 ** database containing the table. Return NULL if not found. 00262 ** 00263 ** If zDatabase is 0, all databases are searched for the table and the 00264 ** first matching table is returned. (No checking for duplicate table 00265 ** names is done.) The search order is TEMP first, then MAIN, then any 00266 ** auxiliary databases added using the ATTACH command. 00267 ** 00268 ** See also sqlite3LocateTable(). 00269 */ 00270 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 00271 Table *p = 0; 00272 int i; 00273 int nName; 00274 assert( zName!=0 ); 00275 nName = sqlite3Strlen(db, zName) + 1; 00276 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 00277 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 00278 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; 00279 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName); 00280 if( p ) break; 00281 } 00282 return p; 00283 } 00284 00285 /* 00286 ** Locate the in-memory structure that describes a particular database 00287 ** table given the name of that table and (optionally) the name of the 00288 ** database containing the table. Return NULL if not found. Also leave an 00289 ** error message in pParse->zErrMsg. 00290 ** 00291 ** The difference between this routine and sqlite3FindTable() is that this 00292 ** routine leaves an error message in pParse->zErrMsg where 00293 ** sqlite3FindTable() does not. 00294 */ 00295 Table *sqlite3LocateTable( 00296 Parse *pParse, /* context in which to report errors */ 00297 int isView, /* True if looking for a VIEW rather than a TABLE */ 00298 const char *zName, /* Name of the table we are looking for */ 00299 const char *zDbase /* Name of the database. Might be NULL */ 00300 ){ 00301 Table *p; 00302 00303 /* Read the database schema. If an error occurs, leave an error message 00304 ** and code in pParse and return NULL. */ 00305 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 00306 return 0; 00307 } 00308 00309 p = sqlite3FindTable(pParse->db, zName, zDbase); 00310 if( p==0 ){ 00311 const char *zMsg = isView ? "no such view" : "no such table"; 00312 if( zDbase ){ 00313 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 00314 }else{ 00315 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 00316 } 00317 pParse->checkSchema = 1; 00318 } 00319 return p; 00320 } 00321 00322 /* 00323 ** Locate the in-memory structure that describes 00324 ** a particular index given the name of that index 00325 ** and the name of the database that contains the index. 00326 ** Return NULL if not found. 00327 ** 00328 ** If zDatabase is 0, all databases are searched for the 00329 ** table and the first matching index is returned. (No checking 00330 ** for duplicate index names is done.) The search order is 00331 ** TEMP first, then MAIN, then any auxiliary databases added 00332 ** using the ATTACH command. 00333 */ 00334 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 00335 Index *p = 0; 00336 int i; 00337 int nName = sqlite3Strlen(db, zName)+1; 00338 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 00339 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 00340 Schema *pSchema = db->aDb[j].pSchema; 00341 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; 00342 assert( pSchema || (j==1 && !db->aDb[1].pBt) ); 00343 if( pSchema ){ 00344 p = sqlite3HashFind(&pSchema->idxHash, zName, nName); 00345 } 00346 if( p ) break; 00347 } 00348 return p; 00349 } 00350 00351 /* 00352 ** Reclaim the memory used by an index 00353 */ 00354 static void freeIndex(Index *p){ 00355 sqlite3 *db = p->pTable->db; 00356 sqlite3DbFree(db, p->zColAff); 00357 sqlite3DbFree(db, p); 00358 } 00359 00360 /* 00361 ** Remove the given index from the index hash table, and free 00362 ** its memory structures. 00363 ** 00364 ** The index is removed from the database hash tables but 00365 ** it is not unlinked from the Table that it indexes. 00366 ** Unlinking from the Table must be done by the calling function. 00367 */ 00368 static void sqliteDeleteIndex(Index *p){ 00369 Index *pOld; 00370 const char *zName = p->zName; 00371 00372 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0); 00373 assert( pOld==0 || pOld==p ); 00374 freeIndex(p); 00375 } 00376 00377 /* 00378 ** For the index called zIdxName which is found in the database iDb, 00379 ** unlike that index from its Table then remove the index from 00380 ** the index hash table and free all memory structures associated 00381 ** with the index. 00382 */ 00383 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 00384 Index *pIndex; 00385 int len; 00386 Hash *pHash = &db->aDb[iDb].pSchema->idxHash; 00387 00388 len = sqlite3Strlen(db, zIdxName); 00389 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0); 00390 if( pIndex ){ 00391 if( pIndex->pTable->pIndex==pIndex ){ 00392 pIndex->pTable->pIndex = pIndex->pNext; 00393 }else{ 00394 Index *p; 00395 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){} 00396 if( p && p->pNext==pIndex ){ 00397 p->pNext = pIndex->pNext; 00398 } 00399 } 00400 freeIndex(pIndex); 00401 } 00402 db->flags |= SQLITE_InternChanges; 00403 } 00404 00405 /* 00406 ** Erase all schema information from the in-memory hash tables of 00407 ** a single database. This routine is called to reclaim memory 00408 ** before the database closes. It is also called during a rollback 00409 ** if there were schema changes during the transaction or if a 00410 ** schema-cookie mismatch occurs. 00411 ** 00412 ** If iDb<=0 then reset the internal schema tables for all database 00413 ** files. If iDb>=2 then reset the internal schema for only the 00414 ** single file indicated. 00415 */ 00416 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ 00417 int i, j; 00418 assert( iDb>=0 && iDb<db->nDb ); 00419 00420 if( iDb==0 ){ 00421 sqlite3BtreeEnterAll(db); 00422 } 00423 for(i=iDb; i<db->nDb; i++){ 00424 Db *pDb = &db->aDb[i]; 00425 if( pDb->pSchema ){ 00426 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt))); 00427 sqlite3SchemaFree(pDb->pSchema); 00428 } 00429 if( iDb>0 ) return; 00430 } 00431 assert( iDb==0 ); 00432 db->flags &= ~SQLITE_InternChanges; 00433 sqlite3BtreeLeaveAll(db); 00434 00435 /* If one or more of the auxiliary database files has been closed, 00436 ** then remove them from the auxiliary database list. We take the 00437 ** opportunity to do this here since we have just deleted all of the 00438 ** schema hash tables and therefore do not have to make any changes 00439 ** to any of those tables. 00440 */ 00441 for(i=0; i<db->nDb; i++){ 00442 struct Db *pDb = &db->aDb[i]; 00443 if( pDb->pBt==0 ){ 00444 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux); 00445 pDb->pAux = 0; 00446 } 00447 } 00448 for(i=j=2; i<db->nDb; i++){ 00449 struct Db *pDb = &db->aDb[i]; 00450 if( pDb->pBt==0 ){ 00451 sqlite3DbFree(db, pDb->zName); 00452 pDb->zName = 0; 00453 continue; 00454 } 00455 if( j<i ){ 00456 db->aDb[j] = db->aDb[i]; 00457 } 00458 j++; 00459 } 00460 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); 00461 db->nDb = j; 00462 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 00463 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 00464 sqlite3DbFree(db, db->aDb); 00465 db->aDb = db->aDbStatic; 00466 } 00467 } 00468 00469 /* 00470 ** This routine is called when a commit occurs. 00471 */ 00472 void sqlite3CommitInternalChanges(sqlite3 *db){ 00473 db->flags &= ~SQLITE_InternChanges; 00474 } 00475 00476 /* 00477 ** Clear the column names from a table or view. 00478 */ 00479 static void sqliteResetColumnNames(Table *pTable){ 00480 int i; 00481 Column *pCol; 00482 sqlite3 *db = pTable->db; 00483 assert( pTable!=0 ); 00484 if( (pCol = pTable->aCol)!=0 ){ 00485 for(i=0; i<pTable->nCol; i++, pCol++){ 00486 sqlite3DbFree(db, pCol->zName); 00487 sqlite3ExprDelete(db, pCol->pDflt); 00488 sqlite3DbFree(db, pCol->zType); 00489 sqlite3DbFree(db, pCol->zColl); 00490 } 00491 sqlite3DbFree(db, pTable->aCol); 00492 } 00493 pTable->aCol = 0; 00494 pTable->nCol = 0; 00495 } 00496 00497 /* 00498 ** Remove the memory data structures associated with the given 00499 ** Table. No changes are made to disk by this routine. 00500 ** 00501 ** This routine just deletes the data structure. It does not unlink 00502 ** the table data structure from the hash table. Nor does it remove 00503 ** foreign keys from the sqlite.aFKey hash table. But it does destroy 00504 ** memory structures of the indices and foreign keys associated with 00505 ** the table. 00506 */ 00507 void sqlite3DeleteTable(Table *pTable){ 00508 Index *pIndex, *pNext; 00509 FKey *pFKey, *pNextFKey; 00510 sqlite3 *db; 00511 00512 if( pTable==0 ) return; 00513 db = pTable->db; 00514 00515 /* Do not delete the table until the reference count reaches zero. */ 00516 pTable->nRef--; 00517 if( pTable->nRef>0 ){ 00518 return; 00519 } 00520 assert( pTable->nRef==0 ); 00521 00522 /* Delete all indices associated with this table 00523 */ 00524 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 00525 pNext = pIndex->pNext; 00526 assert( pIndex->pSchema==pTable->pSchema ); 00527 sqliteDeleteIndex(pIndex); 00528 } 00529 00530 #ifndef SQLITE_OMIT_FOREIGN_KEY 00531 /* Delete all foreign keys associated with this table. The keys 00532 ** should have already been unlinked from the pSchema->aFKey hash table 00533 */ 00534 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){ 00535 pNextFKey = pFKey->pNextFrom; 00536 assert( sqlite3HashFind(&pTable->pSchema->aFKey, 00537 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey ); 00538 sqlite3DbFree(db, pFKey); 00539 } 00540 #endif 00541 00542 /* Delete the Table structure itself. 00543 */ 00544 sqliteResetColumnNames(pTable); 00545 sqlite3DbFree(db, pTable->zName); 00546 sqlite3DbFree(db, pTable->zColAff); 00547 sqlite3SelectDelete(db, pTable->pSelect); 00548 #ifndef SQLITE_OMIT_CHECK 00549 sqlite3ExprDelete(db, pTable->pCheck); 00550 #endif 00551 sqlite3VtabClear(pTable); 00552 sqlite3DbFree(db, pTable); 00553 } 00554 00555 /* 00556 ** Unlink the given table from the hash tables and the delete the 00557 ** table structure with all its indices and foreign keys. 00558 */ 00559 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 00560 Table *p; 00561 FKey *pF1, *pF2; 00562 Db *pDb; 00563 00564 assert( db!=0 ); 00565 assert( iDb>=0 && iDb<db->nDb ); 00566 assert( zTabName && zTabName[0] ); 00567 pDb = &db->aDb[iDb]; 00568 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0); 00569 if( p ){ 00570 #ifndef SQLITE_OMIT_FOREIGN_KEY 00571 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){ 00572 int nTo = strlen(pF1->zTo) + 1; 00573 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo); 00574 if( pF2==pF1 ){ 00575 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo); 00576 }else{ 00577 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; } 00578 if( pF2 ){ 00579 pF2->pNextTo = pF1->pNextTo; 00580 } 00581 } 00582 } 00583 #endif 00584 sqlite3DeleteTable(p); 00585 } 00586 db->flags |= SQLITE_InternChanges; 00587 } 00588 00589 /* 00590 ** Given a token, return a string that consists of the text of that 00591 ** token with any quotations removed. Space to hold the returned string 00592 ** is obtained from sqliteMalloc() and must be freed by the calling 00593 ** function. 00594 ** 00595 ** Tokens are often just pointers into the original SQL text and so 00596 ** are not \000 terminated and are not persistent. The returned string 00597 ** is \000 terminated and is persistent. 00598 */ 00599 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ 00600 char *zName; 00601 if( pName ){ 00602 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); 00603 sqlite3Dequote(zName); 00604 }else{ 00605 zName = 0; 00606 } 00607 return zName; 00608 } 00609 00610 /* 00611 ** Open the sqlite_master table stored in database number iDb for 00612 ** writing. The table is opened using cursor 0. 00613 */ 00614 void sqlite3OpenMasterTable(Parse *p, int iDb){ 00615 Vdbe *v = sqlite3GetVdbe(p); 00616 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); 00617 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */ 00618 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); 00619 } 00620 00621 /* 00622 ** The token *pName contains the name of a database (either "main" or 00623 ** "temp" or the name of an attached db). This routine returns the 00624 ** index of the named database in db->aDb[], or -1 if the named db 00625 ** does not exist. 00626 */ 00627 int sqlite3FindDb(sqlite3 *db, Token *pName){ 00628 int i = -1; /* Database number */ 00629 int n; /* Number of characters in the name */ 00630 Db *pDb; /* A database whose name space is being searched */ 00631 char *zName; /* Name we are searching for */ 00632 00633 zName = sqlite3NameFromToken(db, pName); 00634 if( zName ){ 00635 n = strlen(zName); 00636 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 00637 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 00638 0==sqlite3StrICmp(pDb->zName, zName) ){ 00639 break; 00640 } 00641 } 00642 sqlite3DbFree(db, zName); 00643 } 00644 return i; 00645 } 00646 00647 /* The table or view or trigger name is passed to this routine via tokens 00648 ** pName1 and pName2. If the table name was fully qualified, for example: 00649 ** 00650 ** CREATE TABLE xxx.yyy (...); 00651 ** 00652 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 00653 ** the table name is not fully qualified, i.e.: 00654 ** 00655 ** CREATE TABLE yyy(...); 00656 ** 00657 ** Then pName1 is set to "yyy" and pName2 is "". 00658 ** 00659 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 00660 ** pName2) that stores the unqualified table name. The index of the 00661 ** database "xxx" is returned. 00662 */ 00663 int sqlite3TwoPartName( 00664 Parse *pParse, /* Parsing and code generating context */ 00665 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 00666 Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 00667 Token **pUnqual /* Write the unqualified object name here */ 00668 ){ 00669 int iDb; /* Database holding the object */ 00670 sqlite3 *db = pParse->db; 00671 00672 if( pName2 && pName2->n>0 ){ 00673 assert( !db->init.busy ); 00674 *pUnqual = pName2; 00675 iDb = sqlite3FindDb(db, pName1); 00676 if( iDb<0 ){ 00677 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 00678 pParse->nErr++; 00679 return -1; 00680 } 00681 }else{ 00682 assert( db->init.iDb==0 || db->init.busy ); 00683 iDb = db->init.iDb; 00684 *pUnqual = pName1; 00685 } 00686 return iDb; 00687 } 00688 00689 /* 00690 ** This routine is used to check if the UTF-8 string zName is a legal 00691 ** unqualified name for a new schema object (table, index, view or 00692 ** trigger). All names are legal except those that begin with the string 00693 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 00694 ** is reserved for internal use. 00695 */ 00696 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ 00697 if( !pParse->db->init.busy && pParse->nested==0 00698 && (pParse->db->flags & SQLITE_WriteSchema)==0 00699 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 00700 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 00701 return SQLITE_ERROR; 00702 } 00703 return SQLITE_OK; 00704 } 00705 00706 /* 00707 ** Begin constructing a new table representation in memory. This is 00708 ** the first of several action routines that get called in response 00709 ** to a CREATE TABLE statement. In particular, this routine is called 00710 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 00711 ** flag is true if the table should be stored in the auxiliary database 00712 ** file instead of in the main database file. This is normally the case 00713 ** when the "TEMP" or "TEMPORARY" keyword occurs in between 00714 ** CREATE and TABLE. 00715 ** 00716 ** The new table record is initialized and put in pParse->pNewTable. 00717 ** As more of the CREATE TABLE statement is parsed, additional action 00718 ** routines will be called to add more information to this record. 00719 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 00720 ** is called to complete the construction of the new table record. 00721 */ 00722 void sqlite3StartTable( 00723 Parse *pParse, /* Parser context */ 00724 Token *pName1, /* First part of the name of the table or view */ 00725 Token *pName2, /* Second part of the name of the table or view */ 00726 int isTemp, /* True if this is a TEMP table */ 00727 int isView, /* True if this is a VIEW */ 00728 int isVirtual, /* True if this is a VIRTUAL table */ 00729 int noErr /* Do nothing if table already exists */ 00730 ){ 00731 Table *pTable; 00732 char *zName = 0; /* The name of the new table */ 00733 sqlite3 *db = pParse->db; 00734 Vdbe *v; 00735 int iDb; /* Database number to create the table in */ 00736 Token *pName; /* Unqualified name of the table to create */ 00737 00738 /* The table or view name to create is passed to this routine via tokens 00739 ** pName1 and pName2. If the table name was fully qualified, for example: 00740 ** 00741 ** CREATE TABLE xxx.yyy (...); 00742 ** 00743 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 00744 ** the table name is not fully qualified, i.e.: 00745 ** 00746 ** CREATE TABLE yyy(...); 00747 ** 00748 ** Then pName1 is set to "yyy" and pName2 is "". 00749 ** 00750 ** The call below sets the pName pointer to point at the token (pName1 or 00751 ** pName2) that stores the unqualified table name. The variable iDb is 00752 ** set to the index of the database that the table or view is to be 00753 ** created in. 00754 */ 00755 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 00756 if( iDb<0 ) return; 00757 if( !OMIT_TEMPDB && isTemp && iDb>1 ){ 00758 /* If creating a temp table, the name may not be qualified */ 00759 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 00760 return; 00761 } 00762 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 00763 00764 pParse->sNameToken = *pName; 00765 zName = sqlite3NameFromToken(db, pName); 00766 if( zName==0 ) return; 00767 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 00768 goto begin_table_error; 00769 } 00770 if( db->init.iDb==1 ) isTemp = 1; 00771 #ifndef SQLITE_OMIT_AUTHORIZATION 00772 assert( (isTemp & 1)==isTemp ); 00773 { 00774 int code; 00775 char *zDb = db->aDb[iDb].zName; 00776 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 00777 goto begin_table_error; 00778 } 00779 if( isView ){ 00780 if( !OMIT_TEMPDB && isTemp ){ 00781 code = SQLITE_CREATE_TEMP_VIEW; 00782 }else{ 00783 code = SQLITE_CREATE_VIEW; 00784 } 00785 }else{ 00786 if( !OMIT_TEMPDB && isTemp ){ 00787 code = SQLITE_CREATE_TEMP_TABLE; 00788 }else{ 00789 code = SQLITE_CREATE_TABLE; 00790 } 00791 } 00792 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ 00793 goto begin_table_error; 00794 } 00795 } 00796 #endif 00797 00798 /* Make sure the new table name does not collide with an existing 00799 ** index or table name in the same database. Issue an error message if 00800 ** it does. The exception is if the statement being parsed was passed 00801 ** to an sqlite3_declare_vtab() call. In that case only the column names 00802 ** and types will be used, so there is no need to test for namespace 00803 ** collisions. 00804 */ 00805 if( !IN_DECLARE_VTAB ){ 00806 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 00807 goto begin_table_error; 00808 } 00809 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName); 00810 if( pTable ){ 00811 if( !noErr ){ 00812 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 00813 } 00814 goto begin_table_error; 00815 } 00816 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){ 00817 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 00818 goto begin_table_error; 00819 } 00820 } 00821 00822 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 00823 if( pTable==0 ){ 00824 db->mallocFailed = 1; 00825 pParse->rc = SQLITE_NOMEM; 00826 pParse->nErr++; 00827 goto begin_table_error; 00828 } 00829 pTable->zName = zName; 00830 pTable->iPKey = -1; 00831 pTable->pSchema = db->aDb[iDb].pSchema; 00832 pTable->nRef = 1; 00833 pTable->db = db; 00834 if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable); 00835 pParse->pNewTable = pTable; 00836 00837 /* If this is the magic sqlite_sequence table used by autoincrement, 00838 ** then record a pointer to this table in the main database structure 00839 ** so that INSERT can find the table easily. 00840 */ 00841 #ifndef SQLITE_OMIT_AUTOINCREMENT 00842 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 00843 pTable->pSchema->pSeqTab = pTable; 00844 } 00845 #endif 00846 00847 /* Begin generating the code that will insert the table record into 00848 ** the SQLITE_MASTER table. Note in particular that we must go ahead 00849 ** and allocate the record number for the table entry now. Before any 00850 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 00851 ** indices to be created and the table record must come before the 00852 ** indices. Hence, the record number for the table must be allocated 00853 ** now. 00854 */ 00855 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 00856 int j1; 00857 int fileFormat; 00858 int reg1, reg2, reg3; 00859 sqlite3BeginWriteOperation(pParse, 0, iDb); 00860 00861 #ifndef SQLITE_OMIT_VIRTUALTABLE 00862 if( isVirtual ){ 00863 sqlite3VdbeAddOp0(v, OP_VBegin); 00864 } 00865 #endif 00866 00867 /* If the file format and encoding in the database have not been set, 00868 ** set them now. 00869 */ 00870 reg1 = pParse->regRowid = ++pParse->nMem; 00871 reg2 = pParse->regRoot = ++pParse->nMem; 00872 reg3 = ++pParse->nMem; 00873 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */ 00874 sqlite3VdbeUsesBtree(v, iDb); 00875 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); 00876 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 00877 1 : SQLITE_MAX_FILE_FORMAT; 00878 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); 00879 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3); 00880 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); 00881 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3); 00882 sqlite3VdbeJumpHere(v, j1); 00883 00884 /* This just creates a place-holder record in the sqlite_master table. 00885 ** The record created does not contain anything yet. It will be replaced 00886 ** by the real entry in code generated at sqlite3EndTable(). 00887 ** 00888 ** The rowid for the new entry is left on the top of the stack. 00889 ** The rowid value is needed by the code that sqlite3EndTable will 00890 ** generate. 00891 */ 00892 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 00893 if( isView || isVirtual ){ 00894 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 00895 }else 00896 #endif 00897 { 00898 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); 00899 } 00900 sqlite3OpenMasterTable(pParse, iDb); 00901 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 00902 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); 00903 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 00904 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 00905 sqlite3VdbeAddOp0(v, OP_Close); 00906 } 00907 00908 /* Normal (non-error) return. */ 00909 return; 00910 00911 /* If an error occurs, we jump here */ 00912 begin_table_error: 00913 sqlite3DbFree(db, zName); 00914 return; 00915 } 00916 00917 /* 00918 ** This macro is used to compare two strings in a case-insensitive manner. 00919 ** It is slightly faster than calling sqlite3StrICmp() directly, but 00920 ** produces larger code. 00921 ** 00922 ** WARNING: This macro is not compatible with the strcmp() family. It 00923 ** returns true if the two strings are equal, otherwise false. 00924 */ 00925 #define STRICMP(x, y) (\ 00926 sqlite3UpperToLower[*(unsigned char *)(x)]== \ 00927 sqlite3UpperToLower[*(unsigned char *)(y)] \ 00928 && sqlite3StrICmp((x)+1,(y)+1)==0 ) 00929 00930 /* 00931 ** Add a new column to the table currently being constructed. 00932 ** 00933 ** The parser calls this routine once for each column declaration 00934 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 00935 ** first to get things going. Then this routine is called for each 00936 ** column. 00937 */ 00938 void sqlite3AddColumn(Parse *pParse, Token *pName){ 00939 Table *p; 00940 int i; 00941 char *z; 00942 Column *pCol; 00943 sqlite3 *db = pParse->db; 00944 if( (p = pParse->pNewTable)==0 ) return; 00945 #if SQLITE_MAX_COLUMN 00946 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 00947 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 00948 return; 00949 } 00950 #endif 00951 z = sqlite3NameFromToken(pParse->db, pName); 00952 if( z==0 ) return; 00953 for(i=0; i<p->nCol; i++){ 00954 if( STRICMP(z, p->aCol[i].zName) ){ 00955 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 00956 sqlite3DbFree(db, z); 00957 return; 00958 } 00959 } 00960 if( (p->nCol & 0x7)==0 ){ 00961 Column *aNew; 00962 aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); 00963 if( aNew==0 ){ 00964 sqlite3DbFree(db, z); 00965 return; 00966 } 00967 p->aCol = aNew; 00968 } 00969 pCol = &p->aCol[p->nCol]; 00970 memset(pCol, 0, sizeof(p->aCol[0])); 00971 pCol->zName = z; 00972 00973 /* If there is no type specified, columns have the default affinity 00974 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will 00975 ** be called next to set pCol->affinity correctly. 00976 */ 00977 pCol->affinity = SQLITE_AFF_NONE; 00978 p->nCol++; 00979 } 00980 00981 /* 00982 ** This routine is called by the parser while in the middle of 00983 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 00984 ** been seen on a column. This routine sets the notNull flag on 00985 ** the column currently under construction. 00986 */ 00987 void sqlite3AddNotNull(Parse *pParse, int onError){ 00988 Table *p; 00989 int i; 00990 if( (p = pParse->pNewTable)==0 ) return; 00991 i = p->nCol-1; 00992 if( i>=0 ) p->aCol[i].notNull = onError; 00993 } 00994 00995 /* 00996 ** Scan the column type name zType (length nType) and return the 00997 ** associated affinity type. 00998 ** 00999 ** This routine does a case-independent search of zType for the 01000 ** substrings in the following table. If one of the substrings is 01001 ** found, the corresponding affinity is returned. If zType contains 01002 ** more than one of the substrings, entries toward the top of 01003 ** the table take priority. For example, if zType is 'BLOBINT', 01004 ** SQLITE_AFF_INTEGER is returned. 01005 ** 01006 ** Substring | Affinity 01007 ** -------------------------------- 01008 ** 'INT' | SQLITE_AFF_INTEGER 01009 ** 'CHAR' | SQLITE_AFF_TEXT 01010 ** 'CLOB' | SQLITE_AFF_TEXT 01011 ** 'TEXT' | SQLITE_AFF_TEXT 01012 ** 'BLOB' | SQLITE_AFF_NONE 01013 ** 'REAL' | SQLITE_AFF_REAL 01014 ** 'FLOA' | SQLITE_AFF_REAL 01015 ** 'DOUB' | SQLITE_AFF_REAL 01016 ** 01017 ** If none of the substrings in the above table are found, 01018 ** SQLITE_AFF_NUMERIC is returned. 01019 */ 01020 char sqlite3AffinityType(const Token *pType){ 01021 u32 h = 0; 01022 char aff = SQLITE_AFF_NUMERIC; 01023 const unsigned char *zIn = pType->z; 01024 const unsigned char *zEnd = &pType->z[pType->n]; 01025 01026 while( zIn!=zEnd ){ 01027 h = (h<<8) + sqlite3UpperToLower[*zIn]; 01028 zIn++; 01029 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 01030 aff = SQLITE_AFF_TEXT; 01031 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 01032 aff = SQLITE_AFF_TEXT; 01033 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 01034 aff = SQLITE_AFF_TEXT; 01035 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 01036 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 01037 aff = SQLITE_AFF_NONE; 01038 #ifndef SQLITE_OMIT_FLOATING_POINT 01039 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 01040 && aff==SQLITE_AFF_NUMERIC ){ 01041 aff = SQLITE_AFF_REAL; 01042 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 01043 && aff==SQLITE_AFF_NUMERIC ){ 01044 aff = SQLITE_AFF_REAL; 01045 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 01046 && aff==SQLITE_AFF_NUMERIC ){ 01047 aff = SQLITE_AFF_REAL; 01048 #endif 01049 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 01050 aff = SQLITE_AFF_INTEGER; 01051 break; 01052 } 01053 } 01054 01055 return aff; 01056 } 01057 01058 /* 01059 ** This routine is called by the parser while in the middle of 01060 ** parsing a CREATE TABLE statement. The pFirst token is the first 01061 ** token in the sequence of tokens that describe the type of the 01062 ** column currently under construction. pLast is the last token 01063 ** in the sequence. Use this information to construct a string 01064 ** that contains the typename of the column and store that string 01065 ** in zType. 01066 */ 01067 void sqlite3AddColumnType(Parse *pParse, Token *pType){ 01068 Table *p; 01069 int i; 01070 Column *pCol; 01071 sqlite3 *db; 01072 01073 if( (p = pParse->pNewTable)==0 ) return; 01074 i = p->nCol-1; 01075 if( i<0 ) return; 01076 pCol = &p->aCol[i]; 01077 db = pParse->db; 01078 sqlite3DbFree(db, pCol->zType); 01079 pCol->zType = sqlite3NameFromToken(db, pType); 01080 pCol->affinity = sqlite3AffinityType(pType); 01081 } 01082 01083 /* 01084 ** The expression is the default value for the most recently added column 01085 ** of the table currently under construction. 01086 ** 01087 ** Default value expressions must be constant. Raise an exception if this 01088 ** is not the case. 01089 ** 01090 ** This routine is called by the parser while in the middle of 01091 ** parsing a CREATE TABLE statement. 01092 */ 01093 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){ 01094 Table *p; 01095 Column *pCol; 01096 sqlite3 *db = pParse->db; 01097 if( (p = pParse->pNewTable)!=0 ){ 01098 pCol = &(p->aCol[p->nCol-1]); 01099 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){ 01100 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 01101 pCol->zName); 01102 }else{ 01103 Expr *pCopy; 01104 sqlite3ExprDelete(db, pCol->pDflt); 01105 pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr); 01106 if( pCopy ){ 01107 sqlite3TokenCopy(db, &pCopy->span, &pExpr->span); 01108 } 01109 } 01110 } 01111 sqlite3ExprDelete(db, pExpr); 01112 } 01113 01114 /* 01115 ** Designate the PRIMARY KEY for the table. pList is a list of names 01116 ** of columns that form the primary key. If pList is NULL, then the 01117 ** most recently added column of the table is the primary key. 01118 ** 01119 ** A table can have at most one primary key. If the table already has 01120 ** a primary key (and this is the second primary key) then create an 01121 ** error. 01122 ** 01123 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 01124 ** then we will try to use that column as the rowid. Set the Table.iPKey 01125 ** field of the table under construction to be the index of the 01126 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 01127 ** no INTEGER PRIMARY KEY. 01128 ** 01129 ** If the key is not an INTEGER PRIMARY KEY, then create a unique 01130 ** index for the key. No index is created for INTEGER PRIMARY KEYs. 01131 */ 01132 void sqlite3AddPrimaryKey( 01133 Parse *pParse, /* Parsing context */ 01134 ExprList *pList, /* List of field names to be indexed */ 01135 int onError, /* What to do with a uniqueness conflict */ 01136 int autoInc, /* True if the AUTOINCREMENT keyword is present */ 01137 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 01138 ){ 01139 Table *pTab = pParse->pNewTable; 01140 char *zType = 0; 01141 int iCol = -1, i; 01142 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; 01143 if( pTab->tabFlags & TF_HasPrimaryKey ){ 01144 sqlite3ErrorMsg(pParse, 01145 "table \"%s\" has more than one primary key", pTab->zName); 01146 goto primary_key_exit; 01147 } 01148 pTab->tabFlags |= TF_HasPrimaryKey; 01149 if( pList==0 ){ 01150 iCol = pTab->nCol - 1; 01151 pTab->aCol[iCol].isPrimKey = 1; 01152 }else{ 01153 for(i=0; i<pList->nExpr; i++){ 01154 for(iCol=0; iCol<pTab->nCol; iCol++){ 01155 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ 01156 break; 01157 } 01158 } 01159 if( iCol<pTab->nCol ){ 01160 pTab->aCol[iCol].isPrimKey = 1; 01161 } 01162 } 01163 if( pList->nExpr>1 ) iCol = -1; 01164 } 01165 if( iCol>=0 && iCol<pTab->nCol ){ 01166 zType = pTab->aCol[iCol].zType; 01167 } 01168 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 01169 && sortOrder==SQLITE_SO_ASC ){ 01170 pTab->iPKey = iCol; 01171 pTab->keyConf = onError; 01172 assert( autoInc==0 || autoInc==1 ); 01173 pTab->tabFlags |= autoInc*TF_Autoincrement; 01174 }else if( autoInc ){ 01175 #ifndef SQLITE_OMIT_AUTOINCREMENT 01176 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 01177 "INTEGER PRIMARY KEY"); 01178 #endif 01179 }else{ 01180 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); 01181 pList = 0; 01182 } 01183 01184 primary_key_exit: 01185 sqlite3ExprListDelete(pParse->db, pList); 01186 return; 01187 } 01188 01189 /* 01190 ** Add a new CHECK constraint to the table currently under construction. 01191 */ 01192 void sqlite3AddCheckConstraint( 01193 Parse *pParse, /* Parsing context */ 01194 Expr *pCheckExpr /* The check expression */ 01195 ){ 01196 sqlite3 *db = pParse->db; 01197 #ifndef SQLITE_OMIT_CHECK 01198 Table *pTab = pParse->pNewTable; 01199 if( pTab && !IN_DECLARE_VTAB ){ 01200 /* The CHECK expression must be duplicated so that tokens refer 01201 ** to malloced space and not the (ephemeral) text of the CREATE TABLE 01202 ** statement */ 01203 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 01204 sqlite3ExprDup(db, pCheckExpr)); 01205 } 01206 #endif 01207 sqlite3ExprDelete(db, pCheckExpr); 01208 } 01209 01210 /* 01211 ** Set the collation function of the most recently parsed table column 01212 ** to the CollSeq given. 01213 */ 01214 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 01215 Table *p; 01216 int i; 01217 char *zColl; /* Dequoted name of collation sequence */ 01218 sqlite3 *db; 01219 01220 if( (p = pParse->pNewTable)==0 ) return; 01221 i = p->nCol-1; 01222 db = pParse->db; 01223 zColl = sqlite3NameFromToken(db, pToken); 01224 if( !zColl ) return; 01225 01226 if( sqlite3LocateCollSeq(pParse, zColl, -1) ){ 01227 Index *pIdx; 01228 p->aCol[i].zColl = zColl; 01229 01230 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 01231 ** then an index may have been created on this column before the 01232 ** collation type was added. Correct this if it is the case. 01233 */ 01234 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 01235 assert( pIdx->nColumn==1 ); 01236 if( pIdx->aiColumn[0]==i ){ 01237 pIdx->azColl[0] = p->aCol[i].zColl; 01238 } 01239 } 01240 }else{ 01241 sqlite3DbFree(db, zColl); 01242 } 01243 } 01244 01245 /* 01246 ** This function returns the collation sequence for database native text 01247 ** encoding identified by the string zName, length nName. 01248 ** 01249 ** If the requested collation sequence is not available, or not available 01250 ** in the database native encoding, the collation factory is invoked to 01251 ** request it. If the collation factory does not supply such a sequence, 01252 ** and the sequence is available in another text encoding, then that is 01253 ** returned instead. 01254 ** 01255 ** If no versions of the requested collations sequence are available, or 01256 ** another error occurs, NULL is returned and an error message written into 01257 ** pParse. 01258 ** 01259 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine 01260 ** invokes the collation factory if the named collation cannot be found 01261 ** and generates an error message. 01262 */ 01263 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){ 01264 sqlite3 *db = pParse->db; 01265 u8 enc = ENC(db); 01266 u8 initbusy = db->init.busy; 01267 CollSeq *pColl; 01268 01269 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy); 01270 if( !initbusy && (!pColl || !pColl->xCmp) ){ 01271 pColl = sqlite3GetCollSeq(db, pColl, zName, nName); 01272 if( !pColl ){ 01273 if( nName<0 ){ 01274 nName = sqlite3Strlen(db, zName); 01275 } 01276 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName); 01277 pColl = 0; 01278 } 01279 } 01280 01281 return pColl; 01282 } 01283 01284 01285 /* 01286 ** Generate code that will increment the schema cookie. 01287 ** 01288 ** The schema cookie is used to determine when the schema for the 01289 ** database changes. After each schema change, the cookie value 01290 ** changes. When a process first reads the schema it records the 01291 ** cookie. Thereafter, whenever it goes to access the database, 01292 ** it checks the cookie to make sure the schema has not changed 01293 ** since it was last read. 01294 ** 01295 ** This plan is not completely bullet-proof. It is possible for 01296 ** the schema to change multiple times and for the cookie to be 01297 ** set back to prior value. But schema changes are infrequent 01298 ** and the probability of hitting the same cookie value is only 01299 ** 1 chance in 2^32. So we're safe enough. 01300 */ 01301 void sqlite3ChangeCookie(Parse *pParse, int iDb){ 01302 int r1 = sqlite3GetTempReg(pParse); 01303 sqlite3 *db = pParse->db; 01304 Vdbe *v = pParse->pVdbe; 01305 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); 01306 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1); 01307 sqlite3ReleaseTempReg(pParse, r1); 01308 } 01309 01310 /* 01311 ** Measure the number of characters needed to output the given 01312 ** identifier. The number returned includes any quotes used 01313 ** but does not include the null terminator. 01314 ** 01315 ** The estimate is conservative. It might be larger that what is 01316 ** really needed. 01317 */ 01318 static int identLength(const char *z){ 01319 int n; 01320 for(n=0; *z; n++, z++){ 01321 if( *z=='"' ){ n++; } 01322 } 01323 return n + 2; 01324 } 01325 01326 /* 01327 ** Write an identifier onto the end of the given string. Add 01328 ** quote characters as needed. 01329 */ 01330 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 01331 unsigned char *zIdent = (unsigned char*)zSignedIdent; 01332 int i, j, needQuote; 01333 i = *pIdx; 01334 for(j=0; zIdent[j]; j++){ 01335 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 01336 } 01337 needQuote = zIdent[j]!=0 || isdigit(zIdent[0]) 01338 || sqlite3KeywordCode(zIdent, j)!=TK_ID; 01339 if( needQuote ) z[i++] = '"'; 01340 for(j=0; zIdent[j]; j++){ 01341 z[i++] = zIdent[j]; 01342 if( zIdent[j]=='"' ) z[i++] = '"'; 01343 } 01344 if( needQuote ) z[i++] = '"'; 01345 z[i] = 0; 01346 *pIdx = i; 01347 } 01348 01349 /* 01350 ** Generate a CREATE TABLE statement appropriate for the given 01351 ** table. Memory to hold the text of the statement is obtained 01352 ** from sqliteMalloc() and must be freed by the calling function. 01353 */ 01354 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){ 01355 int i, k, n; 01356 char *zStmt; 01357 char *zSep, *zSep2, *zEnd, *z; 01358 Column *pCol; 01359 n = 0; 01360 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 01361 n += identLength(pCol->zName); 01362 z = pCol->zType; 01363 if( z ){ 01364 n += (strlen(z) + 1); 01365 } 01366 } 01367 n += identLength(p->zName); 01368 if( n<50 ){ 01369 zSep = ""; 01370 zSep2 = ","; 01371 zEnd = ")"; 01372 }else{ 01373 zSep = "\n "; 01374 zSep2 = ",\n "; 01375 zEnd = "\n)"; 01376 } 01377 n += 35 + 6*p->nCol; 01378 zStmt = sqlite3Malloc( n ); 01379 if( zStmt==0 ){ 01380 db->mallocFailed = 1; 01381 return 0; 01382 } 01383 sqlite3_snprintf(n, zStmt, 01384 !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE "); 01385 k = strlen(zStmt); 01386 identPut(zStmt, &k, p->zName); 01387 zStmt[k++] = '('; 01388 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 01389 sqlite3_snprintf(n-k, &zStmt[k], zSep); 01390 k += strlen(&zStmt[k]); 01391 zSep = zSep2; 01392 identPut(zStmt, &k, pCol->zName); 01393 if( (z = pCol->zType)!=0 ){ 01394 zStmt[k++] = ' '; 01395 assert( strlen(z)+k+1<=n ); 01396 sqlite3_snprintf(n-k, &zStmt[k], "%s", z); 01397 k += strlen(z); 01398 } 01399 } 01400 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 01401 return zStmt; 01402 } 01403 01404 /* 01405 ** This routine is called to report the final ")" that terminates 01406 ** a CREATE TABLE statement. 01407 ** 01408 ** The table structure that other action routines have been building 01409 ** is added to the internal hash tables, assuming no errors have 01410 ** occurred. 01411 ** 01412 ** An entry for the table is made in the master table on disk, unless 01413 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 01414 ** it means we are reading the sqlite_master table because we just 01415 ** connected to the database or because the sqlite_master table has 01416 ** recently changed, so the entry for this table already exists in 01417 ** the sqlite_master table. We do not want to create it again. 01418 ** 01419 ** If the pSelect argument is not NULL, it means that this routine 01420 ** was called to create a table generated from a 01421 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 01422 ** the new table will match the result set of the SELECT. 01423 */ 01424 void sqlite3EndTable( 01425 Parse *pParse, /* Parse context */ 01426 Token *pCons, /* The ',' token after the last column defn. */ 01427 Token *pEnd, /* The final ')' token in the CREATE TABLE */ 01428 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 01429 ){ 01430 Table *p; 01431 sqlite3 *db = pParse->db; 01432 int iDb; 01433 01434 if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) { 01435 return; 01436 } 01437 p = pParse->pNewTable; 01438 if( p==0 ) return; 01439 01440 assert( !db->init.busy || !pSelect ); 01441 01442 iDb = sqlite3SchemaToIndex(db, p->pSchema); 01443 01444 #ifndef SQLITE_OMIT_CHECK 01445 /* Resolve names in all CHECK constraint expressions. 01446 */ 01447 if( p->pCheck ){ 01448 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ 01449 NameContext sNC; /* Name context for pParse->pNewTable */ 01450 01451 memset(&sNC, 0, sizeof(sNC)); 01452 memset(&sSrc, 0, sizeof(sSrc)); 01453 sSrc.nSrc = 1; 01454 sSrc.a[0].zName = p->zName; 01455 sSrc.a[0].pTab = p; 01456 sSrc.a[0].iCursor = -1; 01457 sNC.pParse = pParse; 01458 sNC.pSrcList = &sSrc; 01459 sNC.isCheck = 1; 01460 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){ 01461 return; 01462 } 01463 } 01464 #endif /* !defined(SQLITE_OMIT_CHECK) */ 01465 01466 /* If the db->init.busy is 1 it means we are reading the SQL off the 01467 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 01468 ** So do not write to the disk again. Extract the root page number 01469 ** for the table from the db->init.newTnum field. (The page number 01470 ** should have been put there by the sqliteOpenCb routine.) 01471 */ 01472 if( db->init.busy ){ 01473 p->tnum = db->init.newTnum; 01474 } 01475 01476 /* If not initializing, then create a record for the new table 01477 ** in the SQLITE_MASTER table of the database. The record number 01478 ** for the new table entry should already be on the stack. 01479 ** 01480 ** If this is a TEMPORARY table, write the entry into the auxiliary 01481 ** file instead of into the main database file. 01482 */ 01483 if( !db->init.busy ){ 01484 int n; 01485 Vdbe *v; 01486 char *zType; /* "view" or "table" */ 01487 char *zType2; /* "VIEW" or "TABLE" */ 01488 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 01489 01490 v = sqlite3GetVdbe(pParse); 01491 if( v==0 ) return; 01492 01493 sqlite3VdbeAddOp1(v, OP_Close, 0); 01494 01495 /* Create the rootpage for the new table and push it onto the stack. 01496 ** A view has no rootpage, so just push a zero onto the stack for 01497 ** views. Initialize zType at the same time. 01498 */ 01499 if( p->pSelect==0 ){ 01500 /* A regular table */ 01501 zType = "table"; 01502 zType2 = "TABLE"; 01503 #ifndef SQLITE_OMIT_VIEW 01504 }else{ 01505 /* A view */ 01506 zType = "view"; 01507 zType2 = "VIEW"; 01508 #endif 01509 } 01510 01511 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 01512 ** statement to populate the new table. The root-page number for the 01513 ** new table is on the top of the vdbe stack. 01514 ** 01515 ** Once the SELECT has been coded by sqlite3Select(), it is in a 01516 ** suitable state to query for the column names and types to be used 01517 ** by the new table. 01518 ** 01519 ** A shared-cache write-lock is not required to write to the new table, 01520 ** as a schema-lock must have already been obtained to create it. Since 01521 ** a schema-lock excludes all other database users, the write-lock would 01522 ** be redundant. 01523 */ 01524 if( pSelect ){ 01525 SelectDest dest; 01526 Table *pSelTab; 01527 01528 assert(pParse->nTab==0); 01529 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 01530 sqlite3VdbeChangeP5(v, 1); 01531 pParse->nTab = 2; 01532 sqlite3SelectDestInit(&dest, SRT_Table, 1); 01533 sqlite3Select(pParse, pSelect, &dest); 01534 sqlite3VdbeAddOp1(v, OP_Close, 1); 01535 if( pParse->nErr==0 ){ 01536 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); 01537 if( pSelTab==0 ) return; 01538 assert( p->aCol==0 ); 01539 p->nCol = pSelTab->nCol; 01540 p->aCol = pSelTab->aCol; 01541 pSelTab->nCol = 0; 01542 pSelTab->aCol = 0; 01543 sqlite3DeleteTable(pSelTab); 01544 } 01545 } 01546 01547 /* Compute the complete text of the CREATE statement */ 01548 if( pSelect ){ 01549 zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema); 01550 }else{ 01551 n = pEnd->z - pParse->sNameToken.z + 1; 01552 zStmt = sqlite3MPrintf(db, 01553 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 01554 ); 01555 } 01556 01557 /* A slot for the record has already been allocated in the 01558 ** SQLITE_MASTER table. We just need to update that slot with all 01559 ** the information we've collected. The rowid for the preallocated 01560 ** slot is the 2nd item on the stack. The top of the stack is the 01561 ** root page for the new table (or a 0 if this is a view). 01562 */ 01563 sqlite3NestedParse(pParse, 01564 "UPDATE %Q.%s " 01565 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " 01566 "WHERE rowid=#%d", 01567 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 01568 zType, 01569 p->zName, 01570 p->zName, 01571 pParse->regRoot, 01572 zStmt, 01573 pParse->regRowid 01574 ); 01575 sqlite3DbFree(db, zStmt); 01576 sqlite3ChangeCookie(pParse, iDb); 01577 01578 #ifndef SQLITE_OMIT_AUTOINCREMENT 01579 /* Check to see if we need to create an sqlite_sequence table for 01580 ** keeping track of autoincrement keys. 01581 */ 01582 if( p->tabFlags & TF_Autoincrement ){ 01583 Db *pDb = &db->aDb[iDb]; 01584 if( pDb->pSchema->pSeqTab==0 ){ 01585 sqlite3NestedParse(pParse, 01586 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 01587 pDb->zName 01588 ); 01589 } 01590 } 01591 #endif 01592 01593 /* Reparse everything to update our internal data structures */ 01594 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 01595 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC); 01596 } 01597 01598 01599 /* Add the table to the in-memory representation of the database. 01600 */ 01601 if( db->init.busy && pParse->nErr==0 ){ 01602 Table *pOld; 01603 FKey *pFKey; 01604 Schema *pSchema = p->pSchema; 01605 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p); 01606 if( pOld ){ 01607 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 01608 db->mallocFailed = 1; 01609 return; 01610 } 01611 #ifndef SQLITE_OMIT_FOREIGN_KEY 01612 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 01613 void *data; 01614 int nTo = strlen(pFKey->zTo) + 1; 01615 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo); 01616 data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey); 01617 if( data==(void *)pFKey ){ 01618 db->mallocFailed = 1; 01619 } 01620 } 01621 #endif 01622 pParse->pNewTable = 0; 01623 db->nTable++; 01624 db->flags |= SQLITE_InternChanges; 01625 01626 #ifndef SQLITE_OMIT_ALTERTABLE 01627 if( !p->pSelect ){ 01628 const char *zName = (const char *)pParse->sNameToken.z; 01629 int nName; 01630 assert( !pSelect && pCons && pEnd ); 01631 if( pCons->z==0 ){ 01632 pCons = pEnd; 01633 } 01634 nName = (const char *)pCons->z - zName; 01635 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); 01636 } 01637 #endif 01638 } 01639 } 01640 01641 #ifndef SQLITE_OMIT_VIEW 01642 /* 01643 ** The parser calls this routine in order to create a new VIEW 01644 */ 01645 void sqlite3CreateView( 01646 Parse *pParse, /* The parsing context */ 01647 Token *pBegin, /* The CREATE token that begins the statement */ 01648 Token *pName1, /* The token that holds the name of the view */ 01649 Token *pName2, /* The token that holds the name of the view */ 01650 Select *pSelect, /* A SELECT statement that will become the new view */ 01651 int isTemp, /* TRUE for a TEMPORARY view */ 01652 int noErr /* Suppress error messages if VIEW already exists */ 01653 ){ 01654 Table *p; 01655 int n; 01656 const unsigned char *z; 01657 Token sEnd; 01658 DbFixer sFix; 01659 Token *pName; 01660 int iDb; 01661 sqlite3 *db = pParse->db; 01662 01663 if( pParse->nVar>0 ){ 01664 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 01665 sqlite3SelectDelete(db, pSelect); 01666 return; 01667 } 01668 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 01669 p = pParse->pNewTable; 01670 if( p==0 || pParse->nErr ){ 01671 sqlite3SelectDelete(db, pSelect); 01672 return; 01673 } 01674 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 01675 iDb = sqlite3SchemaToIndex(db, p->pSchema); 01676 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName) 01677 && sqlite3FixSelect(&sFix, pSelect) 01678 ){ 01679 sqlite3SelectDelete(db, pSelect); 01680 return; 01681 } 01682 01683 /* Make a copy of the entire SELECT statement that defines the view. 01684 ** This will force all the Expr.token.z values to be dynamically 01685 ** allocated rather than point to the input string - which means that 01686 ** they will persist after the current sqlite3_exec() call returns. 01687 */ 01688 p->pSelect = sqlite3SelectDup(db, pSelect); 01689 sqlite3SelectDelete(db, pSelect); 01690 if( db->mallocFailed ){ 01691 return; 01692 } 01693 if( !db->init.busy ){ 01694 sqlite3ViewGetColumnNames(pParse, p); 01695 } 01696 01697 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 01698 ** the end. 01699 */ 01700 sEnd = pParse->sLastToken; 01701 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){ 01702 sEnd.z += sEnd.n; 01703 } 01704 sEnd.n = 0; 01705 n = sEnd.z - pBegin->z; 01706 z = (const unsigned char*)pBegin->z; 01707 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; } 01708 sEnd.z = &z[n-1]; 01709 sEnd.n = 1; 01710 01711 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 01712 sqlite3EndTable(pParse, 0, &sEnd, 0); 01713 return; 01714 } 01715 #endif /* SQLITE_OMIT_VIEW */ 01716 01717 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 01718 /* 01719 ** The Table structure pTable is really a VIEW. Fill in the names of 01720 ** the columns of the view in the pTable structure. Return the number 01721 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 01722 */ 01723 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 01724 Table *pSelTab; /* A fake table from which we get the result set */ 01725 Select *pSel; /* Copy of the SELECT that implements the view */ 01726 int nErr = 0; /* Number of errors encountered */ 01727 int n; /* Temporarily holds the number of cursors assigned */ 01728 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 01729 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); 01730 01731 assert( pTable ); 01732 01733 #ifndef SQLITE_OMIT_VIRTUALTABLE 01734 if( sqlite3VtabCallConnect(pParse, pTable) ){ 01735 return SQLITE_ERROR; 01736 } 01737 if( IsVirtual(pTable) ) return 0; 01738 #endif 01739 01740 #ifndef SQLITE_OMIT_VIEW 01741 /* A positive nCol means the columns names for this view are 01742 ** already known. 01743 */ 01744 if( pTable->nCol>0 ) return 0; 01745 01746 /* A negative nCol is a special marker meaning that we are currently 01747 ** trying to compute the column names. If we enter this routine with 01748 ** a negative nCol, it means two or more views form a loop, like this: 01749 ** 01750 ** CREATE VIEW one AS SELECT * FROM two; 01751 ** CREATE VIEW two AS SELECT * FROM one; 01752 ** 01753 ** Actually, this error is caught previously and so the following test 01754 ** should always fail. But we will leave it in place just to be safe. 01755 */ 01756 if( pTable->nCol<0 ){ 01757 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 01758 return 1; 01759 } 01760 assert( pTable->nCol>=0 ); 01761 01762 /* If we get this far, it means we need to compute the table names. 01763 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 01764 ** "*" elements in the results set of the view and will assign cursors 01765 ** to the elements of the FROM clause. But we do not want these changes 01766 ** to be permanent. So the computation is done on a copy of the SELECT 01767 ** statement that defines the view. 01768 */ 01769 assert( pTable->pSelect ); 01770 pSel = sqlite3SelectDup(db, pTable->pSelect); 01771 if( pSel ){ 01772 n = pParse->nTab; 01773 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 01774 pTable->nCol = -1; 01775 #ifndef SQLITE_OMIT_AUTHORIZATION 01776 xAuth = db->xAuth; 01777 db->xAuth = 0; 01778 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 01779 db->xAuth = xAuth; 01780 #else 01781 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 01782 #endif 01783 pParse->nTab = n; 01784 if( pSelTab ){ 01785 assert( pTable->aCol==0 ); 01786 pTable->nCol = pSelTab->nCol; 01787 pTable->aCol = pSelTab->aCol; 01788 pSelTab->nCol = 0; 01789 pSelTab->aCol = 0; 01790 sqlite3DeleteTable(pSelTab); 01791 pTable->pSchema->flags |= DB_UnresetViews; 01792 }else{ 01793 pTable->nCol = 0; 01794 nErr++; 01795 } 01796 sqlite3SelectDelete(db, pSel); 01797 } else { 01798 nErr++; 01799 } 01800 #endif /* SQLITE_OMIT_VIEW */ 01801 return nErr; 01802 } 01803 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 01804 01805 #ifndef SQLITE_OMIT_VIEW 01806 /* 01807 ** Clear the column names from every VIEW in database idx. 01808 */ 01809 static void sqliteViewResetAll(sqlite3 *db, int idx){ 01810 HashElem *i; 01811 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 01812 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 01813 Table *pTab = sqliteHashData(i); 01814 if( pTab->pSelect ){ 01815 sqliteResetColumnNames(pTab); 01816 } 01817 } 01818 DbClearProperty(db, idx, DB_UnresetViews); 01819 } 01820 #else 01821 # define sqliteViewResetAll(A,B) 01822 #endif /* SQLITE_OMIT_VIEW */ 01823 01824 /* 01825 ** This function is called by the VDBE to adjust the internal schema 01826 ** used by SQLite when the btree layer moves a table root page. The 01827 ** root-page of a table or index in database iDb has changed from iFrom 01828 ** to iTo. 01829 ** 01830 ** Ticket #1728: The symbol table might still contain information 01831 ** on tables and/or indices that are the process of being deleted. 01832 ** If you are unlucky, one of those deleted indices or tables might 01833 ** have the same rootpage number as the real table or index that is 01834 ** being moved. So we cannot stop searching after the first match 01835 ** because the first match might be for one of the deleted indices 01836 ** or tables and not the table/index that is actually being moved. 01837 ** We must continue looping until all tables and indices with 01838 ** rootpage==iFrom have been converted to have a rootpage of iTo 01839 ** in order to be certain that we got the right one. 01840 */ 01841 #ifndef SQLITE_OMIT_AUTOVACUUM 01842 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){ 01843 HashElem *pElem; 01844 Hash *pHash; 01845 01846 pHash = &pDb->pSchema->tblHash; 01847 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 01848 Table *pTab = sqliteHashData(pElem); 01849 if( pTab->tnum==iFrom ){ 01850 pTab->tnum = iTo; 01851 } 01852 } 01853 pHash = &pDb->pSchema->idxHash; 01854 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 01855 Index *pIdx = sqliteHashData(pElem); 01856 if( pIdx->tnum==iFrom ){ 01857 pIdx->tnum = iTo; 01858 } 01859 } 01860 } 01861 #endif 01862 01863 /* 01864 ** Write code to erase the table with root-page iTable from database iDb. 01865 ** Also write code to modify the sqlite_master table and internal schema 01866 ** if a root-page of another table is moved by the btree-layer whilst 01867 ** erasing iTable (this can happen with an auto-vacuum database). 01868 */ 01869 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 01870 Vdbe *v = sqlite3GetVdbe(pParse); 01871 int r1 = sqlite3GetTempReg(pParse); 01872 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 01873 #ifndef SQLITE_OMIT_AUTOVACUUM 01874 /* OP_Destroy stores an in integer r1. If this integer 01875 ** is non-zero, then it is the root page number of a table moved to 01876 ** location iTable. The following code modifies the sqlite_master table to 01877 ** reflect this. 01878 ** 01879 ** The "#%d" in the SQL is a special constant that means whatever value 01880 ** is on the top of the stack. See sqlite3RegisterExpr(). 01881 */ 01882 sqlite3NestedParse(pParse, 01883 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", 01884 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); 01885 #endif 01886 sqlite3ReleaseTempReg(pParse, r1); 01887 } 01888 01889 /* 01890 ** Write VDBE code to erase table pTab and all associated indices on disk. 01891 ** Code to update the sqlite_master tables and internal schema definitions 01892 ** in case a root-page belonging to another table is moved by the btree layer 01893 ** is also added (this can happen with an auto-vacuum database). 01894 */ 01895 static void destroyTable(Parse *pParse, Table *pTab){ 01896 #ifdef SQLITE_OMIT_AUTOVACUUM 01897 Index *pIdx; 01898 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 01899 destroyRootPage(pParse, pTab->tnum, iDb); 01900 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 01901 destroyRootPage(pParse, pIdx->tnum, iDb); 01902 } 01903 #else 01904 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 01905 ** is not defined), then it is important to call OP_Destroy on the 01906 ** table and index root-pages in order, starting with the numerically 01907 ** largest root-page number. This guarantees that none of the root-pages 01908 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 01909 ** following were coded: 01910 ** 01911 ** OP_Destroy 4 0 01912 ** ... 01913 ** OP_Destroy 5 0 01914 ** 01915 ** and root page 5 happened to be the largest root-page number in the 01916 ** database, then root page 5 would be moved to page 4 by the 01917 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 01918 ** a free-list page. 01919 */ 01920 int iTab = pTab->tnum; 01921 int iDestroyed = 0; 01922 01923 while( 1 ){ 01924 Index *pIdx; 01925 int iLargest = 0; 01926 01927 if( iDestroyed==0 || iTab<iDestroyed ){ 01928 iLargest = iTab; 01929 } 01930 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 01931 int iIdx = pIdx->tnum; 01932 assert( pIdx->pSchema==pTab->pSchema ); 01933 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 01934 iLargest = iIdx; 01935 } 01936 } 01937 if( iLargest==0 ){ 01938 return; 01939 }else{ 01940 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 01941 destroyRootPage(pParse, iLargest, iDb); 01942 iDestroyed = iLargest; 01943 } 01944 } 01945 #endif 01946 } 01947 01948 /* 01949 ** This routine is called to do the work of a DROP TABLE statement. 01950 ** pName is the name of the table to be dropped. 01951 */ 01952 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 01953 Table *pTab; 01954 Vdbe *v; 01955 sqlite3 *db = pParse->db; 01956 int iDb; 01957 01958 if( pParse->nErr || db->mallocFailed ){ 01959 goto exit_drop_table; 01960 } 01961 assert( pName->nSrc==1 ); 01962 pTab = sqlite3LocateTable(pParse, isView, 01963 pName->a[0].zName, pName->a[0].zDatabase); 01964 01965 if( pTab==0 ){ 01966 if( noErr ){ 01967 sqlite3ErrorClear(pParse); 01968 } 01969 goto exit_drop_table; 01970 } 01971 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 01972 assert( iDb>=0 && iDb<db->nDb ); 01973 01974 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 01975 ** it is initialized. 01976 */ 01977 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 01978 goto exit_drop_table; 01979 } 01980 #ifndef SQLITE_OMIT_AUTHORIZATION 01981 { 01982 int code; 01983 const char *zTab = SCHEMA_TABLE(iDb); 01984 const char *zDb = db->aDb[iDb].zName; 01985 const char *zArg2 = 0; 01986 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 01987 goto exit_drop_table; 01988 } 01989 if( isView ){ 01990 if( !OMIT_TEMPDB && iDb==1 ){ 01991 code = SQLITE_DROP_TEMP_VIEW; 01992 }else{ 01993 code = SQLITE_DROP_VIEW; 01994 } 01995 #ifndef SQLITE_OMIT_VIRTUALTABLE 01996 }else if( IsVirtual(pTab) ){ 01997 code = SQLITE_DROP_VTABLE; 01998 zArg2 = pTab->pMod->zName; 01999 #endif 02000 }else{ 02001 if( !OMIT_TEMPDB && iDb==1 ){ 02002 code = SQLITE_DROP_TEMP_TABLE; 02003 }else{ 02004 code = SQLITE_DROP_TABLE; 02005 } 02006 } 02007 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 02008 goto exit_drop_table; 02009 } 02010 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 02011 goto exit_drop_table; 02012 } 02013 } 02014 #endif 02015 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 02016 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 02017 goto exit_drop_table; 02018 } 02019 02020 #ifndef SQLITE_OMIT_VIEW 02021 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 02022 ** on a table. 02023 */ 02024 if( isView && pTab->pSelect==0 ){ 02025 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 02026 goto exit_drop_table; 02027 } 02028 if( !isView && pTab->pSelect ){ 02029 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 02030 goto exit_drop_table; 02031 } 02032 #endif 02033 02034 /* Generate code to remove the table from the master table 02035 ** on disk. 02036 */ 02037 v = sqlite3GetVdbe(pParse); 02038 if( v ){ 02039 Trigger *pTrigger; 02040 Db *pDb = &db->aDb[iDb]; 02041 sqlite3BeginWriteOperation(pParse, 1, iDb); 02042 02043 #ifndef SQLITE_OMIT_VIRTUALTABLE 02044 if( IsVirtual(pTab) ){ 02045 Vdbe *v = sqlite3GetVdbe(pParse); 02046 if( v ){ 02047 sqlite3VdbeAddOp0(v, OP_VBegin); 02048 } 02049 } 02050 #endif 02051 02052 /* Drop all triggers associated with the table being dropped. Code 02053 ** is generated to remove entries from sqlite_master and/or 02054 ** sqlite_temp_master if required. 02055 */ 02056 pTrigger = pTab->pTrigger; 02057 while( pTrigger ){ 02058 assert( pTrigger->pSchema==pTab->pSchema || 02059 pTrigger->pSchema==db->aDb[1].pSchema ); 02060 sqlite3DropTriggerPtr(pParse, pTrigger); 02061 pTrigger = pTrigger->pNext; 02062 } 02063 02064 #ifndef SQLITE_OMIT_AUTOINCREMENT 02065 /* Remove any entries of the sqlite_sequence table associated with 02066 ** the table being dropped. This is done before the table is dropped 02067 ** at the btree level, in case the sqlite_sequence table needs to 02068 ** move as a result of the drop (can happen in auto-vacuum mode). 02069 */ 02070 if( pTab->tabFlags & TF_Autoincrement ){ 02071 sqlite3NestedParse(pParse, 02072 "DELETE FROM %s.sqlite_sequence WHERE name=%Q", 02073 pDb->zName, pTab->zName 02074 ); 02075 } 02076 #endif 02077 02078 /* Drop all SQLITE_MASTER table and index entries that refer to the 02079 ** table. The program name loops through the master table and deletes 02080 ** every row that refers to a table of the same name as the one being 02081 ** dropped. Triggers are handled seperately because a trigger can be 02082 ** created in the temp database that refers to a table in another 02083 ** database. 02084 */ 02085 sqlite3NestedParse(pParse, 02086 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 02087 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); 02088 02089 /* Drop any statistics from the sqlite_stat1 table, if it exists */ 02090 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 02091 sqlite3NestedParse(pParse, 02092 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName 02093 ); 02094 } 02095 02096 if( !isView && !IsVirtual(pTab) ){ 02097 destroyTable(pParse, pTab); 02098 } 02099 02100 /* Remove the table entry from SQLite's internal schema and modify 02101 ** the schema cookie. 02102 */ 02103 if( IsVirtual(pTab) ){ 02104 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 02105 } 02106 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 02107 sqlite3ChangeCookie(pParse, iDb); 02108 } 02109 sqliteViewResetAll(db, iDb); 02110 02111 exit_drop_table: 02112 sqlite3SrcListDelete(db, pName); 02113 } 02114 02115 /* 02116 ** This routine is called to create a new foreign key on the table 02117 ** currently under construction. pFromCol determines which columns 02118 ** in the current table point to the foreign key. If pFromCol==0 then 02119 ** connect the key to the last column inserted. pTo is the name of 02120 ** the table referred to. pToCol is a list of tables in the other 02121 ** pTo table that the foreign key points to. flags contains all 02122 ** information about the conflict resolution algorithms specified 02123 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 02124 ** 02125 ** An FKey structure is created and added to the table currently 02126 ** under construction in the pParse->pNewTable field. The new FKey 02127 ** is not linked into db->aFKey at this point - that does not happen 02128 ** until sqlite3EndTable(). 02129 ** 02130 ** The foreign key is set for IMMEDIATE processing. A subsequent call 02131 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 02132 */ 02133 void sqlite3CreateForeignKey( 02134 Parse *pParse, /* Parsing context */ 02135 ExprList *pFromCol, /* Columns in this table that point to other table */ 02136 Token *pTo, /* Name of the other table */ 02137 ExprList *pToCol, /* Columns in the other table */ 02138 int flags /* Conflict resolution algorithms. */ 02139 ){ 02140 sqlite3 *db = pParse->db; 02141 #ifndef SQLITE_OMIT_FOREIGN_KEY 02142 FKey *pFKey = 0; 02143 Table *p = pParse->pNewTable; 02144 int nByte; 02145 int i; 02146 int nCol; 02147 char *z; 02148 02149 assert( pTo!=0 ); 02150 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end; 02151 if( pFromCol==0 ){ 02152 int iCol = p->nCol-1; 02153 if( iCol<0 ) goto fk_end; 02154 if( pToCol && pToCol->nExpr!=1 ){ 02155 sqlite3ErrorMsg(pParse, "foreign key on %s" 02156 " should reference only one column of table %T", 02157 p->aCol[iCol].zName, pTo); 02158 goto fk_end; 02159 } 02160 nCol = 1; 02161 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 02162 sqlite3ErrorMsg(pParse, 02163 "number of columns in foreign key does not match the number of " 02164 "columns in the referenced table"); 02165 goto fk_end; 02166 }else{ 02167 nCol = pFromCol->nExpr; 02168 } 02169 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1; 02170 if( pToCol ){ 02171 for(i=0; i<pToCol->nExpr; i++){ 02172 nByte += strlen(pToCol->a[i].zName) + 1; 02173 } 02174 } 02175 pFKey = sqlite3DbMallocZero(db, nByte ); 02176 if( pFKey==0 ){ 02177 goto fk_end; 02178 } 02179 pFKey->pFrom = p; 02180 pFKey->pNextFrom = p->pFKey; 02181 z = (char*)&pFKey[1]; 02182 pFKey->aCol = (struct sColMap*)z; 02183 z += sizeof(struct sColMap)*nCol; 02184 pFKey->zTo = z; 02185 memcpy(z, pTo->z, pTo->n); 02186 z[pTo->n] = 0; 02187 z += pTo->n+1; 02188 pFKey->pNextTo = 0; 02189 pFKey->nCol = nCol; 02190 if( pFromCol==0 ){ 02191 pFKey->aCol[0].iFrom = p->nCol-1; 02192 }else{ 02193 for(i=0; i<nCol; i++){ 02194 int j; 02195 for(j=0; j<p->nCol; j++){ 02196 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 02197 pFKey->aCol[i].iFrom = j; 02198 break; 02199 } 02200 } 02201 if( j>=p->nCol ){ 02202 sqlite3ErrorMsg(pParse, 02203 "unknown column \"%s\" in foreign key definition", 02204 pFromCol->a[i].zName); 02205 goto fk_end; 02206 } 02207 } 02208 } 02209 if( pToCol ){ 02210 for(i=0; i<nCol; i++){ 02211 int n = strlen(pToCol->a[i].zName); 02212 pFKey->aCol[i].zCol = z; 02213 memcpy(z, pToCol->a[i].zName, n); 02214 z[n] = 0; 02215 z += n+1; 02216 } 02217 } 02218 pFKey->isDeferred = 0; 02219 pFKey->deleteConf = flags & 0xff; 02220 pFKey->updateConf = (flags >> 8 ) & 0xff; 02221 pFKey->insertConf = (flags >> 16 ) & 0xff; 02222 02223 /* Link the foreign key to the table as the last step. 02224 */ 02225 p->pFKey = pFKey; 02226 pFKey = 0; 02227 02228 fk_end: 02229 sqlite3DbFree(db, pFKey); 02230 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 02231 sqlite3ExprListDelete(db, pFromCol); 02232 sqlite3ExprListDelete(db, pToCol); 02233 } 02234 02235 /* 02236 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 02237 ** clause is seen as part of a foreign key definition. The isDeferred 02238 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 02239 ** The behavior of the most recently created foreign key is adjusted 02240 ** accordingly. 02241 */ 02242 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 02243 #ifndef SQLITE_OMIT_FOREIGN_KEY 02244 Table *pTab; 02245 FKey *pFKey; 02246 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 02247 pFKey->isDeferred = isDeferred; 02248 #endif 02249 } 02250 02251 /* 02252 ** Generate code that will erase and refill index *pIdx. This is 02253 ** used to initialize a newly created index or to recompute the 02254 ** content of an index in response to a REINDEX command. 02255 ** 02256 ** if memRootPage is not negative, it means that the index is newly 02257 ** created. The register specified by memRootPage contains the 02258 ** root page number of the index. If memRootPage is negative, then 02259 ** the index already exists and must be cleared before being refilled and 02260 ** the root page number of the index is taken from pIndex->tnum. 02261 */ 02262 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 02263 Table *pTab = pIndex->pTable; /* The table that is indexed */ 02264 int iTab = pParse->nTab; /* Btree cursor used for pTab */ 02265 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */ 02266 int addr1; /* Address of top of loop */ 02267 int tnum; /* Root page of index */ 02268 Vdbe *v; /* Generate code into this virtual machine */ 02269 KeyInfo *pKey; /* KeyInfo for index */ 02270 int regIdxKey; /* Registers containing the index key */ 02271 int regRecord; /* Register holding assemblied index record */ 02272 sqlite3 *db = pParse->db; /* The database connection */ 02273 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 02274 02275 #ifndef SQLITE_OMIT_AUTHORIZATION 02276 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 02277 db->aDb[iDb].zName ) ){ 02278 return; 02279 } 02280 #endif 02281 02282 /* Require a write-lock on the table to perform this operation */ 02283 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 02284 02285 v = sqlite3GetVdbe(pParse); 02286 if( v==0 ) return; 02287 if( memRootPage>=0 ){ 02288 tnum = memRootPage; 02289 }else{ 02290 tnum = pIndex->tnum; 02291 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 02292 } 02293 pKey = sqlite3IndexKeyinfo(pParse, pIndex); 02294 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 02295 (char *)pKey, P4_KEYINFO_HANDOFF); 02296 if( memRootPage>=0 ){ 02297 sqlite3VdbeChangeP5(v, 1); 02298 } 02299 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 02300 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); 02301 regRecord = sqlite3GetTempReg(pParse); 02302 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1); 02303 if( pIndex->onError!=OE_None ){ 02304 int j1, j2; 02305 int regRowid; 02306 02307 regRowid = regIdxKey + pIndex->nColumn; 02308 j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn); 02309 j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, 02310 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32); 02311 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0, 02312 "indexed columns are not unique", P4_STATIC); 02313 sqlite3VdbeJumpHere(v, j1); 02314 sqlite3VdbeJumpHere(v, j2); 02315 } 02316 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 02317 sqlite3ReleaseTempReg(pParse, regRecord); 02318 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); 02319 sqlite3VdbeJumpHere(v, addr1); 02320 sqlite3VdbeAddOp1(v, OP_Close, iTab); 02321 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 02322 } 02323 02324 /* 02325 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 02326 ** and pTblList is the name of the table that is to be indexed. Both will 02327 ** be NULL for a primary key or an index that is created to satisfy a 02328 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 02329 ** as the table to be indexed. pParse->pNewTable is a table that is 02330 ** currently being constructed by a CREATE TABLE statement. 02331 ** 02332 ** pList is a list of columns to be indexed. pList will be NULL if this 02333 ** is a primary key or unique-constraint on the most recent column added 02334 ** to the table currently under construction. 02335 */ 02336 void sqlite3CreateIndex( 02337 Parse *pParse, /* All information about this parse */ 02338 Token *pName1, /* First part of index name. May be NULL */ 02339 Token *pName2, /* Second part of index name. May be NULL */ 02340 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 02341 ExprList *pList, /* A list of columns to be indexed */ 02342 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 02343 Token *pStart, /* The CREATE token that begins this statement */ 02344 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */ 02345 int sortOrder, /* Sort order of primary key when pList==NULL */ 02346 int ifNotExist /* Omit error if index already exists */ 02347 ){ 02348 Table *pTab = 0; /* Table to be indexed */ 02349 Index *pIndex = 0; /* The index to be created */ 02350 char *zName = 0; /* Name of the index */ 02351 int nName; /* Number of characters in zName */ 02352 int i, j; 02353 Token nullId; /* Fake token for an empty ID list */ 02354 DbFixer sFix; /* For assigning database names to pTable */ 02355 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 02356 sqlite3 *db = pParse->db; 02357 Db *pDb; /* The specific table containing the indexed database */ 02358 int iDb; /* Index of the database that is being written */ 02359 Token *pName = 0; /* Unqualified name of the index to create */ 02360 struct ExprList_item *pListItem; /* For looping over pList */ 02361 int nCol; 02362 int nExtra = 0; 02363 char *zExtra; 02364 02365 if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){ 02366 goto exit_create_index; 02367 } 02368 02369 /* 02370 ** Find the table that is to be indexed. Return early if not found. 02371 */ 02372 if( pTblName!=0 ){ 02373 02374 /* Use the two-part index name to determine the database 02375 ** to search for the table. 'Fix' the table name to this db 02376 ** before looking up the table. 02377 */ 02378 assert( pName1 && pName2 ); 02379 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 02380 if( iDb<0 ) goto exit_create_index; 02381 02382 #ifndef SQLITE_OMIT_TEMPDB 02383 /* If the index name was unqualified, check if the the table 02384 ** is a temp table. If so, set the database to 1. Do not do this 02385 ** if initialising a database schema. 02386 */ 02387 if( !db->init.busy ){ 02388 pTab = sqlite3SrcListLookup(pParse, pTblName); 02389 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 02390 iDb = 1; 02391 } 02392 } 02393 #endif 02394 02395 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && 02396 sqlite3FixSrcList(&sFix, pTblName) 02397 ){ 02398 /* Because the parser constructs pTblName from a single identifier, 02399 ** sqlite3FixSrcList can never fail. */ 02400 assert(0); 02401 } 02402 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 02403 pTblName->a[0].zDatabase); 02404 if( !pTab || db->mallocFailed ) goto exit_create_index; 02405 assert( db->aDb[iDb].pSchema==pTab->pSchema ); 02406 }else{ 02407 assert( pName==0 ); 02408 pTab = pParse->pNewTable; 02409 if( !pTab ) goto exit_create_index; 02410 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 02411 } 02412 pDb = &db->aDb[iDb]; 02413 02414 if( pTab==0 || pParse->nErr ) goto exit_create_index; 02415 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 02416 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 02417 goto exit_create_index; 02418 } 02419 #ifndef SQLITE_OMIT_VIEW 02420 if( pTab->pSelect ){ 02421 sqlite3ErrorMsg(pParse, "views may not be indexed"); 02422 goto exit_create_index; 02423 } 02424 #endif 02425 #ifndef SQLITE_OMIT_VIRTUALTABLE 02426 if( IsVirtual(pTab) ){ 02427 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 02428 goto exit_create_index; 02429 } 02430 #endif 02431 02432 /* 02433 ** Find the name of the index. Make sure there is not already another 02434 ** index or table with the same name. 02435 ** 02436 ** Exception: If we are reading the names of permanent indices from the 02437 ** sqlite_master table (because some other process changed the schema) and 02438 ** one of the index names collides with the name of a temporary table or 02439 ** index, then we will continue to process this index. 02440 ** 02441 ** If pName==0 it means that we are 02442 ** dealing with a primary key or UNIQUE constraint. We have to invent our 02443 ** own name. 02444 */ 02445 if( pName ){ 02446 zName = sqlite3NameFromToken(db, pName); 02447 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; 02448 if( zName==0 ) goto exit_create_index; 02449 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 02450 goto exit_create_index; 02451 } 02452 if( !db->init.busy ){ 02453 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; 02454 if( sqlite3FindTable(db, zName, 0)!=0 ){ 02455 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 02456 goto exit_create_index; 02457 } 02458 } 02459 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ 02460 if( !ifNotExist ){ 02461 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 02462 } 02463 goto exit_create_index; 02464 } 02465 }else{ 02466 int n; 02467 Index *pLoop; 02468 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 02469 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 02470 if( zName==0 ){ 02471 goto exit_create_index; 02472 } 02473 } 02474 02475 /* Check for authorization to create an index. 02476 */ 02477 #ifndef SQLITE_OMIT_AUTHORIZATION 02478 { 02479 const char *zDb = pDb->zName; 02480 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 02481 goto exit_create_index; 02482 } 02483 i = SQLITE_CREATE_INDEX; 02484 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 02485 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 02486 goto exit_create_index; 02487 } 02488 } 02489 #endif 02490 02491 /* If pList==0, it means this routine was called to make a primary 02492 ** key out of the last column added to the table under construction. 02493 ** So create a fake list to simulate this. 02494 */ 02495 if( pList==0 ){ 02496 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName; 02497 nullId.n = strlen((char*)nullId.z); 02498 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId); 02499 if( pList==0 ) goto exit_create_index; 02500 pList->a[0].sortOrder = sortOrder; 02501 } 02502 02503 /* Figure out how many bytes of space are required to store explicitly 02504 ** specified collation sequence names. 02505 */ 02506 for(i=0; i<pList->nExpr; i++){ 02507 Expr *pExpr; 02508 CollSeq *pColl; 02509 if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){ 02510 nExtra += (1 + strlen(pColl->zName)); 02511 } 02512 } 02513 02514 /* 02515 ** Allocate the index structure. 02516 */ 02517 nName = strlen(zName); 02518 nCol = pList->nExpr; 02519 pIndex = sqlite3DbMallocZero(db, 02520 sizeof(Index) + /* Index structure */ 02521 sizeof(int)*nCol + /* Index.aiColumn */ 02522 sizeof(int)*(nCol+1) + /* Index.aiRowEst */ 02523 sizeof(char *)*nCol + /* Index.azColl */ 02524 sizeof(u8)*nCol + /* Index.aSortOrder */ 02525 nName + 1 + /* Index.zName */ 02526 nExtra /* Collation sequence names */ 02527 ); 02528 if( db->mallocFailed ){ 02529 goto exit_create_index; 02530 } 02531 pIndex->azColl = (char**)(&pIndex[1]); 02532 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); 02533 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]); 02534 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]); 02535 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); 02536 zExtra = (char *)(&pIndex->zName[nName+1]); 02537 memcpy(pIndex->zName, zName, nName+1); 02538 pIndex->pTable = pTab; 02539 pIndex->nColumn = pList->nExpr; 02540 pIndex->onError = onError; 02541 pIndex->autoIndex = pName==0; 02542 pIndex->pSchema = db->aDb[iDb].pSchema; 02543 02544 /* Check to see if we should honor DESC requests on index columns 02545 */ 02546 if( pDb->pSchema->file_format>=4 ){ 02547 sortOrderMask = -1; /* Honor DESC */ 02548 }else{ 02549 sortOrderMask = 0; /* Ignore DESC */ 02550 } 02551 02552 /* Scan the names of the columns of the table to be indexed and 02553 ** load the column indices into the Index structure. Report an error 02554 ** if any column is not found. 02555 */ 02556 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 02557 const char *zColName = pListItem->zName; 02558 Column *pTabCol; 02559 int requestedSortOrder; 02560 char *zColl; /* Collation sequence name */ 02561 02562 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){ 02563 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; 02564 } 02565 if( j>=pTab->nCol ){ 02566 sqlite3ErrorMsg(pParse, "table %s has no column named %s", 02567 pTab->zName, zColName); 02568 goto exit_create_index; 02569 } 02570 /* TODO: Add a test to make sure that the same column is not named 02571 ** more than once within the same index. Only the first instance of 02572 ** the column will ever be used by the optimizer. Note that using the 02573 ** same column more than once cannot be an error because that would 02574 ** break backwards compatibility - it needs to be a warning. 02575 */ 02576 pIndex->aiColumn[i] = j; 02577 if( pListItem->pExpr && pListItem->pExpr->pColl ){ 02578 assert( pListItem->pExpr->pColl ); 02579 zColl = zExtra; 02580 sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName); 02581 zExtra += (strlen(zColl) + 1); 02582 }else{ 02583 zColl = pTab->aCol[j].zColl; 02584 if( !zColl ){ 02585 zColl = db->pDfltColl->zName; 02586 } 02587 } 02588 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){ 02589 goto exit_create_index; 02590 } 02591 pIndex->azColl[i] = zColl; 02592 requestedSortOrder = pListItem->sortOrder & sortOrderMask; 02593 pIndex->aSortOrder[i] = requestedSortOrder; 02594 } 02595 sqlite3DefaultRowEst(pIndex); 02596 02597 if( pTab==pParse->pNewTable ){ 02598 /* This routine has been called to create an automatic index as a 02599 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 02600 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 02601 ** i.e. one of: 02602 ** 02603 ** CREATE TABLE t(x PRIMARY KEY, y); 02604 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 02605 ** 02606 ** Either way, check to see if the table already has such an index. If 02607 ** so, don't bother creating this one. This only applies to 02608 ** automatically created indices. Users can do as they wish with 02609 ** explicit indices. 02610 */ 02611 Index *pIdx; 02612 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 02613 int k; 02614 assert( pIdx->onError!=OE_None ); 02615 assert( pIdx->autoIndex ); 02616 assert( pIndex->onError!=OE_None ); 02617 02618 if( pIdx->nColumn!=pIndex->nColumn ) continue; 02619 for(k=0; k<pIdx->nColumn; k++){ 02620 const char *z1 = pIdx->azColl[k]; 02621 const char *z2 = pIndex->azColl[k]; 02622 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 02623 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break; 02624 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; 02625 } 02626 if( k==pIdx->nColumn ){ 02627 if( pIdx->onError!=pIndex->onError ){ 02628 /* This constraint creates the same index as a previous 02629 ** constraint specified somewhere in the CREATE TABLE statement. 02630 ** However the ON CONFLICT clauses are different. If both this 02631 ** constraint and the previous equivalent constraint have explicit 02632 ** ON CONFLICT clauses this is an error. Otherwise, use the 02633 ** explicitly specified behaviour for the index. 02634 */ 02635 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 02636 sqlite3ErrorMsg(pParse, 02637 "conflicting ON CONFLICT clauses specified", 0); 02638 } 02639 if( pIdx->onError==OE_Default ){ 02640 pIdx->onError = pIndex->onError; 02641 } 02642 } 02643 goto exit_create_index; 02644 } 02645 } 02646 } 02647 02648 /* Link the new Index structure to its table and to the other 02649 ** in-memory database structures. 02650 */ 02651 if( db->init.busy ){ 02652 Index *p; 02653 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 02654 pIndex->zName, strlen(pIndex->zName)+1, pIndex); 02655 if( p ){ 02656 assert( p==pIndex ); /* Malloc must have failed */ 02657 db->mallocFailed = 1; 02658 goto exit_create_index; 02659 } 02660 db->flags |= SQLITE_InternChanges; 02661 if( pTblName!=0 ){ 02662 pIndex->tnum = db->init.newTnum; 02663 } 02664 } 02665 02666 /* If the db->init.busy is 0 then create the index on disk. This 02667 ** involves writing the index into the master table and filling in the 02668 ** index with the current table contents. 02669 ** 02670 ** The db->init.busy is 0 when the user first enters a CREATE INDEX 02671 ** command. db->init.busy is 1 when a database is opened and 02672 ** CREATE INDEX statements are read out of the master table. In 02673 ** the latter case the index already exists on disk, which is why 02674 ** we don't want to recreate it. 02675 ** 02676 ** If pTblName==0 it means this index is generated as a primary key 02677 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table 02678 ** has just been created, it contains no data and the index initialization 02679 ** step can be skipped. 02680 */ 02681 else if( db->init.busy==0 ){ 02682 Vdbe *v; 02683 char *zStmt; 02684 int iMem = ++pParse->nMem; 02685 02686 v = sqlite3GetVdbe(pParse); 02687 if( v==0 ) goto exit_create_index; 02688 02689 02690 /* Create the rootpage for the index 02691 */ 02692 sqlite3BeginWriteOperation(pParse, 1, iDb); 02693 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 02694 02695 /* Gather the complete text of the CREATE INDEX statement into 02696 ** the zStmt variable 02697 */ 02698 if( pStart && pEnd ){ 02699 /* A named index with an explicit CREATE INDEX statement */ 02700 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 02701 onError==OE_None ? "" : " UNIQUE", 02702 pEnd->z - pName->z + 1, 02703 pName->z); 02704 }else{ 02705 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 02706 /* zStmt = sqlite3MPrintf(""); */ 02707 zStmt = 0; 02708 } 02709 02710 /* Add an entry in sqlite_master for this index 02711 */ 02712 sqlite3NestedParse(pParse, 02713 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 02714 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 02715 pIndex->zName, 02716 pTab->zName, 02717 iMem, 02718 zStmt 02719 ); 02720 sqlite3DbFree(db, zStmt); 02721 02722 /* Fill the index with data and reparse the schema. Code an OP_Expire 02723 ** to invalidate all pre-compiled statements. 02724 */ 02725 if( pTblName ){ 02726 sqlite3RefillIndex(pParse, pIndex, iMem); 02727 sqlite3ChangeCookie(pParse, iDb); 02728 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 02729 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC); 02730 sqlite3VdbeAddOp1(v, OP_Expire, 0); 02731 } 02732 } 02733 02734 /* When adding an index to the list of indices for a table, make 02735 ** sure all indices labeled OE_Replace come after all those labeled 02736 ** OE_Ignore. This is necessary for the correct operation of UPDATE 02737 ** and INSERT. 02738 */ 02739 if( db->init.busy || pTblName==0 ){ 02740 if( onError!=OE_Replace || pTab->pIndex==0 02741 || pTab->pIndex->onError==OE_Replace){ 02742 pIndex->pNext = pTab->pIndex; 02743 pTab->pIndex = pIndex; 02744 }else{ 02745 Index *pOther = pTab->pIndex; 02746 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 02747 pOther = pOther->pNext; 02748 } 02749 pIndex->pNext = pOther->pNext; 02750 pOther->pNext = pIndex; 02751 } 02752 pIndex = 0; 02753 } 02754 02755 /* Clean up before exiting */ 02756 exit_create_index: 02757 if( pIndex ){ 02758 freeIndex(pIndex); 02759 } 02760 sqlite3ExprListDelete(db, pList); 02761 sqlite3SrcListDelete(db, pTblName); 02762 sqlite3DbFree(db, zName); 02763 return; 02764 } 02765 02766 /* 02767 ** Generate code to make sure the file format number is at least minFormat. 02768 ** The generated code will increase the file format number if necessary. 02769 */ 02770 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ 02771 Vdbe *v; 02772 v = sqlite3GetVdbe(pParse); 02773 if( v ){ 02774 int r1 = sqlite3GetTempReg(pParse); 02775 int r2 = sqlite3GetTempReg(pParse); 02776 int j1; 02777 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1); 02778 sqlite3VdbeUsesBtree(v, iDb); 02779 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2); 02780 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1); 02781 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2); 02782 sqlite3VdbeJumpHere(v, j1); 02783 sqlite3ReleaseTempReg(pParse, r1); 02784 sqlite3ReleaseTempReg(pParse, r2); 02785 } 02786 } 02787 02788 /* 02789 ** Fill the Index.aiRowEst[] array with default information - information 02790 ** to be used when we have not run the ANALYZE command. 02791 ** 02792 ** aiRowEst[0] is suppose to contain the number of elements in the index. 02793 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 02794 ** number of rows in the table that match any particular value of the 02795 ** first column of the index. aiRowEst[2] is an estimate of the number 02796 ** of rows that match any particular combiniation of the first 2 columns 02797 ** of the index. And so forth. It must always be the case that 02798 * 02799 ** aiRowEst[N]<=aiRowEst[N-1] 02800 ** aiRowEst[N]>=1 02801 ** 02802 ** Apart from that, we have little to go on besides intuition as to 02803 ** how aiRowEst[] should be initialized. The numbers generated here 02804 ** are based on typical values found in actual indices. 02805 */ 02806 void sqlite3DefaultRowEst(Index *pIdx){ 02807 unsigned *a = pIdx->aiRowEst; 02808 int i; 02809 assert( a!=0 ); 02810 a[0] = 1000000; 02811 for(i=pIdx->nColumn; i>=5; i--){ 02812 a[i] = 5; 02813 } 02814 while( i>=1 ){ 02815 a[i] = 11 - i; 02816 i--; 02817 } 02818 if( pIdx->onError!=OE_None ){ 02819 a[pIdx->nColumn] = 1; 02820 } 02821 } 02822 02823 /* 02824 ** This routine will drop an existing named index. This routine 02825 ** implements the DROP INDEX statement. 02826 */ 02827 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 02828 Index *pIndex; 02829 Vdbe *v; 02830 sqlite3 *db = pParse->db; 02831 int iDb; 02832 02833 if( pParse->nErr || db->mallocFailed ){ 02834 goto exit_drop_index; 02835 } 02836 assert( pName->nSrc==1 ); 02837 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 02838 goto exit_drop_index; 02839 } 02840 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 02841 if( pIndex==0 ){ 02842 if( !ifExists ){ 02843 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 02844 } 02845 pParse->checkSchema = 1; 02846 goto exit_drop_index; 02847 } 02848 if( pIndex->autoIndex ){ 02849 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 02850 "or PRIMARY KEY constraint cannot be dropped", 0); 02851 goto exit_drop_index; 02852 } 02853 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 02854 #ifndef SQLITE_OMIT_AUTHORIZATION 02855 { 02856 int code = SQLITE_DROP_INDEX; 02857 Table *pTab = pIndex->pTable; 02858 const char *zDb = db->aDb[iDb].zName; 02859 const char *zTab = SCHEMA_TABLE(iDb); 02860 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 02861 goto exit_drop_index; 02862 } 02863 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 02864 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 02865 goto exit_drop_index; 02866 } 02867 } 02868 #endif 02869 02870 /* Generate code to remove the index and from the master table */ 02871 v = sqlite3GetVdbe(pParse); 02872 if( v ){ 02873 sqlite3BeginWriteOperation(pParse, 1, iDb); 02874 sqlite3NestedParse(pParse, 02875 "DELETE FROM %Q.%s WHERE name=%Q", 02876 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 02877 pIndex->zName 02878 ); 02879 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 02880 sqlite3NestedParse(pParse, 02881 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q", 02882 db->aDb[iDb].zName, pIndex->zName 02883 ); 02884 } 02885 sqlite3ChangeCookie(pParse, iDb); 02886 destroyRootPage(pParse, pIndex->tnum, iDb); 02887 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 02888 } 02889 02890 exit_drop_index: 02891 sqlite3SrcListDelete(db, pName); 02892 } 02893 02894 /* 02895 ** pArray is a pointer to an array of objects. Each object in the 02896 ** array is szEntry bytes in size. This routine allocates a new 02897 ** object on the end of the array. 02898 ** 02899 ** *pnEntry is the number of entries already in use. *pnAlloc is 02900 ** the previously allocated size of the array. initSize is the 02901 ** suggested initial array size allocation. 02902 ** 02903 ** The index of the new entry is returned in *pIdx. 02904 ** 02905 ** This routine returns a pointer to the array of objects. This 02906 ** might be the same as the pArray parameter or it might be a different 02907 ** pointer if the array was resized. 02908 */ 02909 void *sqlite3ArrayAllocate( 02910 sqlite3 *db, /* Connection to notify of malloc failures */ 02911 void *pArray, /* Array of objects. Might be reallocated */ 02912 int szEntry, /* Size of each object in the array */ 02913 int initSize, /* Suggested initial allocation, in elements */ 02914 int *pnEntry, /* Number of objects currently in use */ 02915 int *pnAlloc, /* Current size of the allocation, in elements */ 02916 int *pIdx /* Write the index of a new slot here */ 02917 ){ 02918 char *z; 02919 if( *pnEntry >= *pnAlloc ){ 02920 void *pNew; 02921 int newSize; 02922 newSize = (*pnAlloc)*2 + initSize; 02923 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry); 02924 if( pNew==0 ){ 02925 *pIdx = -1; 02926 return pArray; 02927 } 02928 *pnAlloc = newSize; 02929 pArray = pNew; 02930 } 02931 z = (char*)pArray; 02932 memset(&z[*pnEntry * szEntry], 0, szEntry); 02933 *pIdx = *pnEntry; 02934 ++*pnEntry; 02935 return pArray; 02936 } 02937 02938 /* 02939 ** Append a new element to the given IdList. Create a new IdList if 02940 ** need be. 02941 ** 02942 ** A new IdList is returned, or NULL if malloc() fails. 02943 */ 02944 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 02945 int i; 02946 if( pList==0 ){ 02947 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 02948 if( pList==0 ) return 0; 02949 pList->nAlloc = 0; 02950 } 02951 pList->a = sqlite3ArrayAllocate( 02952 db, 02953 pList->a, 02954 sizeof(pList->a[0]), 02955 5, 02956 &pList->nId, 02957 &pList->nAlloc, 02958 &i 02959 ); 02960 if( i<0 ){ 02961 sqlite3IdListDelete(db, pList); 02962 return 0; 02963 } 02964 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 02965 return pList; 02966 } 02967 02968 /* 02969 ** Delete an IdList. 02970 */ 02971 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 02972 int i; 02973 if( pList==0 ) return; 02974 for(i=0; i<pList->nId; i++){ 02975 sqlite3DbFree(db, pList->a[i].zName); 02976 } 02977 sqlite3DbFree(db, pList->a); 02978 sqlite3DbFree(db, pList); 02979 } 02980 02981 /* 02982 ** Return the index in pList of the identifier named zId. Return -1 02983 ** if not found. 02984 */ 02985 int sqlite3IdListIndex(IdList *pList, const char *zName){ 02986 int i; 02987 if( pList==0 ) return -1; 02988 for(i=0; i<pList->nId; i++){ 02989 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 02990 } 02991 return -1; 02992 } 02993 02994 /* 02995 ** Expand the space allocated for the given SrcList object by 02996 ** creating nExtra new slots beginning at iStart. iStart is zero based. 02997 ** New slots are zeroed. 02998 ** 02999 ** For example, suppose a SrcList initially contains two entries: A,B. 03000 ** To append 3 new entries onto the end, do this: 03001 ** 03002 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 03003 ** 03004 ** After the call above it would contain: A, B, nil, nil, nil. 03005 ** If the iStart argument had been 1 instead of 2, then the result 03006 ** would have been: A, nil, nil, nil, B. To prepend the new slots, 03007 ** the iStart value would be 0. The result then would 03008 ** be: nil, nil, nil, A, B. 03009 ** 03010 ** If a memory allocation fails the SrcList is unchanged. The 03011 ** db->mallocFailed flag will be set to true. 03012 */ 03013 SrcList *sqlite3SrcListEnlarge( 03014 sqlite3 *db, /* Database connection to notify of OOM errors */ 03015 SrcList *pSrc, /* The SrcList to be enlarged */ 03016 int nExtra, /* Number of new slots to add to pSrc->a[] */ 03017 int iStart /* Index in pSrc->a[] of first new slot */ 03018 ){ 03019 int i; 03020 03021 /* Sanity checking on calling parameters */ 03022 assert( iStart>=0 ); 03023 assert( nExtra>=1 ); 03024 if( pSrc==0 || iStart>pSrc->nSrc ){ 03025 assert( db->mallocFailed ); 03026 return pSrc; 03027 } 03028 03029 /* Allocate additional space if needed */ 03030 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){ 03031 SrcList *pNew; 03032 int nAlloc = pSrc->nSrc+nExtra; 03033 pNew = sqlite3DbRealloc(db, pSrc, 03034 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 03035 if( pNew==0 ){ 03036 assert( db->mallocFailed ); 03037 return pSrc; 03038 } 03039 pSrc = pNew; 03040 pSrc->nAlloc = nAlloc; 03041 } 03042 03043 /* Move existing slots that come after the newly inserted slots 03044 ** out of the way */ 03045 for(i=pSrc->nSrc-1; i>=iStart; i--){ 03046 pSrc->a[i+nExtra] = pSrc->a[i]; 03047 } 03048 pSrc->nSrc += nExtra; 03049 03050 /* Zero the newly allocated slots */ 03051 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 03052 for(i=iStart; i<iStart+nExtra; i++){ 03053 pSrc->a[i].iCursor = -1; 03054 } 03055 03056 /* Return a pointer to the enlarged SrcList */ 03057 return pSrc; 03058 } 03059 03060 03061 /* 03062 ** Append a new table name to the given SrcList. Create a new SrcList if 03063 ** need be. A new entry is created in the SrcList even if pToken is NULL. 03064 ** 03065 ** A SrcList is returned, or NULL if there is an OOM error. The returned 03066 ** SrcList might be the same as the SrcList that was input or it might be 03067 ** a new one. If an OOM error does occurs, then the prior value of pList 03068 ** that is input to this routine is automatically freed. 03069 ** 03070 ** If pDatabase is not null, it means that the table has an optional 03071 ** database name prefix. Like this: "database.table". The pDatabase 03072 ** points to the table name and the pTable points to the database name. 03073 ** The SrcList.a[].zName field is filled with the table name which might 03074 ** come from pTable (if pDatabase is NULL) or from pDatabase. 03075 ** SrcList.a[].zDatabase is filled with the database name from pTable, 03076 ** or with NULL if no database is specified. 03077 ** 03078 ** In other words, if call like this: 03079 ** 03080 ** sqlite3SrcListAppend(D,A,B,0); 03081 ** 03082 ** Then B is a table name and the database name is unspecified. If called 03083 ** like this: 03084 ** 03085 ** sqlite3SrcListAppend(D,A,B,C); 03086 ** 03087 ** Then C is the table name and B is the database name. 03088 */ 03089 SrcList *sqlite3SrcListAppend( 03090 sqlite3 *db, /* Connection to notify of malloc failures */ 03091 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 03092 Token *pTable, /* Table to append */ 03093 Token *pDatabase /* Database of the table */ 03094 ){ 03095 struct SrcList_item *pItem; 03096 if( pList==0 ){ 03097 pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); 03098 if( pList==0 ) return 0; 03099 pList->nAlloc = 1; 03100 } 03101 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); 03102 if( db->mallocFailed ){ 03103 sqlite3SrcListDelete(db, pList); 03104 return 0; 03105 } 03106 pItem = &pList->a[pList->nSrc-1]; 03107 if( pDatabase && pDatabase->z==0 ){ 03108 pDatabase = 0; 03109 } 03110 if( pDatabase && pTable ){ 03111 Token *pTemp = pDatabase; 03112 pDatabase = pTable; 03113 pTable = pTemp; 03114 } 03115 pItem->zName = sqlite3NameFromToken(db, pTable); 03116 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); 03117 return pList; 03118 } 03119 03120 /* 03121 ** Assign VdbeCursor index numbers to all tables in a SrcList 03122 */ 03123 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 03124 int i; 03125 struct SrcList_item *pItem; 03126 assert(pList || pParse->db->mallocFailed ); 03127 if( pList ){ 03128 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 03129 if( pItem->iCursor>=0 ) break; 03130 pItem->iCursor = pParse->nTab++; 03131 if( pItem->pSelect ){ 03132 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 03133 } 03134 } 03135 } 03136 } 03137 03138 /* 03139 ** Delete an entire SrcList including all its substructure. 03140 */ 03141 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 03142 int i; 03143 struct SrcList_item *pItem; 03144 if( pList==0 ) return; 03145 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 03146 sqlite3DbFree(db, pItem->zDatabase); 03147 sqlite3DbFree(db, pItem->zName); 03148 sqlite3DbFree(db, pItem->zAlias); 03149 sqlite3DbFree(db, pItem->zIndex); 03150 sqlite3DeleteTable(pItem->pTab); 03151 sqlite3SelectDelete(db, pItem->pSelect); 03152 sqlite3ExprDelete(db, pItem->pOn); 03153 sqlite3IdListDelete(db, pItem->pUsing); 03154 } 03155 sqlite3DbFree(db, pList); 03156 } 03157 03158 /* 03159 ** This routine is called by the parser to add a new term to the 03160 ** end of a growing FROM clause. The "p" parameter is the part of 03161 ** the FROM clause that has already been constructed. "p" is NULL 03162 ** if this is the first term of the FROM clause. pTable and pDatabase 03163 ** are the name of the table and database named in the FROM clause term. 03164 ** pDatabase is NULL if the database name qualifier is missing - the 03165 ** usual case. If the term has a alias, then pAlias points to the 03166 ** alias token. If the term is a subquery, then pSubquery is the 03167 ** SELECT statement that the subquery encodes. The pTable and 03168 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 03169 ** parameters are the content of the ON and USING clauses. 03170 ** 03171 ** Return a new SrcList which encodes is the FROM with the new 03172 ** term added. 03173 */ 03174 SrcList *sqlite3SrcListAppendFromTerm( 03175 Parse *pParse, /* Parsing context */ 03176 SrcList *p, /* The left part of the FROM clause already seen */ 03177 Token *pTable, /* Name of the table to add to the FROM clause */ 03178 Token *pDatabase, /* Name of the database containing pTable */ 03179 Token *pAlias, /* The right-hand side of the AS subexpression */ 03180 Select *pSubquery, /* A subquery used in place of a table name */ 03181 Expr *pOn, /* The ON clause of a join */ 03182 IdList *pUsing /* The USING clause of a join */ 03183 ){ 03184 struct SrcList_item *pItem; 03185 sqlite3 *db = pParse->db; 03186 p = sqlite3SrcListAppend(db, p, pTable, pDatabase); 03187 if( p==0 || p->nSrc==0 ){ 03188 sqlite3ExprDelete(db, pOn); 03189 sqlite3IdListDelete(db, pUsing); 03190 sqlite3SelectDelete(db, pSubquery); 03191 return p; 03192 } 03193 pItem = &p->a[p->nSrc-1]; 03194 if( pAlias && pAlias->n ){ 03195 pItem->zAlias = sqlite3NameFromToken(db, pAlias); 03196 } 03197 pItem->pSelect = pSubquery; 03198 pItem->pOn = pOn; 03199 pItem->pUsing = pUsing; 03200 return p; 03201 } 03202 03203 /* 03204 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 03205 ** element of the source-list passed as the second argument. 03206 */ 03207 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 03208 if( pIndexedBy && p && p->nSrc>0 ){ 03209 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 03210 assert( pItem->notIndexed==0 && pItem->zIndex==0 ); 03211 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 03212 /* A "NOT INDEXED" clause was supplied. See parse.y 03213 ** construct "indexed_opt" for details. */ 03214 pItem->notIndexed = 1; 03215 }else{ 03216 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy); 03217 } 03218 } 03219 } 03220 03221 /* 03222 ** When building up a FROM clause in the parser, the join operator 03223 ** is initially attached to the left operand. But the code generator 03224 ** expects the join operator to be on the right operand. This routine 03225 ** Shifts all join operators from left to right for an entire FROM 03226 ** clause. 03227 ** 03228 ** Example: Suppose the join is like this: 03229 ** 03230 ** A natural cross join B 03231 ** 03232 ** The operator is "natural cross join". The A and B operands are stored 03233 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 03234 ** operator with A. This routine shifts that operator over to B. 03235 */ 03236 void sqlite3SrcListShiftJoinType(SrcList *p){ 03237 if( p && p->a ){ 03238 int i; 03239 for(i=p->nSrc-1; i>0; i--){ 03240 p->a[i].jointype = p->a[i-1].jointype; 03241 } 03242 p->a[0].jointype = 0; 03243 } 03244 } 03245 03246 /* 03247 ** Begin a transaction 03248 */ 03249 void sqlite3BeginTransaction(Parse *pParse, int type){ 03250 sqlite3 *db; 03251 Vdbe *v; 03252 int i; 03253 03254 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 03255 if( pParse->nErr || db->mallocFailed ) return; 03256 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return; 03257 03258 v = sqlite3GetVdbe(pParse); 03259 if( !v ) return; 03260 if( type!=TK_DEFERRED ){ 03261 for(i=0; i<db->nDb; i++){ 03262 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 03263 sqlite3VdbeUsesBtree(v, i); 03264 } 03265 } 03266 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); 03267 } 03268 03269 /* 03270 ** Commit a transaction 03271 */ 03272 void sqlite3CommitTransaction(Parse *pParse){ 03273 sqlite3 *db; 03274 Vdbe *v; 03275 03276 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 03277 if( pParse->nErr || db->mallocFailed ) return; 03278 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return; 03279 03280 v = sqlite3GetVdbe(pParse); 03281 if( v ){ 03282 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); 03283 } 03284 } 03285 03286 /* 03287 ** Rollback a transaction 03288 */ 03289 void sqlite3RollbackTransaction(Parse *pParse){ 03290 sqlite3 *db; 03291 Vdbe *v; 03292 03293 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 03294 if( pParse->nErr || db->mallocFailed ) return; 03295 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return; 03296 03297 v = sqlite3GetVdbe(pParse); 03298 if( v ){ 03299 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 03300 } 03301 } 03302 03303 /* 03304 ** Make sure the TEMP database is open and available for use. Return 03305 ** the number of errors. Leave any error messages in the pParse structure. 03306 */ 03307 int sqlite3OpenTempDatabase(Parse *pParse){ 03308 sqlite3 *db = pParse->db; 03309 if( db->aDb[1].pBt==0 && !pParse->explain ){ 03310 int rc; 03311 static const int flags = 03312 SQLITE_OPEN_READWRITE | 03313 SQLITE_OPEN_CREATE | 03314 SQLITE_OPEN_EXCLUSIVE | 03315 SQLITE_OPEN_DELETEONCLOSE | 03316 SQLITE_OPEN_TEMP_DB; 03317 03318 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, 03319 &db->aDb[1].pBt); 03320 if( rc!=SQLITE_OK ){ 03321 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 03322 "file for storing temporary tables"); 03323 pParse->rc = rc; 03324 return 1; 03325 } 03326 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit ); 03327 assert( db->aDb[1].pSchema ); 03328 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt), 03329 db->dfltJournalMode); 03330 } 03331 return 0; 03332 } 03333 03334 /* 03335 ** Generate VDBE code that will verify the schema cookie and start 03336 ** a read-transaction for all named database files. 03337 ** 03338 ** It is important that all schema cookies be verified and all 03339 ** read transactions be started before anything else happens in 03340 ** the VDBE program. But this routine can be called after much other 03341 ** code has been generated. So here is what we do: 03342 ** 03343 ** The first time this routine is called, we code an OP_Goto that 03344 ** will jump to a subroutine at the end of the program. Then we 03345 ** record every database that needs its schema verified in the 03346 ** pParse->cookieMask field. Later, after all other code has been 03347 ** generated, the subroutine that does the cookie verifications and 03348 ** starts the transactions will be coded and the OP_Goto P2 value 03349 ** will be made to point to that subroutine. The generation of the 03350 ** cookie verification subroutine code happens in sqlite3FinishCoding(). 03351 ** 03352 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the 03353 ** schema on any databases. This can be used to position the OP_Goto 03354 ** early in the code, before we know if any database tables will be used. 03355 */ 03356 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 03357 sqlite3 *db; 03358 Vdbe *v; 03359 int mask; 03360 03361 v = sqlite3GetVdbe(pParse); 03362 if( v==0 ) return; /* This only happens if there was a prior error */ 03363 db = pParse->db; 03364 if( pParse->cookieGoto==0 ){ 03365 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; 03366 } 03367 if( iDb>=0 ){ 03368 assert( iDb<db->nDb ); 03369 assert( db->aDb[iDb].pBt!=0 || iDb==1 ); 03370 assert( iDb<SQLITE_MAX_ATTACHED+2 ); 03371 mask = 1<<iDb; 03372 if( (pParse->cookieMask & mask)==0 ){ 03373 pParse->cookieMask |= mask; 03374 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; 03375 if( !OMIT_TEMPDB && iDb==1 ){ 03376 sqlite3OpenTempDatabase(pParse); 03377 } 03378 } 03379 } 03380 } 03381 03382 /* 03383 ** Generate VDBE code that prepares for doing an operation that 03384 ** might change the database. 03385 ** 03386 ** This routine starts a new transaction if we are not already within 03387 ** a transaction. If we are already within a transaction, then a checkpoint 03388 ** is set if the setStatement parameter is true. A checkpoint should 03389 ** be set for operations that might fail (due to a constraint) part of 03390 ** the way through and which will need to undo some writes without having to 03391 ** rollback the whole transaction. For operations where all constraints 03392 ** can be checked before any changes are made to the database, it is never 03393 ** necessary to undo a write and the checkpoint should not be set. 03394 ** 03395 ** Only database iDb and the temp database are made writable by this call. 03396 ** If iDb==0, then the main and temp databases are made writable. If 03397 ** iDb==1 then only the temp database is made writable. If iDb>1 then the 03398 ** specified auxiliary database and the temp database are made writable. 03399 */ 03400 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 03401 Vdbe *v = sqlite3GetVdbe(pParse); 03402 if( v==0 ) return; 03403 sqlite3CodeVerifySchema(pParse, iDb); 03404 pParse->writeMask |= 1<<iDb; 03405 if( setStatement && pParse->nested==0 ){ 03406 sqlite3VdbeAddOp1(v, OP_Statement, iDb); 03407 } 03408 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){ 03409 sqlite3BeginWriteOperation(pParse, setStatement, 1); 03410 } 03411 } 03412 03413 /* 03414 ** Check to see if pIndex uses the collating sequence pColl. Return 03415 ** true if it does and false if it does not. 03416 */ 03417 #ifndef SQLITE_OMIT_REINDEX 03418 static int collationMatch(const char *zColl, Index *pIndex){ 03419 int i; 03420 for(i=0; i<pIndex->nColumn; i++){ 03421 const char *z = pIndex->azColl[i]; 03422 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){ 03423 return 1; 03424 } 03425 } 03426 return 0; 03427 } 03428 #endif 03429 03430 /* 03431 ** Recompute all indices of pTab that use the collating sequence pColl. 03432 ** If pColl==0 then recompute all indices of pTab. 03433 */ 03434 #ifndef SQLITE_OMIT_REINDEX 03435 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 03436 Index *pIndex; /* An index associated with pTab */ 03437 03438 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 03439 if( zColl==0 || collationMatch(zColl, pIndex) ){ 03440 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 03441 sqlite3BeginWriteOperation(pParse, 0, iDb); 03442 sqlite3RefillIndex(pParse, pIndex, -1); 03443 } 03444 } 03445 } 03446 #endif 03447 03448 /* 03449 ** Recompute all indices of all tables in all databases where the 03450 ** indices use the collating sequence pColl. If pColl==0 then recompute 03451 ** all indices everywhere. 03452 */ 03453 #ifndef SQLITE_OMIT_REINDEX 03454 static void reindexDatabases(Parse *pParse, char const *zColl){ 03455 Db *pDb; /* A single database */ 03456 int iDb; /* The database index number */ 03457 sqlite3 *db = pParse->db; /* The database connection */ 03458 HashElem *k; /* For looping over tables in pDb */ 03459 Table *pTab; /* A table in the database */ 03460 03461 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 03462 assert( pDb!=0 ); 03463 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 03464 pTab = (Table*)sqliteHashData(k); 03465 reindexTable(pParse, pTab, zColl); 03466 } 03467 } 03468 } 03469 #endif 03470 03471 /* 03472 ** Generate code for the REINDEX command. 03473 ** 03474 ** REINDEX -- 1 03475 ** REINDEX <collation> -- 2 03476 ** REINDEX ?<database>.?<tablename> -- 3 03477 ** REINDEX ?<database>.?<indexname> -- 4 03478 ** 03479 ** Form 1 causes all indices in all attached databases to be rebuilt. 03480 ** Form 2 rebuilds all indices in all databases that use the named 03481 ** collating function. Forms 3 and 4 rebuild the named index or all 03482 ** indices associated with the named table. 03483 */ 03484 #ifndef SQLITE_OMIT_REINDEX 03485 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 03486 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 03487 char *z; /* Name of a table or index */ 03488 const char *zDb; /* Name of the database */ 03489 Table *pTab; /* A table in the database */ 03490 Index *pIndex; /* An index associated with pTab */ 03491 int iDb; /* The database index number */ 03492 sqlite3 *db = pParse->db; /* The database connection */ 03493 Token *pObjName; /* Name of the table or index to be reindexed */ 03494 03495 /* Read the database schema. If an error occurs, leave an error message 03496 ** and code in pParse and return NULL. */ 03497 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 03498 return; 03499 } 03500 03501 if( pName1==0 || pName1->z==0 ){ 03502 reindexDatabases(pParse, 0); 03503 return; 03504 }else if( pName2==0 || pName2->z==0 ){ 03505 char *zColl; 03506 assert( pName1->z ); 03507 zColl = sqlite3NameFromToken(pParse->db, pName1); 03508 if( !zColl ) return; 03509 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0); 03510 if( pColl ){ 03511 if( zColl ){ 03512 reindexDatabases(pParse, zColl); 03513 sqlite3DbFree(db, zColl); 03514 } 03515 return; 03516 } 03517 sqlite3DbFree(db, zColl); 03518 } 03519 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 03520 if( iDb<0 ) return; 03521 z = sqlite3NameFromToken(db, pObjName); 03522 if( z==0 ) return; 03523 zDb = db->aDb[iDb].zName; 03524 pTab = sqlite3FindTable(db, z, zDb); 03525 if( pTab ){ 03526 reindexTable(pParse, pTab, 0); 03527 sqlite3DbFree(db, z); 03528 return; 03529 } 03530 pIndex = sqlite3FindIndex(db, z, zDb); 03531 sqlite3DbFree(db, z); 03532 if( pIndex ){ 03533 sqlite3BeginWriteOperation(pParse, 0, iDb); 03534 sqlite3RefillIndex(pParse, pIndex, -1); 03535 return; 03536 } 03537 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 03538 } 03539 #endif 03540 03541 /* 03542 ** Return a dynamicly allocated KeyInfo structure that can be used 03543 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx. 03544 ** 03545 ** If successful, a pointer to the new structure is returned. In this case 03546 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 03547 ** pointer. If an error occurs (out of memory or missing collation 03548 ** sequence), NULL is returned and the state of pParse updated to reflect 03549 ** the error. 03550 */ 03551 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ 03552 int i; 03553 int nCol = pIdx->nColumn; 03554 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol; 03555 sqlite3 *db = pParse->db; 03556 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes); 03557 03558 if( pKey ){ 03559 pKey->db = pParse->db; 03560 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]); 03561 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) ); 03562 for(i=0; i<nCol; i++){ 03563 char *zColl = pIdx->azColl[i]; 03564 assert( zColl ); 03565 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1); 03566 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 03567 } 03568 pKey->nField = nCol; 03569 } 03570 03571 if( pParse->nErr ){ 03572 sqlite3DbFree(db, pKey); 03573 pKey = 0; 03574 } 03575 return pKey; 03576 }
ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:52 2011 by Doxygen 1.6.1