| OLD | NEW |
| (Empty) |
| 1 /* | |
| 2 ** 2001 September 15 | |
| 3 ** | |
| 4 ** The author disclaims copyright to this source code. In place of | |
| 5 ** a legal notice, here is a blessing: | |
| 6 ** | |
| 7 ** May you do good and not evil. | |
| 8 ** May you find forgiveness for yourself and forgive others. | |
| 9 ** May you share freely, never taking more than you give. | |
| 10 ** | |
| 11 ************************************************************************* | |
| 12 ** This file contains C code routines that are called by the SQLite parser | |
| 13 ** when syntax rules are reduced. The routines in this file handle the | |
| 14 ** following kinds of SQL syntax: | |
| 15 ** | |
| 16 ** CREATE TABLE | |
| 17 ** DROP TABLE | |
| 18 ** CREATE INDEX | |
| 19 ** DROP INDEX | |
| 20 ** creating ID lists | |
| 21 ** BEGIN TRANSACTION | |
| 22 ** COMMIT | |
| 23 ** ROLLBACK | |
| 24 */ | |
| 25 #include "sqliteInt.h" | |
| 26 | |
| 27 /* | |
| 28 ** This routine is called when a new SQL statement is beginning to | |
| 29 ** be parsed. Initialize the pParse structure as needed. | |
| 30 */ | |
| 31 void sqlite3BeginParse(Parse *pParse, int explainFlag){ | |
| 32 pParse->explain = (u8)explainFlag; | |
| 33 pParse->nVar = 0; | |
| 34 } | |
| 35 | |
| 36 #ifndef SQLITE_OMIT_SHARED_CACHE | |
| 37 /* | |
| 38 ** The TableLock structure is only used by the sqlite3TableLock() and | |
| 39 ** codeTableLocks() functions. | |
| 40 */ | |
| 41 struct TableLock { | |
| 42 int iDb; /* The database containing the table to be locked */ | |
| 43 int iTab; /* The root page of the table to be locked */ | |
| 44 u8 isWriteLock; /* True for write lock. False for a read lock */ | |
| 45 const char *zName; /* Name of the table */ | |
| 46 }; | |
| 47 | |
| 48 /* | |
| 49 ** Record the fact that we want to lock a table at run-time. | |
| 50 ** | |
| 51 ** The table to be locked has root page iTab and is found in database iDb. | |
| 52 ** A read or a write lock can be taken depending on isWritelock. | |
| 53 ** | |
| 54 ** This routine just records the fact that the lock is desired. The | |
| 55 ** code to make the lock occur is generated by a later call to | |
| 56 ** codeTableLocks() which occurs during sqlite3FinishCoding(). | |
| 57 */ | |
| 58 void sqlite3TableLock( | |
| 59 Parse *pParse, /* Parsing context */ | |
| 60 int iDb, /* Index of the database containing the table to lock */ | |
| 61 int iTab, /* Root page number of the table to be locked */ | |
| 62 u8 isWriteLock, /* True for a write lock */ | |
| 63 const char *zName /* Name of the table to be locked */ | |
| 64 ){ | |
| 65 Parse *pToplevel = sqlite3ParseToplevel(pParse); | |
| 66 int i; | |
| 67 int nBytes; | |
| 68 TableLock *p; | |
| 69 assert( iDb>=0 ); | |
| 70 | |
| 71 for(i=0; i<pToplevel->nTableLock; i++){ | |
| 72 p = &pToplevel->aTableLock[i]; | |
| 73 if( p->iDb==iDb && p->iTab==iTab ){ | |
| 74 p->isWriteLock = (p->isWriteLock || isWriteLock); | |
| 75 return; | |
| 76 } | |
| 77 } | |
| 78 | |
| 79 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); | |
| 80 pToplevel->aTableLock = | |
| 81 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); | |
| 82 if( pToplevel->aTableLock ){ | |
| 83 p = &pToplevel->aTableLock[pToplevel->nTableLock++]; | |
| 84 p->iDb = iDb; | |
| 85 p->iTab = iTab; | |
| 86 p->isWriteLock = isWriteLock; | |
| 87 p->zName = zName; | |
| 88 }else{ | |
| 89 pToplevel->nTableLock = 0; | |
| 90 pToplevel->db->mallocFailed = 1; | |
| 91 } | |
| 92 } | |
| 93 | |
| 94 /* | |
| 95 ** Code an OP_TableLock instruction for each table locked by the | |
| 96 ** statement (configured by calls to sqlite3TableLock()). | |
| 97 */ | |
| 98 static void codeTableLocks(Parse *pParse){ | |
| 99 int i; | |
| 100 Vdbe *pVdbe; | |
| 101 | |
| 102 pVdbe = sqlite3GetVdbe(pParse); | |
| 103 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ | |
| 104 | |
| 105 for(i=0; i<pParse->nTableLock; i++){ | |
| 106 TableLock *p = &pParse->aTableLock[i]; | |
| 107 int p1 = p->iDb; | |
| 108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, | |
| 109 p->zName, P4_STATIC); | |
| 110 } | |
| 111 } | |
| 112 #else | |
| 113 #define codeTableLocks(x) | |
| 114 #endif | |
| 115 | |
| 116 /* | |
| 117 ** Return TRUE if the given yDbMask object is empty - if it contains no | |
| 118 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() | |
| 119 ** macros when SQLITE_MAX_ATTACHED is greater than 30. | |
| 120 */ | |
| 121 #if SQLITE_MAX_ATTACHED>30 | |
| 122 int sqlite3DbMaskAllZero(yDbMask m){ | |
| 123 int i; | |
| 124 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0; | |
| 125 return 1; | |
| 126 } | |
| 127 #endif | |
| 128 | |
| 129 /* | |
| 130 ** This routine is called after a single SQL statement has been | |
| 131 ** parsed and a VDBE program to execute that statement has been | |
| 132 ** prepared. This routine puts the finishing touches on the | |
| 133 ** VDBE program and resets the pParse structure for the next | |
| 134 ** parse. | |
| 135 ** | |
| 136 ** Note that if an error occurred, it might be the case that | |
| 137 ** no VDBE code was generated. | |
| 138 */ | |
| 139 void sqlite3FinishCoding(Parse *pParse){ | |
| 140 sqlite3 *db; | |
| 141 Vdbe *v; | |
| 142 | |
| 143 assert( pParse->pToplevel==0 ); | |
| 144 db = pParse->db; | |
| 145 if( pParse->nested ) return; | |
| 146 if( db->mallocFailed || pParse->nErr ){ | |
| 147 if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; | |
| 148 return; | |
| 149 } | |
| 150 | |
| 151 /* Begin by generating some termination code at the end of the | |
| 152 ** vdbe program | |
| 153 */ | |
| 154 v = sqlite3GetVdbe(pParse); | |
| 155 assert( !pParse->isMultiWrite | |
| 156 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); | |
| 157 if( v ){ | |
| 158 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){} | |
| 159 sqlite3VdbeAddOp0(v, OP_Halt); | |
| 160 | |
| 161 #if SQLITE_USER_AUTHENTICATION | |
| 162 if( pParse->nTableLock>0 && db->init.busy==0 ){ | |
| 163 sqlite3UserAuthInit(db); | |
| 164 if( db->auth.authLevel<UAUTH_User ){ | |
| 165 pParse->rc = SQLITE_AUTH_USER; | |
| 166 sqlite3ErrorMsg(pParse, "user not authenticated"); | |
| 167 return; | |
| 168 } | |
| 169 } | |
| 170 #endif | |
| 171 | |
| 172 /* The cookie mask contains one bit for each database file open. | |
| 173 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are | |
| 174 ** set for each database that is used. Generate code to start a | |
| 175 ** transaction on each used database and to verify the schema cookie | |
| 176 ** on each used database. | |
| 177 */ | |
| 178 if( db->mallocFailed==0 | |
| 179 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) | |
| 180 ){ | |
| 181 int iDb, i; | |
| 182 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); | |
| 183 sqlite3VdbeJumpHere(v, 0); | |
| 184 for(iDb=0; iDb<db->nDb; iDb++){ | |
| 185 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; | |
| 186 sqlite3VdbeUsesBtree(v, iDb); | |
| 187 sqlite3VdbeAddOp4Int(v, | |
| 188 OP_Transaction, /* Opcode */ | |
| 189 iDb, /* P1 */ | |
| 190 DbMaskTest(pParse->writeMask,iDb), /* P2 */ | |
| 191 pParse->cookieValue[iDb], /* P3 */ | |
| 192 db->aDb[iDb].pSchema->iGeneration /* P4 */ | |
| 193 ); | |
| 194 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); | |
| 195 VdbeComment((v, | |
| 196 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); | |
| 197 } | |
| 198 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 199 for(i=0; i<pParse->nVtabLock; i++){ | |
| 200 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); | |
| 201 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); | |
| 202 } | |
| 203 pParse->nVtabLock = 0; | |
| 204 #endif | |
| 205 | |
| 206 /* Once all the cookies have been verified and transactions opened, | |
| 207 ** obtain the required table-locks. This is a no-op unless the | |
| 208 ** shared-cache feature is enabled. | |
| 209 */ | |
| 210 codeTableLocks(pParse); | |
| 211 | |
| 212 /* Initialize any AUTOINCREMENT data structures required. | |
| 213 */ | |
| 214 sqlite3AutoincrementBegin(pParse); | |
| 215 | |
| 216 /* Code constant expressions that where factored out of inner loops */ | |
| 217 if( pParse->pConstExpr ){ | |
| 218 ExprList *pEL = pParse->pConstExpr; | |
| 219 pParse->okConstFactor = 0; | |
| 220 for(i=0; i<pEL->nExpr; i++){ | |
| 221 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); | |
| 222 } | |
| 223 } | |
| 224 | |
| 225 /* Finally, jump back to the beginning of the executable code. */ | |
| 226 sqlite3VdbeGoto(v, 1); | |
| 227 } | |
| 228 } | |
| 229 | |
| 230 | |
| 231 /* Get the VDBE program ready for execution | |
| 232 */ | |
| 233 if( v && pParse->nErr==0 && !db->mallocFailed ){ | |
| 234 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ | |
| 235 /* A minimum of one cursor is required if autoincrement is used | |
| 236 * See ticket [a696379c1f08866] */ | |
| 237 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; | |
| 238 sqlite3VdbeMakeReady(v, pParse); | |
| 239 pParse->rc = SQLITE_DONE; | |
| 240 pParse->colNamesSet = 0; | |
| 241 }else{ | |
| 242 pParse->rc = SQLITE_ERROR; | |
| 243 } | |
| 244 pParse->nTab = 0; | |
| 245 pParse->nMem = 0; | |
| 246 pParse->nSet = 0; | |
| 247 pParse->nVar = 0; | |
| 248 DbMaskZero(pParse->cookieMask); | |
| 249 } | |
| 250 | |
| 251 /* | |
| 252 ** Run the parser and code generator recursively in order to generate | |
| 253 ** code for the SQL statement given onto the end of the pParse context | |
| 254 ** currently under construction. When the parser is run recursively | |
| 255 ** this way, the final OP_Halt is not appended and other initialization | |
| 256 ** and finalization steps are omitted because those are handling by the | |
| 257 ** outermost parser. | |
| 258 ** | |
| 259 ** Not everything is nestable. This facility is designed to permit | |
| 260 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use | |
| 261 ** care if you decide to try to use this routine for some other purposes. | |
| 262 */ | |
| 263 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ | |
| 264 va_list ap; | |
| 265 char *zSql; | |
| 266 char *zErrMsg = 0; | |
| 267 sqlite3 *db = pParse->db; | |
| 268 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) | |
| 269 char saveBuf[SAVE_SZ]; | |
| 270 | |
| 271 if( pParse->nErr ) return; | |
| 272 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ | |
| 273 va_start(ap, zFormat); | |
| 274 zSql = sqlite3VMPrintf(db, zFormat, ap); | |
| 275 va_end(ap); | |
| 276 if( zSql==0 ){ | |
| 277 return; /* A malloc must have failed */ | |
| 278 } | |
| 279 pParse->nested++; | |
| 280 memcpy(saveBuf, &pParse->nVar, SAVE_SZ); | |
| 281 memset(&pParse->nVar, 0, SAVE_SZ); | |
| 282 sqlite3RunParser(pParse, zSql, &zErrMsg); | |
| 283 sqlite3DbFree(db, zErrMsg); | |
| 284 sqlite3DbFree(db, zSql); | |
| 285 memcpy(&pParse->nVar, saveBuf, SAVE_SZ); | |
| 286 pParse->nested--; | |
| 287 } | |
| 288 | |
| 289 #if SQLITE_USER_AUTHENTICATION | |
| 290 /* | |
| 291 ** Return TRUE if zTable is the name of the system table that stores the | |
| 292 ** list of users and their access credentials. | |
| 293 */ | |
| 294 int sqlite3UserAuthTable(const char *zTable){ | |
| 295 return sqlite3_stricmp(zTable, "sqlite_user")==0; | |
| 296 } | |
| 297 #endif | |
| 298 | |
| 299 /* | |
| 300 ** Locate the in-memory structure that describes a particular database | |
| 301 ** table given the name of that table and (optionally) the name of the | |
| 302 ** database containing the table. Return NULL if not found. | |
| 303 ** | |
| 304 ** If zDatabase is 0, all databases are searched for the table and the | |
| 305 ** first matching table is returned. (No checking for duplicate table | |
| 306 ** names is done.) The search order is TEMP first, then MAIN, then any | |
| 307 ** auxiliary databases added using the ATTACH command. | |
| 308 ** | |
| 309 ** See also sqlite3LocateTable(). | |
| 310 */ | |
| 311 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ | |
| 312 Table *p = 0; | |
| 313 int i; | |
| 314 | |
| 315 /* All mutexes are required for schema access. Make sure we hold them. */ | |
| 316 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); | |
| 317 #if SQLITE_USER_AUTHENTICATION | |
| 318 /* Only the admin user is allowed to know that the sqlite_user table | |
| 319 ** exists */ | |
| 320 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ | |
| 321 return 0; | |
| 322 } | |
| 323 #endif | |
| 324 for(i=OMIT_TEMPDB; i<db->nDb; i++){ | |
| 325 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ | |
| 326 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; | |
| 327 assert( sqlite3SchemaMutexHeld(db, j, 0) ); | |
| 328 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); | |
| 329 if( p ) break; | |
| 330 } | |
| 331 return p; | |
| 332 } | |
| 333 | |
| 334 /* | |
| 335 ** Locate the in-memory structure that describes a particular database | |
| 336 ** table given the name of that table and (optionally) the name of the | |
| 337 ** database containing the table. Return NULL if not found. Also leave an | |
| 338 ** error message in pParse->zErrMsg. | |
| 339 ** | |
| 340 ** The difference between this routine and sqlite3FindTable() is that this | |
| 341 ** routine leaves an error message in pParse->zErrMsg where | |
| 342 ** sqlite3FindTable() does not. | |
| 343 */ | |
| 344 Table *sqlite3LocateTable( | |
| 345 Parse *pParse, /* context in which to report errors */ | |
| 346 int isView, /* True if looking for a VIEW rather than a TABLE */ | |
| 347 const char *zName, /* Name of the table we are looking for */ | |
| 348 const char *zDbase /* Name of the database. Might be NULL */ | |
| 349 ){ | |
| 350 Table *p; | |
| 351 | |
| 352 /* Read the database schema. If an error occurs, leave an error message | |
| 353 ** and code in pParse and return NULL. */ | |
| 354 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ | |
| 355 return 0; | |
| 356 } | |
| 357 | |
| 358 p = sqlite3FindTable(pParse->db, zName, zDbase); | |
| 359 if( p==0 ){ | |
| 360 const char *zMsg = isView ? "no such view" : "no such table"; | |
| 361 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 362 if( sqlite3FindDbName(pParse->db, zDbase)<1 ){ | |
| 363 /* If zName is the not the name of a table in the schema created using | |
| 364 ** CREATE, then check to see if it is the name of an virtual table that | |
| 365 ** can be an eponymous virtual table. */ | |
| 366 Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); | |
| 367 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ | |
| 368 return pMod->pEpoTab; | |
| 369 } | |
| 370 } | |
| 371 #endif | |
| 372 if( zDbase ){ | |
| 373 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); | |
| 374 }else{ | |
| 375 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); | |
| 376 } | |
| 377 pParse->checkSchema = 1; | |
| 378 } | |
| 379 | |
| 380 return p; | |
| 381 } | |
| 382 | |
| 383 /* | |
| 384 ** Locate the table identified by *p. | |
| 385 ** | |
| 386 ** This is a wrapper around sqlite3LocateTable(). The difference between | |
| 387 ** sqlite3LocateTable() and this function is that this function restricts | |
| 388 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be | |
| 389 ** non-NULL if it is part of a view or trigger program definition. See | |
| 390 ** sqlite3FixSrcList() for details. | |
| 391 */ | |
| 392 Table *sqlite3LocateTableItem( | |
| 393 Parse *pParse, | |
| 394 int isView, | |
| 395 struct SrcList_item *p | |
| 396 ){ | |
| 397 const char *zDb; | |
| 398 assert( p->pSchema==0 || p->zDatabase==0 ); | |
| 399 if( p->pSchema ){ | |
| 400 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); | |
| 401 zDb = pParse->db->aDb[iDb].zName; | |
| 402 }else{ | |
| 403 zDb = p->zDatabase; | |
| 404 } | |
| 405 return sqlite3LocateTable(pParse, isView, p->zName, zDb); | |
| 406 } | |
| 407 | |
| 408 /* | |
| 409 ** Locate the in-memory structure that describes | |
| 410 ** a particular index given the name of that index | |
| 411 ** and the name of the database that contains the index. | |
| 412 ** Return NULL if not found. | |
| 413 ** | |
| 414 ** If zDatabase is 0, all databases are searched for the | |
| 415 ** table and the first matching index is returned. (No checking | |
| 416 ** for duplicate index names is done.) The search order is | |
| 417 ** TEMP first, then MAIN, then any auxiliary databases added | |
| 418 ** using the ATTACH command. | |
| 419 */ | |
| 420 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ | |
| 421 Index *p = 0; | |
| 422 int i; | |
| 423 /* All mutexes are required for schema access. Make sure we hold them. */ | |
| 424 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); | |
| 425 for(i=OMIT_TEMPDB; i<db->nDb; i++){ | |
| 426 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ | |
| 427 Schema *pSchema = db->aDb[j].pSchema; | |
| 428 assert( pSchema ); | |
| 429 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; | |
| 430 assert( sqlite3SchemaMutexHeld(db, j, 0) ); | |
| 431 p = sqlite3HashFind(&pSchema->idxHash, zName); | |
| 432 if( p ) break; | |
| 433 } | |
| 434 return p; | |
| 435 } | |
| 436 | |
| 437 /* | |
| 438 ** Reclaim the memory used by an index | |
| 439 */ | |
| 440 static void freeIndex(sqlite3 *db, Index *p){ | |
| 441 #ifndef SQLITE_OMIT_ANALYZE | |
| 442 sqlite3DeleteIndexSamples(db, p); | |
| 443 #endif | |
| 444 sqlite3ExprDelete(db, p->pPartIdxWhere); | |
| 445 sqlite3ExprListDelete(db, p->aColExpr); | |
| 446 sqlite3DbFree(db, p->zColAff); | |
| 447 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); | |
| 448 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | |
| 449 sqlite3_free(p->aiRowEst); | |
| 450 #endif | |
| 451 sqlite3DbFree(db, p); | |
| 452 } | |
| 453 | |
| 454 /* | |
| 455 ** For the index called zIdxName which is found in the database iDb, | |
| 456 ** unlike that index from its Table then remove the index from | |
| 457 ** the index hash table and free all memory structures associated | |
| 458 ** with the index. | |
| 459 */ | |
| 460 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ | |
| 461 Index *pIndex; | |
| 462 Hash *pHash; | |
| 463 | |
| 464 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 465 pHash = &db->aDb[iDb].pSchema->idxHash; | |
| 466 pIndex = sqlite3HashInsert(pHash, zIdxName, 0); | |
| 467 if( ALWAYS(pIndex) ){ | |
| 468 if( pIndex->pTable->pIndex==pIndex ){ | |
| 469 pIndex->pTable->pIndex = pIndex->pNext; | |
| 470 }else{ | |
| 471 Index *p; | |
| 472 /* Justification of ALWAYS(); The index must be on the list of | |
| 473 ** indices. */ | |
| 474 p = pIndex->pTable->pIndex; | |
| 475 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } | |
| 476 if( ALWAYS(p && p->pNext==pIndex) ){ | |
| 477 p->pNext = pIndex->pNext; | |
| 478 } | |
| 479 } | |
| 480 freeIndex(db, pIndex); | |
| 481 } | |
| 482 db->flags |= SQLITE_InternChanges; | |
| 483 } | |
| 484 | |
| 485 /* | |
| 486 ** Look through the list of open database files in db->aDb[] and if | |
| 487 ** any have been closed, remove them from the list. Reallocate the | |
| 488 ** db->aDb[] structure to a smaller size, if possible. | |
| 489 ** | |
| 490 ** Entry 0 (the "main" database) and entry 1 (the "temp" database) | |
| 491 ** are never candidates for being collapsed. | |
| 492 */ | |
| 493 void sqlite3CollapseDatabaseArray(sqlite3 *db){ | |
| 494 int i, j; | |
| 495 for(i=j=2; i<db->nDb; i++){ | |
| 496 struct Db *pDb = &db->aDb[i]; | |
| 497 if( pDb->pBt==0 ){ | |
| 498 sqlite3DbFree(db, pDb->zName); | |
| 499 pDb->zName = 0; | |
| 500 continue; | |
| 501 } | |
| 502 if( j<i ){ | |
| 503 db->aDb[j] = db->aDb[i]; | |
| 504 } | |
| 505 j++; | |
| 506 } | |
| 507 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); | |
| 508 db->nDb = j; | |
| 509 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ | |
| 510 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); | |
| 511 sqlite3DbFree(db, db->aDb); | |
| 512 db->aDb = db->aDbStatic; | |
| 513 } | |
| 514 } | |
| 515 | |
| 516 /* | |
| 517 ** Reset the schema for the database at index iDb. Also reset the | |
| 518 ** TEMP schema. | |
| 519 */ | |
| 520 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ | |
| 521 Db *pDb; | |
| 522 assert( iDb<db->nDb ); | |
| 523 | |
| 524 /* Case 1: Reset the single schema identified by iDb */ | |
| 525 pDb = &db->aDb[iDb]; | |
| 526 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 527 assert( pDb->pSchema!=0 ); | |
| 528 sqlite3SchemaClear(pDb->pSchema); | |
| 529 | |
| 530 /* If any database other than TEMP is reset, then also reset TEMP | |
| 531 ** since TEMP might be holding triggers that reference tables in the | |
| 532 ** other database. | |
| 533 */ | |
| 534 if( iDb!=1 ){ | |
| 535 pDb = &db->aDb[1]; | |
| 536 assert( pDb->pSchema!=0 ); | |
| 537 sqlite3SchemaClear(pDb->pSchema); | |
| 538 } | |
| 539 return; | |
| 540 } | |
| 541 | |
| 542 /* | |
| 543 ** Erase all schema information from all attached databases (including | |
| 544 ** "main" and "temp") for a single database connection. | |
| 545 */ | |
| 546 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ | |
| 547 int i; | |
| 548 sqlite3BtreeEnterAll(db); | |
| 549 for(i=0; i<db->nDb; i++){ | |
| 550 Db *pDb = &db->aDb[i]; | |
| 551 if( pDb->pSchema ){ | |
| 552 sqlite3SchemaClear(pDb->pSchema); | |
| 553 } | |
| 554 } | |
| 555 db->flags &= ~SQLITE_InternChanges; | |
| 556 sqlite3VtabUnlockList(db); | |
| 557 sqlite3BtreeLeaveAll(db); | |
| 558 sqlite3CollapseDatabaseArray(db); | |
| 559 } | |
| 560 | |
| 561 /* | |
| 562 ** This routine is called when a commit occurs. | |
| 563 */ | |
| 564 void sqlite3CommitInternalChanges(sqlite3 *db){ | |
| 565 db->flags &= ~SQLITE_InternChanges; | |
| 566 } | |
| 567 | |
| 568 /* | |
| 569 ** Delete memory allocated for the column names of a table or view (the | |
| 570 ** Table.aCol[] array). | |
| 571 */ | |
| 572 void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ | |
| 573 int i; | |
| 574 Column *pCol; | |
| 575 assert( pTable!=0 ); | |
| 576 if( (pCol = pTable->aCol)!=0 ){ | |
| 577 for(i=0; i<pTable->nCol; i++, pCol++){ | |
| 578 sqlite3DbFree(db, pCol->zName); | |
| 579 sqlite3ExprDelete(db, pCol->pDflt); | |
| 580 sqlite3DbFree(db, pCol->zDflt); | |
| 581 sqlite3DbFree(db, pCol->zType); | |
| 582 sqlite3DbFree(db, pCol->zColl); | |
| 583 } | |
| 584 sqlite3DbFree(db, pTable->aCol); | |
| 585 } | |
| 586 } | |
| 587 | |
| 588 /* | |
| 589 ** Remove the memory data structures associated with the given | |
| 590 ** Table. No changes are made to disk by this routine. | |
| 591 ** | |
| 592 ** This routine just deletes the data structure. It does not unlink | |
| 593 ** the table data structure from the hash table. But it does destroy | |
| 594 ** memory structures of the indices and foreign keys associated with | |
| 595 ** the table. | |
| 596 ** | |
| 597 ** The db parameter is optional. It is needed if the Table object | |
| 598 ** contains lookaside memory. (Table objects in the schema do not use | |
| 599 ** lookaside memory, but some ephemeral Table objects do.) Or the | |
| 600 ** db parameter can be used with db->pnBytesFreed to measure the memory | |
| 601 ** used by the Table object. | |
| 602 */ | |
| 603 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ | |
| 604 Index *pIndex, *pNext; | |
| 605 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ | |
| 606 | |
| 607 assert( !pTable || pTable->nRef>0 ); | |
| 608 | |
| 609 /* Do not delete the table until the reference count reaches zero. */ | |
| 610 if( !pTable ) return; | |
| 611 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; | |
| 612 | |
| 613 /* Record the number of outstanding lookaside allocations in schema Tables | |
| 614 ** prior to doing any free() operations. Since schema Tables do not use | |
| 615 ** lookaside, this number should not change. */ | |
| 616 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? | |
| 617 db->lookaside.nOut : 0 ); | |
| 618 | |
| 619 /* Delete all indices associated with this table. */ | |
| 620 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ | |
| 621 pNext = pIndex->pNext; | |
| 622 assert( pIndex->pSchema==pTable->pSchema ); | |
| 623 if( !db || db->pnBytesFreed==0 ){ | |
| 624 char *zName = pIndex->zName; | |
| 625 TESTONLY ( Index *pOld = ) sqlite3HashInsert( | |
| 626 &pIndex->pSchema->idxHash, zName, 0 | |
| 627 ); | |
| 628 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); | |
| 629 assert( pOld==pIndex || pOld==0 ); | |
| 630 } | |
| 631 freeIndex(db, pIndex); | |
| 632 } | |
| 633 | |
| 634 /* Delete any foreign keys attached to this table. */ | |
| 635 sqlite3FkDelete(db, pTable); | |
| 636 | |
| 637 /* Delete the Table structure itself. | |
| 638 */ | |
| 639 sqlite3DeleteColumnNames(db, pTable); | |
| 640 sqlite3DbFree(db, pTable->zName); | |
| 641 sqlite3DbFree(db, pTable->zColAff); | |
| 642 sqlite3SelectDelete(db, pTable->pSelect); | |
| 643 sqlite3ExprListDelete(db, pTable->pCheck); | |
| 644 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 645 sqlite3VtabClear(db, pTable); | |
| 646 #endif | |
| 647 sqlite3DbFree(db, pTable); | |
| 648 | |
| 649 /* Verify that no lookaside memory was used by schema tables */ | |
| 650 assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); | |
| 651 } | |
| 652 | |
| 653 /* | |
| 654 ** Unlink the given table from the hash tables and the delete the | |
| 655 ** table structure with all its indices and foreign keys. | |
| 656 */ | |
| 657 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ | |
| 658 Table *p; | |
| 659 Db *pDb; | |
| 660 | |
| 661 assert( db!=0 ); | |
| 662 assert( iDb>=0 && iDb<db->nDb ); | |
| 663 assert( zTabName ); | |
| 664 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 665 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ | |
| 666 pDb = &db->aDb[iDb]; | |
| 667 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); | |
| 668 sqlite3DeleteTable(db, p); | |
| 669 db->flags |= SQLITE_InternChanges; | |
| 670 } | |
| 671 | |
| 672 /* | |
| 673 ** Given a token, return a string that consists of the text of that | |
| 674 ** token. Space to hold the returned string | |
| 675 ** is obtained from sqliteMalloc() and must be freed by the calling | |
| 676 ** function. | |
| 677 ** | |
| 678 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that | |
| 679 ** surround the body of the token are removed. | |
| 680 ** | |
| 681 ** Tokens are often just pointers into the original SQL text and so | |
| 682 ** are not \000 terminated and are not persistent. The returned string | |
| 683 ** is \000 terminated and is persistent. | |
| 684 */ | |
| 685 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ | |
| 686 char *zName; | |
| 687 if( pName ){ | |
| 688 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); | |
| 689 sqlite3Dequote(zName); | |
| 690 }else{ | |
| 691 zName = 0; | |
| 692 } | |
| 693 return zName; | |
| 694 } | |
| 695 | |
| 696 /* | |
| 697 ** Open the sqlite_master table stored in database number iDb for | |
| 698 ** writing. The table is opened using cursor 0. | |
| 699 */ | |
| 700 void sqlite3OpenMasterTable(Parse *p, int iDb){ | |
| 701 Vdbe *v = sqlite3GetVdbe(p); | |
| 702 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); | |
| 703 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); | |
| 704 if( p->nTab==0 ){ | |
| 705 p->nTab = 1; | |
| 706 } | |
| 707 } | |
| 708 | |
| 709 /* | |
| 710 ** Parameter zName points to a nul-terminated buffer containing the name | |
| 711 ** of a database ("main", "temp" or the name of an attached db). This | |
| 712 ** function returns the index of the named database in db->aDb[], or | |
| 713 ** -1 if the named db cannot be found. | |
| 714 */ | |
| 715 int sqlite3FindDbName(sqlite3 *db, const char *zName){ | |
| 716 int i = -1; /* Database number */ | |
| 717 if( zName ){ | |
| 718 Db *pDb; | |
| 719 int n = sqlite3Strlen30(zName); | |
| 720 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ | |
| 721 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && | |
| 722 0==sqlite3StrICmp(pDb->zName, zName) ){ | |
| 723 break; | |
| 724 } | |
| 725 } | |
| 726 } | |
| 727 return i; | |
| 728 } | |
| 729 | |
| 730 /* | |
| 731 ** The token *pName contains the name of a database (either "main" or | |
| 732 ** "temp" or the name of an attached db). This routine returns the | |
| 733 ** index of the named database in db->aDb[], or -1 if the named db | |
| 734 ** does not exist. | |
| 735 */ | |
| 736 int sqlite3FindDb(sqlite3 *db, Token *pName){ | |
| 737 int i; /* Database number */ | |
| 738 char *zName; /* Name we are searching for */ | |
| 739 zName = sqlite3NameFromToken(db, pName); | |
| 740 i = sqlite3FindDbName(db, zName); | |
| 741 sqlite3DbFree(db, zName); | |
| 742 return i; | |
| 743 } | |
| 744 | |
| 745 /* The table or view or trigger name is passed to this routine via tokens | |
| 746 ** pName1 and pName2. If the table name was fully qualified, for example: | |
| 747 ** | |
| 748 ** CREATE TABLE xxx.yyy (...); | |
| 749 ** | |
| 750 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if | |
| 751 ** the table name is not fully qualified, i.e.: | |
| 752 ** | |
| 753 ** CREATE TABLE yyy(...); | |
| 754 ** | |
| 755 ** Then pName1 is set to "yyy" and pName2 is "". | |
| 756 ** | |
| 757 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or | |
| 758 ** pName2) that stores the unqualified table name. The index of the | |
| 759 ** database "xxx" is returned. | |
| 760 */ | |
| 761 int sqlite3TwoPartName( | |
| 762 Parse *pParse, /* Parsing and code generating context */ | |
| 763 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ | |
| 764 Token *pName2, /* The "yyy" in the name "xxx.yyy" */ | |
| 765 Token **pUnqual /* Write the unqualified object name here */ | |
| 766 ){ | |
| 767 int iDb; /* Database holding the object */ | |
| 768 sqlite3 *db = pParse->db; | |
| 769 | |
| 770 if( ALWAYS(pName2!=0) && pName2->n>0 ){ | |
| 771 if( db->init.busy ) { | |
| 772 sqlite3ErrorMsg(pParse, "corrupt database"); | |
| 773 return -1; | |
| 774 } | |
| 775 *pUnqual = pName2; | |
| 776 iDb = sqlite3FindDb(db, pName1); | |
| 777 if( iDb<0 ){ | |
| 778 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); | |
| 779 return -1; | |
| 780 } | |
| 781 }else{ | |
| 782 assert( db->init.iDb==0 || db->init.busy ); | |
| 783 iDb = db->init.iDb; | |
| 784 *pUnqual = pName1; | |
| 785 } | |
| 786 return iDb; | |
| 787 } | |
| 788 | |
| 789 /* | |
| 790 ** This routine is used to check if the UTF-8 string zName is a legal | |
| 791 ** unqualified name for a new schema object (table, index, view or | |
| 792 ** trigger). All names are legal except those that begin with the string | |
| 793 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace | |
| 794 ** is reserved for internal use. | |
| 795 */ | |
| 796 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ | |
| 797 if( !pParse->db->init.busy && pParse->nested==0 | |
| 798 && (pParse->db->flags & SQLITE_WriteSchema)==0 | |
| 799 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ | |
| 800 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); | |
| 801 return SQLITE_ERROR; | |
| 802 } | |
| 803 return SQLITE_OK; | |
| 804 } | |
| 805 | |
| 806 /* | |
| 807 ** Return the PRIMARY KEY index of a table | |
| 808 */ | |
| 809 Index *sqlite3PrimaryKeyIndex(Table *pTab){ | |
| 810 Index *p; | |
| 811 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} | |
| 812 return p; | |
| 813 } | |
| 814 | |
| 815 /* | |
| 816 ** Return the column of index pIdx that corresponds to table | |
| 817 ** column iCol. Return -1 if not found. | |
| 818 */ | |
| 819 i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ | |
| 820 int i; | |
| 821 for(i=0; i<pIdx->nColumn; i++){ | |
| 822 if( iCol==pIdx->aiColumn[i] ) return i; | |
| 823 } | |
| 824 return -1; | |
| 825 } | |
| 826 | |
| 827 /* | |
| 828 ** Begin constructing a new table representation in memory. This is | |
| 829 ** the first of several action routines that get called in response | |
| 830 ** to a CREATE TABLE statement. In particular, this routine is called | |
| 831 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp | |
| 832 ** flag is true if the table should be stored in the auxiliary database | |
| 833 ** file instead of in the main database file. This is normally the case | |
| 834 ** when the "TEMP" or "TEMPORARY" keyword occurs in between | |
| 835 ** CREATE and TABLE. | |
| 836 ** | |
| 837 ** The new table record is initialized and put in pParse->pNewTable. | |
| 838 ** As more of the CREATE TABLE statement is parsed, additional action | |
| 839 ** routines will be called to add more information to this record. | |
| 840 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine | |
| 841 ** is called to complete the construction of the new table record. | |
| 842 */ | |
| 843 void sqlite3StartTable( | |
| 844 Parse *pParse, /* Parser context */ | |
| 845 Token *pName1, /* First part of the name of the table or view */ | |
| 846 Token *pName2, /* Second part of the name of the table or view */ | |
| 847 int isTemp, /* True if this is a TEMP table */ | |
| 848 int isView, /* True if this is a VIEW */ | |
| 849 int isVirtual, /* True if this is a VIRTUAL table */ | |
| 850 int noErr /* Do nothing if table already exists */ | |
| 851 ){ | |
| 852 Table *pTable; | |
| 853 char *zName = 0; /* The name of the new table */ | |
| 854 sqlite3 *db = pParse->db; | |
| 855 Vdbe *v; | |
| 856 int iDb; /* Database number to create the table in */ | |
| 857 Token *pName; /* Unqualified name of the table to create */ | |
| 858 | |
| 859 /* The table or view name to create is passed to this routine via tokens | |
| 860 ** pName1 and pName2. If the table name was fully qualified, for example: | |
| 861 ** | |
| 862 ** CREATE TABLE xxx.yyy (...); | |
| 863 ** | |
| 864 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if | |
| 865 ** the table name is not fully qualified, i.e.: | |
| 866 ** | |
| 867 ** CREATE TABLE yyy(...); | |
| 868 ** | |
| 869 ** Then pName1 is set to "yyy" and pName2 is "". | |
| 870 ** | |
| 871 ** The call below sets the pName pointer to point at the token (pName1 or | |
| 872 ** pName2) that stores the unqualified table name. The variable iDb is | |
| 873 ** set to the index of the database that the table or view is to be | |
| 874 ** created in. | |
| 875 */ | |
| 876 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); | |
| 877 if( iDb<0 ) return; | |
| 878 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ | |
| 879 /* If creating a temp table, the name may not be qualified. Unless | |
| 880 ** the database name is "temp" anyway. */ | |
| 881 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); | |
| 882 return; | |
| 883 } | |
| 884 if( !OMIT_TEMPDB && isTemp ) iDb = 1; | |
| 885 | |
| 886 pParse->sNameToken = *pName; | |
| 887 zName = sqlite3NameFromToken(db, pName); | |
| 888 if( zName==0 ) return; | |
| 889 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ | |
| 890 goto begin_table_error; | |
| 891 } | |
| 892 if( db->init.iDb==1 ) isTemp = 1; | |
| 893 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 894 assert( (isTemp & 1)==isTemp ); | |
| 895 { | |
| 896 int code; | |
| 897 char *zDb = db->aDb[iDb].zName; | |
| 898 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ | |
| 899 goto begin_table_error; | |
| 900 } | |
| 901 if( isView ){ | |
| 902 if( !OMIT_TEMPDB && isTemp ){ | |
| 903 code = SQLITE_CREATE_TEMP_VIEW; | |
| 904 }else{ | |
| 905 code = SQLITE_CREATE_VIEW; | |
| 906 } | |
| 907 }else{ | |
| 908 if( !OMIT_TEMPDB && isTemp ){ | |
| 909 code = SQLITE_CREATE_TEMP_TABLE; | |
| 910 }else{ | |
| 911 code = SQLITE_CREATE_TABLE; | |
| 912 } | |
| 913 } | |
| 914 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ | |
| 915 goto begin_table_error; | |
| 916 } | |
| 917 } | |
| 918 #endif | |
| 919 | |
| 920 /* Make sure the new table name does not collide with an existing | |
| 921 ** index or table name in the same database. Issue an error message if | |
| 922 ** it does. The exception is if the statement being parsed was passed | |
| 923 ** to an sqlite3_declare_vtab() call. In that case only the column names | |
| 924 ** and types will be used, so there is no need to test for namespace | |
| 925 ** collisions. | |
| 926 */ | |
| 927 if( !IN_DECLARE_VTAB ){ | |
| 928 char *zDb = db->aDb[iDb].zName; | |
| 929 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ | |
| 930 goto begin_table_error; | |
| 931 } | |
| 932 pTable = sqlite3FindTable(db, zName, zDb); | |
| 933 if( pTable ){ | |
| 934 if( !noErr ){ | |
| 935 sqlite3ErrorMsg(pParse, "table %T already exists", pName); | |
| 936 }else{ | |
| 937 assert( !db->init.busy || CORRUPT_DB ); | |
| 938 sqlite3CodeVerifySchema(pParse, iDb); | |
| 939 } | |
| 940 goto begin_table_error; | |
| 941 } | |
| 942 if( sqlite3FindIndex(db, zName, zDb)!=0 ){ | |
| 943 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); | |
| 944 goto begin_table_error; | |
| 945 } | |
| 946 } | |
| 947 | |
| 948 pTable = sqlite3DbMallocZero(db, sizeof(Table)); | |
| 949 if( pTable==0 ){ | |
| 950 db->mallocFailed = 1; | |
| 951 pParse->rc = SQLITE_NOMEM; | |
| 952 pParse->nErr++; | |
| 953 goto begin_table_error; | |
| 954 } | |
| 955 pTable->zName = zName; | |
| 956 pTable->iPKey = -1; | |
| 957 pTable->pSchema = db->aDb[iDb].pSchema; | |
| 958 pTable->nRef = 1; | |
| 959 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); | |
| 960 assert( pParse->pNewTable==0 ); | |
| 961 pParse->pNewTable = pTable; | |
| 962 | |
| 963 /* If this is the magic sqlite_sequence table used by autoincrement, | |
| 964 ** then record a pointer to this table in the main database structure | |
| 965 ** so that INSERT can find the table easily. | |
| 966 */ | |
| 967 #ifndef SQLITE_OMIT_AUTOINCREMENT | |
| 968 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ | |
| 969 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 970 pTable->pSchema->pSeqTab = pTable; | |
| 971 } | |
| 972 #endif | |
| 973 | |
| 974 /* Begin generating the code that will insert the table record into | |
| 975 ** the SQLITE_MASTER table. Note in particular that we must go ahead | |
| 976 ** and allocate the record number for the table entry now. Before any | |
| 977 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause | |
| 978 ** indices to be created and the table record must come before the | |
| 979 ** indices. Hence, the record number for the table must be allocated | |
| 980 ** now. | |
| 981 */ | |
| 982 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ | |
| 983 int addr1; | |
| 984 int fileFormat; | |
| 985 int reg1, reg2, reg3; | |
| 986 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ | |
| 987 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; | |
| 988 sqlite3BeginWriteOperation(pParse, 1, iDb); | |
| 989 | |
| 990 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 991 if( isVirtual ){ | |
| 992 sqlite3VdbeAddOp0(v, OP_VBegin); | |
| 993 } | |
| 994 #endif | |
| 995 | |
| 996 /* If the file format and encoding in the database have not been set, | |
| 997 ** set them now. | |
| 998 */ | |
| 999 reg1 = pParse->regRowid = ++pParse->nMem; | |
| 1000 reg2 = pParse->regRoot = ++pParse->nMem; | |
| 1001 reg3 = ++pParse->nMem; | |
| 1002 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); | |
| 1003 sqlite3VdbeUsesBtree(v, iDb); | |
| 1004 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); | |
| 1005 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? | |
| 1006 1 : SQLITE_MAX_FILE_FORMAT; | |
| 1007 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); | |
| 1008 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3); | |
| 1009 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); | |
| 1010 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3); | |
| 1011 sqlite3VdbeJumpHere(v, addr1); | |
| 1012 | |
| 1013 /* This just creates a place-holder record in the sqlite_master table. | |
| 1014 ** The record created does not contain anything yet. It will be replaced | |
| 1015 ** by the real entry in code generated at sqlite3EndTable(). | |
| 1016 ** | |
| 1017 ** The rowid for the new entry is left in register pParse->regRowid. | |
| 1018 ** The root page number of the new table is left in reg pParse->regRoot. | |
| 1019 ** The rowid and root page number values are needed by the code that | |
| 1020 ** sqlite3EndTable will generate. | |
| 1021 */ | |
| 1022 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) | |
| 1023 if( isView || isVirtual ){ | |
| 1024 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); | |
| 1025 }else | |
| 1026 #endif | |
| 1027 { | |
| 1028 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); | |
| 1029 } | |
| 1030 sqlite3OpenMasterTable(pParse, iDb); | |
| 1031 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); | |
| 1032 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); | |
| 1033 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); | |
| 1034 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); | |
| 1035 sqlite3VdbeAddOp0(v, OP_Close); | |
| 1036 } | |
| 1037 | |
| 1038 /* Normal (non-error) return. */ | |
| 1039 return; | |
| 1040 | |
| 1041 /* If an error occurs, we jump here */ | |
| 1042 begin_table_error: | |
| 1043 sqlite3DbFree(db, zName); | |
| 1044 return; | |
| 1045 } | |
| 1046 | |
| 1047 /* Set properties of a table column based on the (magical) | |
| 1048 ** name of the column. | |
| 1049 */ | |
| 1050 #if SQLITE_ENABLE_HIDDEN_COLUMNS | |
| 1051 void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ | |
| 1052 if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ | |
| 1053 pCol->colFlags |= COLFLAG_HIDDEN; | |
| 1054 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ | |
| 1055 pTab->tabFlags |= TF_OOOHidden; | |
| 1056 } | |
| 1057 } | |
| 1058 #endif | |
| 1059 | |
| 1060 | |
| 1061 /* | |
| 1062 ** Add a new column to the table currently being constructed. | |
| 1063 ** | |
| 1064 ** The parser calls this routine once for each column declaration | |
| 1065 ** in a CREATE TABLE statement. sqlite3StartTable() gets called | |
| 1066 ** first to get things going. Then this routine is called for each | |
| 1067 ** column. | |
| 1068 */ | |
| 1069 void sqlite3AddColumn(Parse *pParse, Token *pName){ | |
| 1070 Table *p; | |
| 1071 int i; | |
| 1072 char *z; | |
| 1073 Column *pCol; | |
| 1074 sqlite3 *db = pParse->db; | |
| 1075 if( (p = pParse->pNewTable)==0 ) return; | |
| 1076 #if SQLITE_MAX_COLUMN | |
| 1077 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ | |
| 1078 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); | |
| 1079 return; | |
| 1080 } | |
| 1081 #endif | |
| 1082 z = sqlite3NameFromToken(db, pName); | |
| 1083 if( z==0 ) return; | |
| 1084 for(i=0; i<p->nCol; i++){ | |
| 1085 if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){ | |
| 1086 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); | |
| 1087 sqlite3DbFree(db, z); | |
| 1088 return; | |
| 1089 } | |
| 1090 } | |
| 1091 if( (p->nCol & 0x7)==0 ){ | |
| 1092 Column *aNew; | |
| 1093 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); | |
| 1094 if( aNew==0 ){ | |
| 1095 sqlite3DbFree(db, z); | |
| 1096 return; | |
| 1097 } | |
| 1098 p->aCol = aNew; | |
| 1099 } | |
| 1100 pCol = &p->aCol[p->nCol]; | |
| 1101 memset(pCol, 0, sizeof(p->aCol[0])); | |
| 1102 pCol->zName = z; | |
| 1103 sqlite3ColumnPropertiesFromName(p, pCol); | |
| 1104 | |
| 1105 /* If there is no type specified, columns have the default affinity | |
| 1106 ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will | |
| 1107 ** be called next to set pCol->affinity correctly. | |
| 1108 */ | |
| 1109 pCol->affinity = SQLITE_AFF_BLOB; | |
| 1110 pCol->szEst = 1; | |
| 1111 p->nCol++; | |
| 1112 } | |
| 1113 | |
| 1114 /* | |
| 1115 ** This routine is called by the parser while in the middle of | |
| 1116 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has | |
| 1117 ** been seen on a column. This routine sets the notNull flag on | |
| 1118 ** the column currently under construction. | |
| 1119 */ | |
| 1120 void sqlite3AddNotNull(Parse *pParse, int onError){ | |
| 1121 Table *p; | |
| 1122 p = pParse->pNewTable; | |
| 1123 if( p==0 || NEVER(p->nCol<1) ) return; | |
| 1124 p->aCol[p->nCol-1].notNull = (u8)onError; | |
| 1125 } | |
| 1126 | |
| 1127 /* | |
| 1128 ** Scan the column type name zType (length nType) and return the | |
| 1129 ** associated affinity type. | |
| 1130 ** | |
| 1131 ** This routine does a case-independent search of zType for the | |
| 1132 ** substrings in the following table. If one of the substrings is | |
| 1133 ** found, the corresponding affinity is returned. If zType contains | |
| 1134 ** more than one of the substrings, entries toward the top of | |
| 1135 ** the table take priority. For example, if zType is 'BLOBINT', | |
| 1136 ** SQLITE_AFF_INTEGER is returned. | |
| 1137 ** | |
| 1138 ** Substring | Affinity | |
| 1139 ** -------------------------------- | |
| 1140 ** 'INT' | SQLITE_AFF_INTEGER | |
| 1141 ** 'CHAR' | SQLITE_AFF_TEXT | |
| 1142 ** 'CLOB' | SQLITE_AFF_TEXT | |
| 1143 ** 'TEXT' | SQLITE_AFF_TEXT | |
| 1144 ** 'BLOB' | SQLITE_AFF_BLOB | |
| 1145 ** 'REAL' | SQLITE_AFF_REAL | |
| 1146 ** 'FLOA' | SQLITE_AFF_REAL | |
| 1147 ** 'DOUB' | SQLITE_AFF_REAL | |
| 1148 ** | |
| 1149 ** If none of the substrings in the above table are found, | |
| 1150 ** SQLITE_AFF_NUMERIC is returned. | |
| 1151 */ | |
| 1152 char sqlite3AffinityType(const char *zIn, u8 *pszEst){ | |
| 1153 u32 h = 0; | |
| 1154 char aff = SQLITE_AFF_NUMERIC; | |
| 1155 const char *zChar = 0; | |
| 1156 | |
| 1157 if( zIn==0 ) return aff; | |
| 1158 while( zIn[0] ){ | |
| 1159 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; | |
| 1160 zIn++; | |
| 1161 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ | |
| 1162 aff = SQLITE_AFF_TEXT; | |
| 1163 zChar = zIn; | |
| 1164 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ | |
| 1165 aff = SQLITE_AFF_TEXT; | |
| 1166 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ | |
| 1167 aff = SQLITE_AFF_TEXT; | |
| 1168 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ | |
| 1169 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ | |
| 1170 aff = SQLITE_AFF_BLOB; | |
| 1171 if( zIn[0]=='(' ) zChar = zIn; | |
| 1172 #ifndef SQLITE_OMIT_FLOATING_POINT | |
| 1173 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ | |
| 1174 && aff==SQLITE_AFF_NUMERIC ){ | |
| 1175 aff = SQLITE_AFF_REAL; | |
| 1176 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ | |
| 1177 && aff==SQLITE_AFF_NUMERIC ){ | |
| 1178 aff = SQLITE_AFF_REAL; | |
| 1179 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ | |
| 1180 && aff==SQLITE_AFF_NUMERIC ){ | |
| 1181 aff = SQLITE_AFF_REAL; | |
| 1182 #endif | |
| 1183 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ | |
| 1184 aff = SQLITE_AFF_INTEGER; | |
| 1185 break; | |
| 1186 } | |
| 1187 } | |
| 1188 | |
| 1189 /* If pszEst is not NULL, store an estimate of the field size. The | |
| 1190 ** estimate is scaled so that the size of an integer is 1. */ | |
| 1191 if( pszEst ){ | |
| 1192 *pszEst = 1; /* default size is approx 4 bytes */ | |
| 1193 if( aff<SQLITE_AFF_NUMERIC ){ | |
| 1194 if( zChar ){ | |
| 1195 while( zChar[0] ){ | |
| 1196 if( sqlite3Isdigit(zChar[0]) ){ | |
| 1197 int v = 0; | |
| 1198 sqlite3GetInt32(zChar, &v); | |
| 1199 v = v/4 + 1; | |
| 1200 if( v>255 ) v = 255; | |
| 1201 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ | |
| 1202 break; | |
| 1203 } | |
| 1204 zChar++; | |
| 1205 } | |
| 1206 }else{ | |
| 1207 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ | |
| 1208 } | |
| 1209 } | |
| 1210 } | |
| 1211 return aff; | |
| 1212 } | |
| 1213 | |
| 1214 /* | |
| 1215 ** This routine is called by the parser while in the middle of | |
| 1216 ** parsing a CREATE TABLE statement. The pFirst token is the first | |
| 1217 ** token in the sequence of tokens that describe the type of the | |
| 1218 ** column currently under construction. pLast is the last token | |
| 1219 ** in the sequence. Use this information to construct a string | |
| 1220 ** that contains the typename of the column and store that string | |
| 1221 ** in zType. | |
| 1222 */ | |
| 1223 void sqlite3AddColumnType(Parse *pParse, Token *pType){ | |
| 1224 Table *p; | |
| 1225 Column *pCol; | |
| 1226 | |
| 1227 p = pParse->pNewTable; | |
| 1228 if( p==0 || NEVER(p->nCol<1) ) return; | |
| 1229 pCol = &p->aCol[p->nCol-1]; | |
| 1230 assert( pCol->zType==0 || CORRUPT_DB ); | |
| 1231 sqlite3DbFree(pParse->db, pCol->zType); | |
| 1232 pCol->zType = sqlite3NameFromToken(pParse->db, pType); | |
| 1233 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst); | |
| 1234 } | |
| 1235 | |
| 1236 /* | |
| 1237 ** The expression is the default value for the most recently added column | |
| 1238 ** of the table currently under construction. | |
| 1239 ** | |
| 1240 ** Default value expressions must be constant. Raise an exception if this | |
| 1241 ** is not the case. | |
| 1242 ** | |
| 1243 ** This routine is called by the parser while in the middle of | |
| 1244 ** parsing a CREATE TABLE statement. | |
| 1245 */ | |
| 1246 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ | |
| 1247 Table *p; | |
| 1248 Column *pCol; | |
| 1249 sqlite3 *db = pParse->db; | |
| 1250 p = pParse->pNewTable; | |
| 1251 if( p!=0 ){ | |
| 1252 pCol = &(p->aCol[p->nCol-1]); | |
| 1253 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ | |
| 1254 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", | |
| 1255 pCol->zName); | |
| 1256 }else{ | |
| 1257 /* A copy of pExpr is used instead of the original, as pExpr contains | |
| 1258 ** tokens that point to volatile memory. The 'span' of the expression | |
| 1259 ** is required by pragma table_info. | |
| 1260 */ | |
| 1261 sqlite3ExprDelete(db, pCol->pDflt); | |
| 1262 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE); | |
| 1263 sqlite3DbFree(db, pCol->zDflt); | |
| 1264 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart, | |
| 1265 (int)(pSpan->zEnd - pSpan->zStart)); | |
| 1266 } | |
| 1267 } | |
| 1268 sqlite3ExprDelete(db, pSpan->pExpr); | |
| 1269 } | |
| 1270 | |
| 1271 /* | |
| 1272 ** Backwards Compatibility Hack: | |
| 1273 ** | |
| 1274 ** Historical versions of SQLite accepted strings as column names in | |
| 1275 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: | |
| 1276 ** | |
| 1277 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) | |
| 1278 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); | |
| 1279 ** | |
| 1280 ** This is goofy. But to preserve backwards compatibility we continue to | |
| 1281 ** accept it. This routine does the necessary conversion. It converts | |
| 1282 ** the expression given in its argument from a TK_STRING into a TK_ID | |
| 1283 ** if the expression is just a TK_STRING with an optional COLLATE clause. | |
| 1284 ** If the epxression is anything other than TK_STRING, the expression is | |
| 1285 ** unchanged. | |
| 1286 */ | |
| 1287 static void sqlite3StringToId(Expr *p){ | |
| 1288 if( p->op==TK_STRING ){ | |
| 1289 p->op = TK_ID; | |
| 1290 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ | |
| 1291 p->pLeft->op = TK_ID; | |
| 1292 } | |
| 1293 } | |
| 1294 | |
| 1295 /* | |
| 1296 ** Designate the PRIMARY KEY for the table. pList is a list of names | |
| 1297 ** of columns that form the primary key. If pList is NULL, then the | |
| 1298 ** most recently added column of the table is the primary key. | |
| 1299 ** | |
| 1300 ** A table can have at most one primary key. If the table already has | |
| 1301 ** a primary key (and this is the second primary key) then create an | |
| 1302 ** error. | |
| 1303 ** | |
| 1304 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, | |
| 1305 ** then we will try to use that column as the rowid. Set the Table.iPKey | |
| 1306 ** field of the table under construction to be the index of the | |
| 1307 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is | |
| 1308 ** no INTEGER PRIMARY KEY. | |
| 1309 ** | |
| 1310 ** If the key is not an INTEGER PRIMARY KEY, then create a unique | |
| 1311 ** index for the key. No index is created for INTEGER PRIMARY KEYs. | |
| 1312 */ | |
| 1313 void sqlite3AddPrimaryKey( | |
| 1314 Parse *pParse, /* Parsing context */ | |
| 1315 ExprList *pList, /* List of field names to be indexed */ | |
| 1316 int onError, /* What to do with a uniqueness conflict */ | |
| 1317 int autoInc, /* True if the AUTOINCREMENT keyword is present */ | |
| 1318 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ | |
| 1319 ){ | |
| 1320 Table *pTab = pParse->pNewTable; | |
| 1321 char *zType = 0; | |
| 1322 int iCol = -1, i; | |
| 1323 int nTerm; | |
| 1324 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; | |
| 1325 if( pTab->tabFlags & TF_HasPrimaryKey ){ | |
| 1326 sqlite3ErrorMsg(pParse, | |
| 1327 "table \"%s\" has more than one primary key", pTab->zName); | |
| 1328 goto primary_key_exit; | |
| 1329 } | |
| 1330 pTab->tabFlags |= TF_HasPrimaryKey; | |
| 1331 if( pList==0 ){ | |
| 1332 iCol = pTab->nCol - 1; | |
| 1333 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; | |
| 1334 zType = pTab->aCol[iCol].zType; | |
| 1335 nTerm = 1; | |
| 1336 }else{ | |
| 1337 nTerm = pList->nExpr; | |
| 1338 for(i=0; i<nTerm; i++){ | |
| 1339 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); | |
| 1340 assert( pCExpr!=0 ); | |
| 1341 sqlite3StringToId(pCExpr); | |
| 1342 if( pCExpr->op==TK_ID ){ | |
| 1343 const char *zCName = pCExpr->u.zToken; | |
| 1344 for(iCol=0; iCol<pTab->nCol; iCol++){ | |
| 1345 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ | |
| 1346 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; | |
| 1347 zType = pTab->aCol[iCol].zType; | |
| 1348 break; | |
| 1349 } | |
| 1350 } | |
| 1351 } | |
| 1352 } | |
| 1353 } | |
| 1354 if( nTerm==1 | |
| 1355 && zType && sqlite3StrICmp(zType, "INTEGER")==0 | |
| 1356 && sortOrder!=SQLITE_SO_DESC | |
| 1357 ){ | |
| 1358 pTab->iPKey = iCol; | |
| 1359 pTab->keyConf = (u8)onError; | |
| 1360 assert( autoInc==0 || autoInc==1 ); | |
| 1361 pTab->tabFlags |= autoInc*TF_Autoincrement; | |
| 1362 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; | |
| 1363 }else if( autoInc ){ | |
| 1364 #ifndef SQLITE_OMIT_AUTOINCREMENT | |
| 1365 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " | |
| 1366 "INTEGER PRIMARY KEY"); | |
| 1367 #endif | |
| 1368 }else{ | |
| 1369 Index *p; | |
| 1370 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, | |
| 1371 0, sortOrder, 0); | |
| 1372 if( p ){ | |
| 1373 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY; | |
| 1374 } | |
| 1375 pList = 0; | |
| 1376 } | |
| 1377 | |
| 1378 primary_key_exit: | |
| 1379 sqlite3ExprListDelete(pParse->db, pList); | |
| 1380 return; | |
| 1381 } | |
| 1382 | |
| 1383 /* | |
| 1384 ** Add a new CHECK constraint to the table currently under construction. | |
| 1385 */ | |
| 1386 void sqlite3AddCheckConstraint( | |
| 1387 Parse *pParse, /* Parsing context */ | |
| 1388 Expr *pCheckExpr /* The check expression */ | |
| 1389 ){ | |
| 1390 #ifndef SQLITE_OMIT_CHECK | |
| 1391 Table *pTab = pParse->pNewTable; | |
| 1392 sqlite3 *db = pParse->db; | |
| 1393 if( pTab && !IN_DECLARE_VTAB | |
| 1394 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) | |
| 1395 ){ | |
| 1396 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); | |
| 1397 if( pParse->constraintName.n ){ | |
| 1398 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); | |
| 1399 } | |
| 1400 }else | |
| 1401 #endif | |
| 1402 { | |
| 1403 sqlite3ExprDelete(pParse->db, pCheckExpr); | |
| 1404 } | |
| 1405 } | |
| 1406 | |
| 1407 /* | |
| 1408 ** Set the collation function of the most recently parsed table column | |
| 1409 ** to the CollSeq given. | |
| 1410 */ | |
| 1411 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ | |
| 1412 Table *p; | |
| 1413 int i; | |
| 1414 char *zColl; /* Dequoted name of collation sequence */ | |
| 1415 sqlite3 *db; | |
| 1416 | |
| 1417 if( (p = pParse->pNewTable)==0 ) return; | |
| 1418 i = p->nCol-1; | |
| 1419 db = pParse->db; | |
| 1420 zColl = sqlite3NameFromToken(db, pToken); | |
| 1421 if( !zColl ) return; | |
| 1422 | |
| 1423 if( sqlite3LocateCollSeq(pParse, zColl) ){ | |
| 1424 Index *pIdx; | |
| 1425 sqlite3DbFree(db, p->aCol[i].zColl); | |
| 1426 p->aCol[i].zColl = zColl; | |
| 1427 | |
| 1428 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", | |
| 1429 ** then an index may have been created on this column before the | |
| 1430 ** collation type was added. Correct this if it is the case. | |
| 1431 */ | |
| 1432 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ | |
| 1433 assert( pIdx->nKeyCol==1 ); | |
| 1434 if( pIdx->aiColumn[0]==i ){ | |
| 1435 pIdx->azColl[0] = p->aCol[i].zColl; | |
| 1436 } | |
| 1437 } | |
| 1438 }else{ | |
| 1439 sqlite3DbFree(db, zColl); | |
| 1440 } | |
| 1441 } | |
| 1442 | |
| 1443 /* | |
| 1444 ** This function returns the collation sequence for database native text | |
| 1445 ** encoding identified by the string zName, length nName. | |
| 1446 ** | |
| 1447 ** If the requested collation sequence is not available, or not available | |
| 1448 ** in the database native encoding, the collation factory is invoked to | |
| 1449 ** request it. If the collation factory does not supply such a sequence, | |
| 1450 ** and the sequence is available in another text encoding, then that is | |
| 1451 ** returned instead. | |
| 1452 ** | |
| 1453 ** If no versions of the requested collations sequence are available, or | |
| 1454 ** another error occurs, NULL is returned and an error message written into | |
| 1455 ** pParse. | |
| 1456 ** | |
| 1457 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine | |
| 1458 ** invokes the collation factory if the named collation cannot be found | |
| 1459 ** and generates an error message. | |
| 1460 ** | |
| 1461 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() | |
| 1462 */ | |
| 1463 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ | |
| 1464 sqlite3 *db = pParse->db; | |
| 1465 u8 enc = ENC(db); | |
| 1466 u8 initbusy = db->init.busy; | |
| 1467 CollSeq *pColl; | |
| 1468 | |
| 1469 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); | |
| 1470 if( !initbusy && (!pColl || !pColl->xCmp) ){ | |
| 1471 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); | |
| 1472 } | |
| 1473 | |
| 1474 return pColl; | |
| 1475 } | |
| 1476 | |
| 1477 | |
| 1478 /* | |
| 1479 ** Generate code that will increment the schema cookie. | |
| 1480 ** | |
| 1481 ** The schema cookie is used to determine when the schema for the | |
| 1482 ** database changes. After each schema change, the cookie value | |
| 1483 ** changes. When a process first reads the schema it records the | |
| 1484 ** cookie. Thereafter, whenever it goes to access the database, | |
| 1485 ** it checks the cookie to make sure the schema has not changed | |
| 1486 ** since it was last read. | |
| 1487 ** | |
| 1488 ** This plan is not completely bullet-proof. It is possible for | |
| 1489 ** the schema to change multiple times and for the cookie to be | |
| 1490 ** set back to prior value. But schema changes are infrequent | |
| 1491 ** and the probability of hitting the same cookie value is only | |
| 1492 ** 1 chance in 2^32. So we're safe enough. | |
| 1493 */ | |
| 1494 void sqlite3ChangeCookie(Parse *pParse, int iDb){ | |
| 1495 int r1 = sqlite3GetTempReg(pParse); | |
| 1496 sqlite3 *db = pParse->db; | |
| 1497 Vdbe *v = pParse->pVdbe; | |
| 1498 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 1499 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); | |
| 1500 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1); | |
| 1501 sqlite3ReleaseTempReg(pParse, r1); | |
| 1502 } | |
| 1503 | |
| 1504 /* | |
| 1505 ** Measure the number of characters needed to output the given | |
| 1506 ** identifier. The number returned includes any quotes used | |
| 1507 ** but does not include the null terminator. | |
| 1508 ** | |
| 1509 ** The estimate is conservative. It might be larger that what is | |
| 1510 ** really needed. | |
| 1511 */ | |
| 1512 static int identLength(const char *z){ | |
| 1513 int n; | |
| 1514 for(n=0; *z; n++, z++){ | |
| 1515 if( *z=='"' ){ n++; } | |
| 1516 } | |
| 1517 return n + 2; | |
| 1518 } | |
| 1519 | |
| 1520 /* | |
| 1521 ** The first parameter is a pointer to an output buffer. The second | |
| 1522 ** parameter is a pointer to an integer that contains the offset at | |
| 1523 ** which to write into the output buffer. This function copies the | |
| 1524 ** nul-terminated string pointed to by the third parameter, zSignedIdent, | |
| 1525 ** to the specified offset in the buffer and updates *pIdx to refer | |
| 1526 ** to the first byte after the last byte written before returning. | |
| 1527 ** | |
| 1528 ** If the string zSignedIdent consists entirely of alpha-numeric | |
| 1529 ** characters, does not begin with a digit and is not an SQL keyword, | |
| 1530 ** then it is copied to the output buffer exactly as it is. Otherwise, | |
| 1531 ** it is quoted using double-quotes. | |
| 1532 */ | |
| 1533 static void identPut(char *z, int *pIdx, char *zSignedIdent){ | |
| 1534 unsigned char *zIdent = (unsigned char*)zSignedIdent; | |
| 1535 int i, j, needQuote; | |
| 1536 i = *pIdx; | |
| 1537 | |
| 1538 for(j=0; zIdent[j]; j++){ | |
| 1539 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; | |
| 1540 } | |
| 1541 needQuote = sqlite3Isdigit(zIdent[0]) | |
| 1542 || sqlite3KeywordCode(zIdent, j)!=TK_ID | |
| 1543 || zIdent[j]!=0 | |
| 1544 || j==0; | |
| 1545 | |
| 1546 if( needQuote ) z[i++] = '"'; | |
| 1547 for(j=0; zIdent[j]; j++){ | |
| 1548 z[i++] = zIdent[j]; | |
| 1549 if( zIdent[j]=='"' ) z[i++] = '"'; | |
| 1550 } | |
| 1551 if( needQuote ) z[i++] = '"'; | |
| 1552 z[i] = 0; | |
| 1553 *pIdx = i; | |
| 1554 } | |
| 1555 | |
| 1556 /* | |
| 1557 ** Generate a CREATE TABLE statement appropriate for the given | |
| 1558 ** table. Memory to hold the text of the statement is obtained | |
| 1559 ** from sqliteMalloc() and must be freed by the calling function. | |
| 1560 */ | |
| 1561 static char *createTableStmt(sqlite3 *db, Table *p){ | |
| 1562 int i, k, n; | |
| 1563 char *zStmt; | |
| 1564 char *zSep, *zSep2, *zEnd; | |
| 1565 Column *pCol; | |
| 1566 n = 0; | |
| 1567 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ | |
| 1568 n += identLength(pCol->zName) + 5; | |
| 1569 } | |
| 1570 n += identLength(p->zName); | |
| 1571 if( n<50 ){ | |
| 1572 zSep = ""; | |
| 1573 zSep2 = ","; | |
| 1574 zEnd = ")"; | |
| 1575 }else{ | |
| 1576 zSep = "\n "; | |
| 1577 zSep2 = ",\n "; | |
| 1578 zEnd = "\n)"; | |
| 1579 } | |
| 1580 n += 35 + 6*p->nCol; | |
| 1581 zStmt = sqlite3DbMallocRaw(0, n); | |
| 1582 if( zStmt==0 ){ | |
| 1583 db->mallocFailed = 1; | |
| 1584 return 0; | |
| 1585 } | |
| 1586 sqlite3_snprintf(n, zStmt, "CREATE TABLE "); | |
| 1587 k = sqlite3Strlen30(zStmt); | |
| 1588 identPut(zStmt, &k, p->zName); | |
| 1589 zStmt[k++] = '('; | |
| 1590 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ | |
| 1591 static const char * const azType[] = { | |
| 1592 /* SQLITE_AFF_BLOB */ "", | |
| 1593 /* SQLITE_AFF_TEXT */ " TEXT", | |
| 1594 /* SQLITE_AFF_NUMERIC */ " NUM", | |
| 1595 /* SQLITE_AFF_INTEGER */ " INT", | |
| 1596 /* SQLITE_AFF_REAL */ " REAL" | |
| 1597 }; | |
| 1598 int len; | |
| 1599 const char *zType; | |
| 1600 | |
| 1601 sqlite3_snprintf(n-k, &zStmt[k], zSep); | |
| 1602 k += sqlite3Strlen30(&zStmt[k]); | |
| 1603 zSep = zSep2; | |
| 1604 identPut(zStmt, &k, pCol->zName); | |
| 1605 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); | |
| 1606 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); | |
| 1607 testcase( pCol->affinity==SQLITE_AFF_BLOB ); | |
| 1608 testcase( pCol->affinity==SQLITE_AFF_TEXT ); | |
| 1609 testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); | |
| 1610 testcase( pCol->affinity==SQLITE_AFF_INTEGER ); | |
| 1611 testcase( pCol->affinity==SQLITE_AFF_REAL ); | |
| 1612 | |
| 1613 zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; | |
| 1614 len = sqlite3Strlen30(zType); | |
| 1615 assert( pCol->affinity==SQLITE_AFF_BLOB | |
| 1616 || pCol->affinity==sqlite3AffinityType(zType, 0) ); | |
| 1617 memcpy(&zStmt[k], zType, len); | |
| 1618 k += len; | |
| 1619 assert( k<=n ); | |
| 1620 } | |
| 1621 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); | |
| 1622 return zStmt; | |
| 1623 } | |
| 1624 | |
| 1625 /* | |
| 1626 ** Resize an Index object to hold N columns total. Return SQLITE_OK | |
| 1627 ** on success and SQLITE_NOMEM on an OOM error. | |
| 1628 */ | |
| 1629 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ | |
| 1630 char *zExtra; | |
| 1631 int nByte; | |
| 1632 if( pIdx->nColumn>=N ) return SQLITE_OK; | |
| 1633 assert( pIdx->isResized==0 ); | |
| 1634 nByte = (sizeof(char*) + sizeof(i16) + 1)*N; | |
| 1635 zExtra = sqlite3DbMallocZero(db, nByte); | |
| 1636 if( zExtra==0 ) return SQLITE_NOMEM; | |
| 1637 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); | |
| 1638 pIdx->azColl = (const char**)zExtra; | |
| 1639 zExtra += sizeof(char*)*N; | |
| 1640 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); | |
| 1641 pIdx->aiColumn = (i16*)zExtra; | |
| 1642 zExtra += sizeof(i16)*N; | |
| 1643 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); | |
| 1644 pIdx->aSortOrder = (u8*)zExtra; | |
| 1645 pIdx->nColumn = N; | |
| 1646 pIdx->isResized = 1; | |
| 1647 return SQLITE_OK; | |
| 1648 } | |
| 1649 | |
| 1650 /* | |
| 1651 ** Estimate the total row width for a table. | |
| 1652 */ | |
| 1653 static void estimateTableWidth(Table *pTab){ | |
| 1654 unsigned wTable = 0; | |
| 1655 const Column *pTabCol; | |
| 1656 int i; | |
| 1657 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ | |
| 1658 wTable += pTabCol->szEst; | |
| 1659 } | |
| 1660 if( pTab->iPKey<0 ) wTable++; | |
| 1661 pTab->szTabRow = sqlite3LogEst(wTable*4); | |
| 1662 } | |
| 1663 | |
| 1664 /* | |
| 1665 ** Estimate the average size of a row for an index. | |
| 1666 */ | |
| 1667 static void estimateIndexWidth(Index *pIdx){ | |
| 1668 unsigned wIndex = 0; | |
| 1669 int i; | |
| 1670 const Column *aCol = pIdx->pTable->aCol; | |
| 1671 for(i=0; i<pIdx->nColumn; i++){ | |
| 1672 i16 x = pIdx->aiColumn[i]; | |
| 1673 assert( x<pIdx->pTable->nCol ); | |
| 1674 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; | |
| 1675 } | |
| 1676 pIdx->szIdxRow = sqlite3LogEst(wIndex*4); | |
| 1677 } | |
| 1678 | |
| 1679 /* Return true if value x is found any of the first nCol entries of aiCol[] | |
| 1680 */ | |
| 1681 static int hasColumn(const i16 *aiCol, int nCol, int x){ | |
| 1682 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; | |
| 1683 return 0; | |
| 1684 } | |
| 1685 | |
| 1686 /* | |
| 1687 ** This routine runs at the end of parsing a CREATE TABLE statement that | |
| 1688 ** has a WITHOUT ROWID clause. The job of this routine is to convert both | |
| 1689 ** internal schema data structures and the generated VDBE code so that they | |
| 1690 ** are appropriate for a WITHOUT ROWID table instead of a rowid table. | |
| 1691 ** Changes include: | |
| 1692 ** | |
| 1693 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is | |
| 1694 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical | |
| 1695 ** data storage is a covering index btree. | |
| 1696 ** (2) Bypass the creation of the sqlite_master table entry | |
| 1697 ** for the PRIMARY KEY as the primary key index is now | |
| 1698 ** identified by the sqlite_master table entry of the table itself. | |
| 1699 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the | |
| 1700 ** schema to the rootpage from the main table. | |
| 1701 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL. | |
| 1702 ** (5) Add all table columns to the PRIMARY KEY Index object | |
| 1703 ** so that the PRIMARY KEY is a covering index. The surplus | |
| 1704 ** columns are part of KeyInfo.nXField and are not used for | |
| 1705 ** sorting or lookup or uniqueness checks. | |
| 1706 ** (6) Replace the rowid tail on all automatically generated UNIQUE | |
| 1707 ** indices with the PRIMARY KEY columns. | |
| 1708 */ | |
| 1709 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ | |
| 1710 Index *pIdx; | |
| 1711 Index *pPk; | |
| 1712 int nPk; | |
| 1713 int i, j; | |
| 1714 sqlite3 *db = pParse->db; | |
| 1715 Vdbe *v = pParse->pVdbe; | |
| 1716 | |
| 1717 /* Convert the OP_CreateTable opcode that would normally create the | |
| 1718 ** root-page for the table into an OP_CreateIndex opcode. The index | |
| 1719 ** created will become the PRIMARY KEY index. | |
| 1720 */ | |
| 1721 if( pParse->addrCrTab ){ | |
| 1722 assert( v ); | |
| 1723 sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex); | |
| 1724 } | |
| 1725 | |
| 1726 /* Locate the PRIMARY KEY index. Or, if this table was originally | |
| 1727 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. | |
| 1728 */ | |
| 1729 if( pTab->iPKey>=0 ){ | |
| 1730 ExprList *pList; | |
| 1731 Token ipkToken; | |
| 1732 ipkToken.z = pTab->aCol[pTab->iPKey].zName; | |
| 1733 ipkToken.n = sqlite3Strlen30(ipkToken.z); | |
| 1734 pList = sqlite3ExprListAppend(pParse, 0, | |
| 1735 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); | |
| 1736 if( pList==0 ) return; | |
| 1737 pList->a[0].sortOrder = pParse->iPkSortOrder; | |
| 1738 assert( pParse->pNewTable==pTab ); | |
| 1739 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0); | |
| 1740 if( pPk==0 ) return; | |
| 1741 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY; | |
| 1742 pTab->iPKey = -1; | |
| 1743 }else{ | |
| 1744 pPk = sqlite3PrimaryKeyIndex(pTab); | |
| 1745 | |
| 1746 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master | |
| 1747 ** table entry. This is only required if currently generating VDBE | |
| 1748 ** code for a CREATE TABLE (not when parsing one as part of reading | |
| 1749 ** a database schema). */ | |
| 1750 if( v ){ | |
| 1751 assert( db->init.busy==0 ); | |
| 1752 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); | |
| 1753 } | |
| 1754 | |
| 1755 /* | |
| 1756 ** Remove all redundant columns from the PRIMARY KEY. For example, change | |
| 1757 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later | |
| 1758 ** code assumes the PRIMARY KEY contains no repeated columns. | |
| 1759 */ | |
| 1760 for(i=j=1; i<pPk->nKeyCol; i++){ | |
| 1761 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ | |
| 1762 pPk->nColumn--; | |
| 1763 }else{ | |
| 1764 pPk->aiColumn[j++] = pPk->aiColumn[i]; | |
| 1765 } | |
| 1766 } | |
| 1767 pPk->nKeyCol = j; | |
| 1768 } | |
| 1769 pPk->isCovering = 1; | |
| 1770 assert( pPk!=0 ); | |
| 1771 nPk = pPk->nKeyCol; | |
| 1772 | |
| 1773 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except, | |
| 1774 ** do not enforce this for imposter tables.) */ | |
| 1775 if( !db->init.imposterTable ){ | |
| 1776 for(i=0; i<nPk; i++){ | |
| 1777 pTab->aCol[pPk->aiColumn[i]].notNull = OE_Abort; | |
| 1778 } | |
| 1779 pPk->uniqNotNull = 1; | |
| 1780 } | |
| 1781 | |
| 1782 /* The root page of the PRIMARY KEY is the table root page */ | |
| 1783 pPk->tnum = pTab->tnum; | |
| 1784 | |
| 1785 /* Update the in-memory representation of all UNIQUE indices by converting | |
| 1786 ** the final rowid column into one or more columns of the PRIMARY KEY. | |
| 1787 */ | |
| 1788 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | |
| 1789 int n; | |
| 1790 if( IsPrimaryKeyIndex(pIdx) ) continue; | |
| 1791 for(i=n=0; i<nPk; i++){ | |
| 1792 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; | |
| 1793 } | |
| 1794 if( n==0 ){ | |
| 1795 /* This index is a superset of the primary key */ | |
| 1796 pIdx->nColumn = pIdx->nKeyCol; | |
| 1797 continue; | |
| 1798 } | |
| 1799 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; | |
| 1800 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ | |
| 1801 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ | |
| 1802 pIdx->aiColumn[j] = pPk->aiColumn[i]; | |
| 1803 pIdx->azColl[j] = pPk->azColl[i]; | |
| 1804 j++; | |
| 1805 } | |
| 1806 } | |
| 1807 assert( pIdx->nColumn>=pIdx->nKeyCol+n ); | |
| 1808 assert( pIdx->nColumn>=j ); | |
| 1809 } | |
| 1810 | |
| 1811 /* Add all table columns to the PRIMARY KEY index | |
| 1812 */ | |
| 1813 if( nPk<pTab->nCol ){ | |
| 1814 if( resizeIndexObject(db, pPk, pTab->nCol) ) return; | |
| 1815 for(i=0, j=nPk; i<pTab->nCol; i++){ | |
| 1816 if( !hasColumn(pPk->aiColumn, j, i) ){ | |
| 1817 assert( j<pPk->nColumn ); | |
| 1818 pPk->aiColumn[j] = i; | |
| 1819 pPk->azColl[j] = sqlite3StrBINARY; | |
| 1820 j++; | |
| 1821 } | |
| 1822 } | |
| 1823 assert( pPk->nColumn==j ); | |
| 1824 assert( pTab->nCol==j ); | |
| 1825 }else{ | |
| 1826 pPk->nColumn = pTab->nCol; | |
| 1827 } | |
| 1828 } | |
| 1829 | |
| 1830 /* | |
| 1831 ** This routine is called to report the final ")" that terminates | |
| 1832 ** a CREATE TABLE statement. | |
| 1833 ** | |
| 1834 ** The table structure that other action routines have been building | |
| 1835 ** is added to the internal hash tables, assuming no errors have | |
| 1836 ** occurred. | |
| 1837 ** | |
| 1838 ** An entry for the table is made in the master table on disk, unless | |
| 1839 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 | |
| 1840 ** it means we are reading the sqlite_master table because we just | |
| 1841 ** connected to the database or because the sqlite_master table has | |
| 1842 ** recently changed, so the entry for this table already exists in | |
| 1843 ** the sqlite_master table. We do not want to create it again. | |
| 1844 ** | |
| 1845 ** If the pSelect argument is not NULL, it means that this routine | |
| 1846 ** was called to create a table generated from a | |
| 1847 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of | |
| 1848 ** the new table will match the result set of the SELECT. | |
| 1849 */ | |
| 1850 void sqlite3EndTable( | |
| 1851 Parse *pParse, /* Parse context */ | |
| 1852 Token *pCons, /* The ',' token after the last column defn. */ | |
| 1853 Token *pEnd, /* The ')' before options in the CREATE TABLE */ | |
| 1854 u8 tabOpts, /* Extra table options. Usually 0. */ | |
| 1855 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ | |
| 1856 ){ | |
| 1857 Table *p; /* The new table */ | |
| 1858 sqlite3 *db = pParse->db; /* The database connection */ | |
| 1859 int iDb; /* Database in which the table lives */ | |
| 1860 Index *pIdx; /* An implied index of the table */ | |
| 1861 | |
| 1862 if( pEnd==0 && pSelect==0 ){ | |
| 1863 return; | |
| 1864 } | |
| 1865 assert( !db->mallocFailed ); | |
| 1866 p = pParse->pNewTable; | |
| 1867 if( p==0 ) return; | |
| 1868 | |
| 1869 assert( !db->init.busy || !pSelect ); | |
| 1870 | |
| 1871 /* If the db->init.busy is 1 it means we are reading the SQL off the | |
| 1872 ** "sqlite_master" or "sqlite_temp_master" table on the disk. | |
| 1873 ** So do not write to the disk again. Extract the root page number | |
| 1874 ** for the table from the db->init.newTnum field. (The page number | |
| 1875 ** should have been put there by the sqliteOpenCb routine.) | |
| 1876 */ | |
| 1877 if( db->init.busy ){ | |
| 1878 p->tnum = db->init.newTnum; | |
| 1879 } | |
| 1880 | |
| 1881 /* Special processing for WITHOUT ROWID Tables */ | |
| 1882 if( tabOpts & TF_WithoutRowid ){ | |
| 1883 if( (p->tabFlags & TF_Autoincrement) ){ | |
| 1884 sqlite3ErrorMsg(pParse, | |
| 1885 "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); | |
| 1886 return; | |
| 1887 } | |
| 1888 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ | |
| 1889 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); | |
| 1890 }else{ | |
| 1891 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; | |
| 1892 convertToWithoutRowidTable(pParse, p); | |
| 1893 } | |
| 1894 } | |
| 1895 | |
| 1896 iDb = sqlite3SchemaToIndex(db, p->pSchema); | |
| 1897 | |
| 1898 #ifndef SQLITE_OMIT_CHECK | |
| 1899 /* Resolve names in all CHECK constraint expressions. | |
| 1900 */ | |
| 1901 if( p->pCheck ){ | |
| 1902 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); | |
| 1903 } | |
| 1904 #endif /* !defined(SQLITE_OMIT_CHECK) */ | |
| 1905 | |
| 1906 /* Estimate the average row size for the table and for all implied indices */ | |
| 1907 estimateTableWidth(p); | |
| 1908 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ | |
| 1909 estimateIndexWidth(pIdx); | |
| 1910 } | |
| 1911 | |
| 1912 /* If not initializing, then create a record for the new table | |
| 1913 ** in the SQLITE_MASTER table of the database. | |
| 1914 ** | |
| 1915 ** If this is a TEMPORARY table, write the entry into the auxiliary | |
| 1916 ** file instead of into the main database file. | |
| 1917 */ | |
| 1918 if( !db->init.busy ){ | |
| 1919 int n; | |
| 1920 Vdbe *v; | |
| 1921 char *zType; /* "view" or "table" */ | |
| 1922 char *zType2; /* "VIEW" or "TABLE" */ | |
| 1923 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ | |
| 1924 | |
| 1925 v = sqlite3GetVdbe(pParse); | |
| 1926 if( NEVER(v==0) ) return; | |
| 1927 | |
| 1928 sqlite3VdbeAddOp1(v, OP_Close, 0); | |
| 1929 | |
| 1930 /* | |
| 1931 ** Initialize zType for the new view or table. | |
| 1932 */ | |
| 1933 if( p->pSelect==0 ){ | |
| 1934 /* A regular table */ | |
| 1935 zType = "table"; | |
| 1936 zType2 = "TABLE"; | |
| 1937 #ifndef SQLITE_OMIT_VIEW | |
| 1938 }else{ | |
| 1939 /* A view */ | |
| 1940 zType = "view"; | |
| 1941 zType2 = "VIEW"; | |
| 1942 #endif | |
| 1943 } | |
| 1944 | |
| 1945 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT | |
| 1946 ** statement to populate the new table. The root-page number for the | |
| 1947 ** new table is in register pParse->regRoot. | |
| 1948 ** | |
| 1949 ** Once the SELECT has been coded by sqlite3Select(), it is in a | |
| 1950 ** suitable state to query for the column names and types to be used | |
| 1951 ** by the new table. | |
| 1952 ** | |
| 1953 ** A shared-cache write-lock is not required to write to the new table, | |
| 1954 ** as a schema-lock must have already been obtained to create it. Since | |
| 1955 ** a schema-lock excludes all other database users, the write-lock would | |
| 1956 ** be redundant. | |
| 1957 */ | |
| 1958 if( pSelect ){ | |
| 1959 SelectDest dest; /* Where the SELECT should store results */ | |
| 1960 int regYield; /* Register holding co-routine entry-point */ | |
| 1961 int addrTop; /* Top of the co-routine */ | |
| 1962 int regRec; /* A record to be insert into the new table */ | |
| 1963 int regRowid; /* Rowid of the next row to insert */ | |
| 1964 int addrInsLoop; /* Top of the loop for inserting rows */ | |
| 1965 Table *pSelTab; /* A table that describes the SELECT results */ | |
| 1966 | |
| 1967 regYield = ++pParse->nMem; | |
| 1968 regRec = ++pParse->nMem; | |
| 1969 regRowid = ++pParse->nMem; | |
| 1970 assert(pParse->nTab==1); | |
| 1971 sqlite3MayAbort(pParse); | |
| 1972 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); | |
| 1973 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); | |
| 1974 pParse->nTab = 2; | |
| 1975 addrTop = sqlite3VdbeCurrentAddr(v) + 1; | |
| 1976 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); | |
| 1977 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); | |
| 1978 sqlite3Select(pParse, pSelect, &dest); | |
| 1979 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); | |
| 1980 sqlite3VdbeJumpHere(v, addrTop - 1); | |
| 1981 if( pParse->nErr ) return; | |
| 1982 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); | |
| 1983 if( pSelTab==0 ) return; | |
| 1984 assert( p->aCol==0 ); | |
| 1985 p->nCol = pSelTab->nCol; | |
| 1986 p->aCol = pSelTab->aCol; | |
| 1987 pSelTab->nCol = 0; | |
| 1988 pSelTab->aCol = 0; | |
| 1989 sqlite3DeleteTable(db, pSelTab); | |
| 1990 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); | |
| 1991 VdbeCoverage(v); | |
| 1992 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); | |
| 1993 sqlite3TableAffinity(v, p, 0); | |
| 1994 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); | |
| 1995 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); | |
| 1996 sqlite3VdbeGoto(v, addrInsLoop); | |
| 1997 sqlite3VdbeJumpHere(v, addrInsLoop); | |
| 1998 sqlite3VdbeAddOp1(v, OP_Close, 1); | |
| 1999 } | |
| 2000 | |
| 2001 /* Compute the complete text of the CREATE statement */ | |
| 2002 if( pSelect ){ | |
| 2003 zStmt = createTableStmt(db, p); | |
| 2004 }else{ | |
| 2005 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; | |
| 2006 n = (int)(pEnd2->z - pParse->sNameToken.z); | |
| 2007 if( pEnd2->z[0]!=';' ) n += pEnd2->n; | |
| 2008 zStmt = sqlite3MPrintf(db, | |
| 2009 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z | |
| 2010 ); | |
| 2011 } | |
| 2012 | |
| 2013 /* A slot for the record has already been allocated in the | |
| 2014 ** SQLITE_MASTER table. We just need to update that slot with all | |
| 2015 ** the information we've collected. | |
| 2016 */ | |
| 2017 sqlite3NestedParse(pParse, | |
| 2018 "UPDATE %Q.%s " | |
| 2019 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " | |
| 2020 "WHERE rowid=#%d", | |
| 2021 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), | |
| 2022 zType, | |
| 2023 p->zName, | |
| 2024 p->zName, | |
| 2025 pParse->regRoot, | |
| 2026 zStmt, | |
| 2027 pParse->regRowid | |
| 2028 ); | |
| 2029 sqlite3DbFree(db, zStmt); | |
| 2030 sqlite3ChangeCookie(pParse, iDb); | |
| 2031 | |
| 2032 #ifndef SQLITE_OMIT_AUTOINCREMENT | |
| 2033 /* Check to see if we need to create an sqlite_sequence table for | |
| 2034 ** keeping track of autoincrement keys. | |
| 2035 */ | |
| 2036 if( p->tabFlags & TF_Autoincrement ){ | |
| 2037 Db *pDb = &db->aDb[iDb]; | |
| 2038 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 2039 if( pDb->pSchema->pSeqTab==0 ){ | |
| 2040 sqlite3NestedParse(pParse, | |
| 2041 "CREATE TABLE %Q.sqlite_sequence(name,seq)", | |
| 2042 pDb->zName | |
| 2043 ); | |
| 2044 } | |
| 2045 } | |
| 2046 #endif | |
| 2047 | |
| 2048 /* Reparse everything to update our internal data structures */ | |
| 2049 sqlite3VdbeAddParseSchemaOp(v, iDb, | |
| 2050 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); | |
| 2051 } | |
| 2052 | |
| 2053 | |
| 2054 /* Add the table to the in-memory representation of the database. | |
| 2055 */ | |
| 2056 if( db->init.busy ){ | |
| 2057 Table *pOld; | |
| 2058 Schema *pSchema = p->pSchema; | |
| 2059 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 2060 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); | |
| 2061 if( pOld ){ | |
| 2062 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ | |
| 2063 db->mallocFailed = 1; | |
| 2064 return; | |
| 2065 } | |
| 2066 pParse->pNewTable = 0; | |
| 2067 db->flags |= SQLITE_InternChanges; | |
| 2068 | |
| 2069 #ifndef SQLITE_OMIT_ALTERTABLE | |
| 2070 if( !p->pSelect ){ | |
| 2071 const char *zName = (const char *)pParse->sNameToken.z; | |
| 2072 int nName; | |
| 2073 assert( !pSelect && pCons && pEnd ); | |
| 2074 if( pCons->z==0 ){ | |
| 2075 pCons = pEnd; | |
| 2076 } | |
| 2077 nName = (int)((const char *)pCons->z - zName); | |
| 2078 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); | |
| 2079 } | |
| 2080 #endif | |
| 2081 } | |
| 2082 } | |
| 2083 | |
| 2084 #ifndef SQLITE_OMIT_VIEW | |
| 2085 /* | |
| 2086 ** The parser calls this routine in order to create a new VIEW | |
| 2087 */ | |
| 2088 void sqlite3CreateView( | |
| 2089 Parse *pParse, /* The parsing context */ | |
| 2090 Token *pBegin, /* The CREATE token that begins the statement */ | |
| 2091 Token *pName1, /* The token that holds the name of the view */ | |
| 2092 Token *pName2, /* The token that holds the name of the view */ | |
| 2093 ExprList *pCNames, /* Optional list of view column names */ | |
| 2094 Select *pSelect, /* A SELECT statement that will become the new view */ | |
| 2095 int isTemp, /* TRUE for a TEMPORARY view */ | |
| 2096 int noErr /* Suppress error messages if VIEW already exists */ | |
| 2097 ){ | |
| 2098 Table *p; | |
| 2099 int n; | |
| 2100 const char *z; | |
| 2101 Token sEnd; | |
| 2102 DbFixer sFix; | |
| 2103 Token *pName = 0; | |
| 2104 int iDb; | |
| 2105 sqlite3 *db = pParse->db; | |
| 2106 | |
| 2107 if( pParse->nVar>0 ){ | |
| 2108 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); | |
| 2109 goto create_view_fail; | |
| 2110 } | |
| 2111 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); | |
| 2112 p = pParse->pNewTable; | |
| 2113 if( p==0 || pParse->nErr ) goto create_view_fail; | |
| 2114 sqlite3TwoPartName(pParse, pName1, pName2, &pName); | |
| 2115 iDb = sqlite3SchemaToIndex(db, p->pSchema); | |
| 2116 sqlite3FixInit(&sFix, pParse, iDb, "view", pName); | |
| 2117 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; | |
| 2118 | |
| 2119 /* Make a copy of the entire SELECT statement that defines the view. | |
| 2120 ** This will force all the Expr.token.z values to be dynamically | |
| 2121 ** allocated rather than point to the input string - which means that | |
| 2122 ** they will persist after the current sqlite3_exec() call returns. | |
| 2123 */ | |
| 2124 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); | |
| 2125 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); | |
| 2126 if( db->mallocFailed ) goto create_view_fail; | |
| 2127 | |
| 2128 /* Locate the end of the CREATE VIEW statement. Make sEnd point to | |
| 2129 ** the end. | |
| 2130 */ | |
| 2131 sEnd = pParse->sLastToken; | |
| 2132 assert( sEnd.z[0]!=0 ); | |
| 2133 if( sEnd.z[0]!=';' ){ | |
| 2134 sEnd.z += sEnd.n; | |
| 2135 } | |
| 2136 sEnd.n = 0; | |
| 2137 n = (int)(sEnd.z - pBegin->z); | |
| 2138 assert( n>0 ); | |
| 2139 z = pBegin->z; | |
| 2140 while( sqlite3Isspace(z[n-1]) ){ n--; } | |
| 2141 sEnd.z = &z[n-1]; | |
| 2142 sEnd.n = 1; | |
| 2143 | |
| 2144 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ | |
| 2145 sqlite3EndTable(pParse, 0, &sEnd, 0, 0); | |
| 2146 | |
| 2147 create_view_fail: | |
| 2148 sqlite3SelectDelete(db, pSelect); | |
| 2149 sqlite3ExprListDelete(db, pCNames); | |
| 2150 return; | |
| 2151 } | |
| 2152 #endif /* SQLITE_OMIT_VIEW */ | |
| 2153 | |
| 2154 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) | |
| 2155 /* | |
| 2156 ** The Table structure pTable is really a VIEW. Fill in the names of | |
| 2157 ** the columns of the view in the pTable structure. Return the number | |
| 2158 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. | |
| 2159 */ | |
| 2160 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ | |
| 2161 Table *pSelTab; /* A fake table from which we get the result set */ | |
| 2162 Select *pSel; /* Copy of the SELECT that implements the view */ | |
| 2163 int nErr = 0; /* Number of errors encountered */ | |
| 2164 int n; /* Temporarily holds the number of cursors assigned */ | |
| 2165 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ | |
| 2166 sqlite3_xauth xAuth; /* Saved xAuth pointer */ | |
| 2167 u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */ | |
| 2168 | |
| 2169 assert( pTable ); | |
| 2170 | |
| 2171 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 2172 if( sqlite3VtabCallConnect(pParse, pTable) ){ | |
| 2173 return SQLITE_ERROR; | |
| 2174 } | |
| 2175 if( IsVirtual(pTable) ) return 0; | |
| 2176 #endif | |
| 2177 | |
| 2178 #ifndef SQLITE_OMIT_VIEW | |
| 2179 /* A positive nCol means the columns names for this view are | |
| 2180 ** already known. | |
| 2181 */ | |
| 2182 if( pTable->nCol>0 ) return 0; | |
| 2183 | |
| 2184 /* A negative nCol is a special marker meaning that we are currently | |
| 2185 ** trying to compute the column names. If we enter this routine with | |
| 2186 ** a negative nCol, it means two or more views form a loop, like this: | |
| 2187 ** | |
| 2188 ** CREATE VIEW one AS SELECT * FROM two; | |
| 2189 ** CREATE VIEW two AS SELECT * FROM one; | |
| 2190 ** | |
| 2191 ** Actually, the error above is now caught prior to reaching this point. | |
| 2192 ** But the following test is still important as it does come up | |
| 2193 ** in the following: | |
| 2194 ** | |
| 2195 ** CREATE TABLE main.ex1(a); | |
| 2196 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; | |
| 2197 ** SELECT * FROM temp.ex1; | |
| 2198 */ | |
| 2199 if( pTable->nCol<0 ){ | |
| 2200 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); | |
| 2201 return 1; | |
| 2202 } | |
| 2203 assert( pTable->nCol>=0 ); | |
| 2204 | |
| 2205 /* If we get this far, it means we need to compute the table names. | |
| 2206 ** Note that the call to sqlite3ResultSetOfSelect() will expand any | |
| 2207 ** "*" elements in the results set of the view and will assign cursors | |
| 2208 ** to the elements of the FROM clause. But we do not want these changes | |
| 2209 ** to be permanent. So the computation is done on a copy of the SELECT | |
| 2210 ** statement that defines the view. | |
| 2211 */ | |
| 2212 assert( pTable->pSelect ); | |
| 2213 bEnabledLA = db->lookaside.bEnabled; | |
| 2214 if( pTable->pCheck ){ | |
| 2215 db->lookaside.bEnabled = 0; | |
| 2216 sqlite3ColumnsFromExprList(pParse, pTable->pCheck, | |
| 2217 &pTable->nCol, &pTable->aCol); | |
| 2218 }else{ | |
| 2219 pSel = sqlite3SelectDup(db, pTable->pSelect, 0); | |
| 2220 if( pSel ){ | |
| 2221 n = pParse->nTab; | |
| 2222 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); | |
| 2223 pTable->nCol = -1; | |
| 2224 db->lookaside.bEnabled = 0; | |
| 2225 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 2226 xAuth = db->xAuth; | |
| 2227 db->xAuth = 0; | |
| 2228 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); | |
| 2229 db->xAuth = xAuth; | |
| 2230 #else | |
| 2231 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); | |
| 2232 #endif | |
| 2233 pParse->nTab = n; | |
| 2234 if( pSelTab ){ | |
| 2235 assert( pTable->aCol==0 ); | |
| 2236 pTable->nCol = pSelTab->nCol; | |
| 2237 pTable->aCol = pSelTab->aCol; | |
| 2238 pSelTab->nCol = 0; | |
| 2239 pSelTab->aCol = 0; | |
| 2240 sqlite3DeleteTable(db, pSelTab); | |
| 2241 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); | |
| 2242 }else{ | |
| 2243 pTable->nCol = 0; | |
| 2244 nErr++; | |
| 2245 } | |
| 2246 sqlite3SelectDelete(db, pSel); | |
| 2247 } else { | |
| 2248 nErr++; | |
| 2249 } | |
| 2250 } | |
| 2251 db->lookaside.bEnabled = bEnabledLA; | |
| 2252 pTable->pSchema->schemaFlags |= DB_UnresetViews; | |
| 2253 #endif /* SQLITE_OMIT_VIEW */ | |
| 2254 return nErr; | |
| 2255 } | |
| 2256 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ | |
| 2257 | |
| 2258 #ifndef SQLITE_OMIT_VIEW | |
| 2259 /* | |
| 2260 ** Clear the column names from every VIEW in database idx. | |
| 2261 */ | |
| 2262 static void sqliteViewResetAll(sqlite3 *db, int idx){ | |
| 2263 HashElem *i; | |
| 2264 assert( sqlite3SchemaMutexHeld(db, idx, 0) ); | |
| 2265 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; | |
| 2266 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ | |
| 2267 Table *pTab = sqliteHashData(i); | |
| 2268 if( pTab->pSelect ){ | |
| 2269 sqlite3DeleteColumnNames(db, pTab); | |
| 2270 pTab->aCol = 0; | |
| 2271 pTab->nCol = 0; | |
| 2272 } | |
| 2273 } | |
| 2274 DbClearProperty(db, idx, DB_UnresetViews); | |
| 2275 } | |
| 2276 #else | |
| 2277 # define sqliteViewResetAll(A,B) | |
| 2278 #endif /* SQLITE_OMIT_VIEW */ | |
| 2279 | |
| 2280 /* | |
| 2281 ** This function is called by the VDBE to adjust the internal schema | |
| 2282 ** used by SQLite when the btree layer moves a table root page. The | |
| 2283 ** root-page of a table or index in database iDb has changed from iFrom | |
| 2284 ** to iTo. | |
| 2285 ** | |
| 2286 ** Ticket #1728: The symbol table might still contain information | |
| 2287 ** on tables and/or indices that are the process of being deleted. | |
| 2288 ** If you are unlucky, one of those deleted indices or tables might | |
| 2289 ** have the same rootpage number as the real table or index that is | |
| 2290 ** being moved. So we cannot stop searching after the first match | |
| 2291 ** because the first match might be for one of the deleted indices | |
| 2292 ** or tables and not the table/index that is actually being moved. | |
| 2293 ** We must continue looping until all tables and indices with | |
| 2294 ** rootpage==iFrom have been converted to have a rootpage of iTo | |
| 2295 ** in order to be certain that we got the right one. | |
| 2296 */ | |
| 2297 #ifndef SQLITE_OMIT_AUTOVACUUM | |
| 2298 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ | |
| 2299 HashElem *pElem; | |
| 2300 Hash *pHash; | |
| 2301 Db *pDb; | |
| 2302 | |
| 2303 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 2304 pDb = &db->aDb[iDb]; | |
| 2305 pHash = &pDb->pSchema->tblHash; | |
| 2306 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ | |
| 2307 Table *pTab = sqliteHashData(pElem); | |
| 2308 if( pTab->tnum==iFrom ){ | |
| 2309 pTab->tnum = iTo; | |
| 2310 } | |
| 2311 } | |
| 2312 pHash = &pDb->pSchema->idxHash; | |
| 2313 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ | |
| 2314 Index *pIdx = sqliteHashData(pElem); | |
| 2315 if( pIdx->tnum==iFrom ){ | |
| 2316 pIdx->tnum = iTo; | |
| 2317 } | |
| 2318 } | |
| 2319 } | |
| 2320 #endif | |
| 2321 | |
| 2322 /* | |
| 2323 ** Write code to erase the table with root-page iTable from database iDb. | |
| 2324 ** Also write code to modify the sqlite_master table and internal schema | |
| 2325 ** if a root-page of another table is moved by the btree-layer whilst | |
| 2326 ** erasing iTable (this can happen with an auto-vacuum database). | |
| 2327 */ | |
| 2328 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ | |
| 2329 Vdbe *v = sqlite3GetVdbe(pParse); | |
| 2330 int r1 = sqlite3GetTempReg(pParse); | |
| 2331 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); | |
| 2332 sqlite3MayAbort(pParse); | |
| 2333 #ifndef SQLITE_OMIT_AUTOVACUUM | |
| 2334 /* OP_Destroy stores an in integer r1. If this integer | |
| 2335 ** is non-zero, then it is the root page number of a table moved to | |
| 2336 ** location iTable. The following code modifies the sqlite_master table to | |
| 2337 ** reflect this. | |
| 2338 ** | |
| 2339 ** The "#NNN" in the SQL is a special constant that means whatever value | |
| 2340 ** is in register NNN. See grammar rules associated with the TK_REGISTER | |
| 2341 ** token for additional information. | |
| 2342 */ | |
| 2343 sqlite3NestedParse(pParse, | |
| 2344 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", | |
| 2345 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); | |
| 2346 #endif | |
| 2347 sqlite3ReleaseTempReg(pParse, r1); | |
| 2348 } | |
| 2349 | |
| 2350 /* | |
| 2351 ** Write VDBE code to erase table pTab and all associated indices on disk. | |
| 2352 ** Code to update the sqlite_master tables and internal schema definitions | |
| 2353 ** in case a root-page belonging to another table is moved by the btree layer | |
| 2354 ** is also added (this can happen with an auto-vacuum database). | |
| 2355 */ | |
| 2356 static void destroyTable(Parse *pParse, Table *pTab){ | |
| 2357 #ifdef SQLITE_OMIT_AUTOVACUUM | |
| 2358 Index *pIdx; | |
| 2359 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); | |
| 2360 destroyRootPage(pParse, pTab->tnum, iDb); | |
| 2361 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | |
| 2362 destroyRootPage(pParse, pIdx->tnum, iDb); | |
| 2363 } | |
| 2364 #else | |
| 2365 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM | |
| 2366 ** is not defined), then it is important to call OP_Destroy on the | |
| 2367 ** table and index root-pages in order, starting with the numerically | |
| 2368 ** largest root-page number. This guarantees that none of the root-pages | |
| 2369 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the | |
| 2370 ** following were coded: | |
| 2371 ** | |
| 2372 ** OP_Destroy 4 0 | |
| 2373 ** ... | |
| 2374 ** OP_Destroy 5 0 | |
| 2375 ** | |
| 2376 ** and root page 5 happened to be the largest root-page number in the | |
| 2377 ** database, then root page 5 would be moved to page 4 by the | |
| 2378 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit | |
| 2379 ** a free-list page. | |
| 2380 */ | |
| 2381 int iTab = pTab->tnum; | |
| 2382 int iDestroyed = 0; | |
| 2383 | |
| 2384 while( 1 ){ | |
| 2385 Index *pIdx; | |
| 2386 int iLargest = 0; | |
| 2387 | |
| 2388 if( iDestroyed==0 || iTab<iDestroyed ){ | |
| 2389 iLargest = iTab; | |
| 2390 } | |
| 2391 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | |
| 2392 int iIdx = pIdx->tnum; | |
| 2393 assert( pIdx->pSchema==pTab->pSchema ); | |
| 2394 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ | |
| 2395 iLargest = iIdx; | |
| 2396 } | |
| 2397 } | |
| 2398 if( iLargest==0 ){ | |
| 2399 return; | |
| 2400 }else{ | |
| 2401 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); | |
| 2402 assert( iDb>=0 && iDb<pParse->db->nDb ); | |
| 2403 destroyRootPage(pParse, iLargest, iDb); | |
| 2404 iDestroyed = iLargest; | |
| 2405 } | |
| 2406 } | |
| 2407 #endif | |
| 2408 } | |
| 2409 | |
| 2410 /* | |
| 2411 ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) | |
| 2412 ** after a DROP INDEX or DROP TABLE command. | |
| 2413 */ | |
| 2414 static void sqlite3ClearStatTables( | |
| 2415 Parse *pParse, /* The parsing context */ | |
| 2416 int iDb, /* The database number */ | |
| 2417 const char *zType, /* "idx" or "tbl" */ | |
| 2418 const char *zName /* Name of index or table */ | |
| 2419 ){ | |
| 2420 int i; | |
| 2421 const char *zDbName = pParse->db->aDb[iDb].zName; | |
| 2422 for(i=1; i<=4; i++){ | |
| 2423 char zTab[24]; | |
| 2424 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); | |
| 2425 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ | |
| 2426 sqlite3NestedParse(pParse, | |
| 2427 "DELETE FROM %Q.%s WHERE %s=%Q", | |
| 2428 zDbName, zTab, zType, zName | |
| 2429 ); | |
| 2430 } | |
| 2431 } | |
| 2432 } | |
| 2433 | |
| 2434 /* | |
| 2435 ** Generate code to drop a table. | |
| 2436 */ | |
| 2437 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ | |
| 2438 Vdbe *v; | |
| 2439 sqlite3 *db = pParse->db; | |
| 2440 Trigger *pTrigger; | |
| 2441 Db *pDb = &db->aDb[iDb]; | |
| 2442 | |
| 2443 v = sqlite3GetVdbe(pParse); | |
| 2444 assert( v!=0 ); | |
| 2445 sqlite3BeginWriteOperation(pParse, 1, iDb); | |
| 2446 | |
| 2447 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 2448 if( IsVirtual(pTab) ){ | |
| 2449 sqlite3VdbeAddOp0(v, OP_VBegin); | |
| 2450 } | |
| 2451 #endif | |
| 2452 | |
| 2453 /* Drop all triggers associated with the table being dropped. Code | |
| 2454 ** is generated to remove entries from sqlite_master and/or | |
| 2455 ** sqlite_temp_master if required. | |
| 2456 */ | |
| 2457 pTrigger = sqlite3TriggerList(pParse, pTab); | |
| 2458 while( pTrigger ){ | |
| 2459 assert( pTrigger->pSchema==pTab->pSchema || | |
| 2460 pTrigger->pSchema==db->aDb[1].pSchema ); | |
| 2461 sqlite3DropTriggerPtr(pParse, pTrigger); | |
| 2462 pTrigger = pTrigger->pNext; | |
| 2463 } | |
| 2464 | |
| 2465 #ifndef SQLITE_OMIT_AUTOINCREMENT | |
| 2466 /* Remove any entries of the sqlite_sequence table associated with | |
| 2467 ** the table being dropped. This is done before the table is dropped | |
| 2468 ** at the btree level, in case the sqlite_sequence table needs to | |
| 2469 ** move as a result of the drop (can happen in auto-vacuum mode). | |
| 2470 */ | |
| 2471 if( pTab->tabFlags & TF_Autoincrement ){ | |
| 2472 sqlite3NestedParse(pParse, | |
| 2473 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", | |
| 2474 pDb->zName, pTab->zName | |
| 2475 ); | |
| 2476 } | |
| 2477 #endif | |
| 2478 | |
| 2479 /* Drop all SQLITE_MASTER table and index entries that refer to the | |
| 2480 ** table. The program name loops through the master table and deletes | |
| 2481 ** every row that refers to a table of the same name as the one being | |
| 2482 ** dropped. Triggers are handled separately because a trigger can be | |
| 2483 ** created in the temp database that refers to a table in another | |
| 2484 ** database. | |
| 2485 */ | |
| 2486 sqlite3NestedParse(pParse, | |
| 2487 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", | |
| 2488 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); | |
| 2489 if( !isView && !IsVirtual(pTab) ){ | |
| 2490 destroyTable(pParse, pTab); | |
| 2491 } | |
| 2492 | |
| 2493 /* Remove the table entry from SQLite's internal schema and modify | |
| 2494 ** the schema cookie. | |
| 2495 */ | |
| 2496 if( IsVirtual(pTab) ){ | |
| 2497 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); | |
| 2498 } | |
| 2499 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); | |
| 2500 sqlite3ChangeCookie(pParse, iDb); | |
| 2501 sqliteViewResetAll(db, iDb); | |
| 2502 } | |
| 2503 | |
| 2504 /* | |
| 2505 ** This routine is called to do the work of a DROP TABLE statement. | |
| 2506 ** pName is the name of the table to be dropped. | |
| 2507 */ | |
| 2508 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ | |
| 2509 Table *pTab; | |
| 2510 Vdbe *v; | |
| 2511 sqlite3 *db = pParse->db; | |
| 2512 int iDb; | |
| 2513 | |
| 2514 if( db->mallocFailed ){ | |
| 2515 goto exit_drop_table; | |
| 2516 } | |
| 2517 assert( pParse->nErr==0 ); | |
| 2518 assert( pName->nSrc==1 ); | |
| 2519 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; | |
| 2520 if( noErr ) db->suppressErr++; | |
| 2521 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); | |
| 2522 if( noErr ) db->suppressErr--; | |
| 2523 | |
| 2524 if( pTab==0 ){ | |
| 2525 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); | |
| 2526 goto exit_drop_table; | |
| 2527 } | |
| 2528 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); | |
| 2529 assert( iDb>=0 && iDb<db->nDb ); | |
| 2530 | |
| 2531 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure | |
| 2532 ** it is initialized. | |
| 2533 */ | |
| 2534 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ | |
| 2535 goto exit_drop_table; | |
| 2536 } | |
| 2537 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 2538 { | |
| 2539 int code; | |
| 2540 const char *zTab = SCHEMA_TABLE(iDb); | |
| 2541 const char *zDb = db->aDb[iDb].zName; | |
| 2542 const char *zArg2 = 0; | |
| 2543 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ | |
| 2544 goto exit_drop_table; | |
| 2545 } | |
| 2546 if( isView ){ | |
| 2547 if( !OMIT_TEMPDB && iDb==1 ){ | |
| 2548 code = SQLITE_DROP_TEMP_VIEW; | |
| 2549 }else{ | |
| 2550 code = SQLITE_DROP_VIEW; | |
| 2551 } | |
| 2552 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 2553 }else if( IsVirtual(pTab) ){ | |
| 2554 code = SQLITE_DROP_VTABLE; | |
| 2555 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; | |
| 2556 #endif | |
| 2557 }else{ | |
| 2558 if( !OMIT_TEMPDB && iDb==1 ){ | |
| 2559 code = SQLITE_DROP_TEMP_TABLE; | |
| 2560 }else{ | |
| 2561 code = SQLITE_DROP_TABLE; | |
| 2562 } | |
| 2563 } | |
| 2564 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ | |
| 2565 goto exit_drop_table; | |
| 2566 } | |
| 2567 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ | |
| 2568 goto exit_drop_table; | |
| 2569 } | |
| 2570 } | |
| 2571 #endif | |
| 2572 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 | |
| 2573 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ | |
| 2574 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); | |
| 2575 goto exit_drop_table; | |
| 2576 } | |
| 2577 | |
| 2578 #ifndef SQLITE_OMIT_VIEW | |
| 2579 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used | |
| 2580 ** on a table. | |
| 2581 */ | |
| 2582 if( isView && pTab->pSelect==0 ){ | |
| 2583 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); | |
| 2584 goto exit_drop_table; | |
| 2585 } | |
| 2586 if( !isView && pTab->pSelect ){ | |
| 2587 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); | |
| 2588 goto exit_drop_table; | |
| 2589 } | |
| 2590 #endif | |
| 2591 | |
| 2592 /* Generate code to remove the table from the master table | |
| 2593 ** on disk. | |
| 2594 */ | |
| 2595 v = sqlite3GetVdbe(pParse); | |
| 2596 if( v ){ | |
| 2597 sqlite3BeginWriteOperation(pParse, 1, iDb); | |
| 2598 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); | |
| 2599 sqlite3FkDropTable(pParse, pName, pTab); | |
| 2600 sqlite3CodeDropTable(pParse, pTab, iDb, isView); | |
| 2601 } | |
| 2602 | |
| 2603 exit_drop_table: | |
| 2604 sqlite3SrcListDelete(db, pName); | |
| 2605 } | |
| 2606 | |
| 2607 /* | |
| 2608 ** This routine is called to create a new foreign key on the table | |
| 2609 ** currently under construction. pFromCol determines which columns | |
| 2610 ** in the current table point to the foreign key. If pFromCol==0 then | |
| 2611 ** connect the key to the last column inserted. pTo is the name of | |
| 2612 ** the table referred to (a.k.a the "parent" table). pToCol is a list | |
| 2613 ** of tables in the parent pTo table. flags contains all | |
| 2614 ** information about the conflict resolution algorithms specified | |
| 2615 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. | |
| 2616 ** | |
| 2617 ** An FKey structure is created and added to the table currently | |
| 2618 ** under construction in the pParse->pNewTable field. | |
| 2619 ** | |
| 2620 ** The foreign key is set for IMMEDIATE processing. A subsequent call | |
| 2621 ** to sqlite3DeferForeignKey() might change this to DEFERRED. | |
| 2622 */ | |
| 2623 void sqlite3CreateForeignKey( | |
| 2624 Parse *pParse, /* Parsing context */ | |
| 2625 ExprList *pFromCol, /* Columns in this table that point to other table */ | |
| 2626 Token *pTo, /* Name of the other table */ | |
| 2627 ExprList *pToCol, /* Columns in the other table */ | |
| 2628 int flags /* Conflict resolution algorithms. */ | |
| 2629 ){ | |
| 2630 sqlite3 *db = pParse->db; | |
| 2631 #ifndef SQLITE_OMIT_FOREIGN_KEY | |
| 2632 FKey *pFKey = 0; | |
| 2633 FKey *pNextTo; | |
| 2634 Table *p = pParse->pNewTable; | |
| 2635 int nByte; | |
| 2636 int i; | |
| 2637 int nCol; | |
| 2638 char *z; | |
| 2639 | |
| 2640 assert( pTo!=0 ); | |
| 2641 if( p==0 || IN_DECLARE_VTAB ) goto fk_end; | |
| 2642 if( pFromCol==0 ){ | |
| 2643 int iCol = p->nCol-1; | |
| 2644 if( NEVER(iCol<0) ) goto fk_end; | |
| 2645 if( pToCol && pToCol->nExpr!=1 ){ | |
| 2646 sqlite3ErrorMsg(pParse, "foreign key on %s" | |
| 2647 " should reference only one column of table %T", | |
| 2648 p->aCol[iCol].zName, pTo); | |
| 2649 goto fk_end; | |
| 2650 } | |
| 2651 nCol = 1; | |
| 2652 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ | |
| 2653 sqlite3ErrorMsg(pParse, | |
| 2654 "number of columns in foreign key does not match the number of " | |
| 2655 "columns in the referenced table"); | |
| 2656 goto fk_end; | |
| 2657 }else{ | |
| 2658 nCol = pFromCol->nExpr; | |
| 2659 } | |
| 2660 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; | |
| 2661 if( pToCol ){ | |
| 2662 for(i=0; i<pToCol->nExpr; i++){ | |
| 2663 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; | |
| 2664 } | |
| 2665 } | |
| 2666 pFKey = sqlite3DbMallocZero(db, nByte ); | |
| 2667 if( pFKey==0 ){ | |
| 2668 goto fk_end; | |
| 2669 } | |
| 2670 pFKey->pFrom = p; | |
| 2671 pFKey->pNextFrom = p->pFKey; | |
| 2672 z = (char*)&pFKey->aCol[nCol]; | |
| 2673 pFKey->zTo = z; | |
| 2674 memcpy(z, pTo->z, pTo->n); | |
| 2675 z[pTo->n] = 0; | |
| 2676 sqlite3Dequote(z); | |
| 2677 z += pTo->n+1; | |
| 2678 pFKey->nCol = nCol; | |
| 2679 if( pFromCol==0 ){ | |
| 2680 pFKey->aCol[0].iFrom = p->nCol-1; | |
| 2681 }else{ | |
| 2682 for(i=0; i<nCol; i++){ | |
| 2683 int j; | |
| 2684 for(j=0; j<p->nCol; j++){ | |
| 2685 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ | |
| 2686 pFKey->aCol[i].iFrom = j; | |
| 2687 break; | |
| 2688 } | |
| 2689 } | |
| 2690 if( j>=p->nCol ){ | |
| 2691 sqlite3ErrorMsg(pParse, | |
| 2692 "unknown column \"%s\" in foreign key definition", | |
| 2693 pFromCol->a[i].zName); | |
| 2694 goto fk_end; | |
| 2695 } | |
| 2696 } | |
| 2697 } | |
| 2698 if( pToCol ){ | |
| 2699 for(i=0; i<nCol; i++){ | |
| 2700 int n = sqlite3Strlen30(pToCol->a[i].zName); | |
| 2701 pFKey->aCol[i].zCol = z; | |
| 2702 memcpy(z, pToCol->a[i].zName, n); | |
| 2703 z[n] = 0; | |
| 2704 z += n+1; | |
| 2705 } | |
| 2706 } | |
| 2707 pFKey->isDeferred = 0; | |
| 2708 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ | |
| 2709 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ | |
| 2710 | |
| 2711 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); | |
| 2712 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, | |
| 2713 pFKey->zTo, (void *)pFKey | |
| 2714 ); | |
| 2715 if( pNextTo==pFKey ){ | |
| 2716 db->mallocFailed = 1; | |
| 2717 goto fk_end; | |
| 2718 } | |
| 2719 if( pNextTo ){ | |
| 2720 assert( pNextTo->pPrevTo==0 ); | |
| 2721 pFKey->pNextTo = pNextTo; | |
| 2722 pNextTo->pPrevTo = pFKey; | |
| 2723 } | |
| 2724 | |
| 2725 /* Link the foreign key to the table as the last step. | |
| 2726 */ | |
| 2727 p->pFKey = pFKey; | |
| 2728 pFKey = 0; | |
| 2729 | |
| 2730 fk_end: | |
| 2731 sqlite3DbFree(db, pFKey); | |
| 2732 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ | |
| 2733 sqlite3ExprListDelete(db, pFromCol); | |
| 2734 sqlite3ExprListDelete(db, pToCol); | |
| 2735 } | |
| 2736 | |
| 2737 /* | |
| 2738 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED | |
| 2739 ** clause is seen as part of a foreign key definition. The isDeferred | |
| 2740 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. | |
| 2741 ** The behavior of the most recently created foreign key is adjusted | |
| 2742 ** accordingly. | |
| 2743 */ | |
| 2744 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ | |
| 2745 #ifndef SQLITE_OMIT_FOREIGN_KEY | |
| 2746 Table *pTab; | |
| 2747 FKey *pFKey; | |
| 2748 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; | |
| 2749 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ | |
| 2750 pFKey->isDeferred = (u8)isDeferred; | |
| 2751 #endif | |
| 2752 } | |
| 2753 | |
| 2754 /* | |
| 2755 ** Generate code that will erase and refill index *pIdx. This is | |
| 2756 ** used to initialize a newly created index or to recompute the | |
| 2757 ** content of an index in response to a REINDEX command. | |
| 2758 ** | |
| 2759 ** if memRootPage is not negative, it means that the index is newly | |
| 2760 ** created. The register specified by memRootPage contains the | |
| 2761 ** root page number of the index. If memRootPage is negative, then | |
| 2762 ** the index already exists and must be cleared before being refilled and | |
| 2763 ** the root page number of the index is taken from pIndex->tnum. | |
| 2764 */ | |
| 2765 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ | |
| 2766 Table *pTab = pIndex->pTable; /* The table that is indexed */ | |
| 2767 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ | |
| 2768 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ | |
| 2769 int iSorter; /* Cursor opened by OpenSorter (if in use) */ | |
| 2770 int addr1; /* Address of top of loop */ | |
| 2771 int addr2; /* Address to jump to for next iteration */ | |
| 2772 int tnum; /* Root page of index */ | |
| 2773 int iPartIdxLabel; /* Jump to this label to skip a row */ | |
| 2774 Vdbe *v; /* Generate code into this virtual machine */ | |
| 2775 KeyInfo *pKey; /* KeyInfo for index */ | |
| 2776 int regRecord; /* Register holding assembled index record */ | |
| 2777 sqlite3 *db = pParse->db; /* The database connection */ | |
| 2778 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); | |
| 2779 | |
| 2780 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 2781 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, | |
| 2782 db->aDb[iDb].zName ) ){ | |
| 2783 return; | |
| 2784 } | |
| 2785 #endif | |
| 2786 | |
| 2787 /* Require a write-lock on the table to perform this operation */ | |
| 2788 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); | |
| 2789 | |
| 2790 v = sqlite3GetVdbe(pParse); | |
| 2791 if( v==0 ) return; | |
| 2792 if( memRootPage>=0 ){ | |
| 2793 tnum = memRootPage; | |
| 2794 }else{ | |
| 2795 tnum = pIndex->tnum; | |
| 2796 } | |
| 2797 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); | |
| 2798 | |
| 2799 /* Open the sorter cursor if we are to use one. */ | |
| 2800 iSorter = pParse->nTab++; | |
| 2801 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) | |
| 2802 sqlite3KeyInfoRef(pKey), P4_KEYINFO); | |
| 2803 | |
| 2804 /* Open the table. Loop through all rows of the table, inserting index | |
| 2805 ** records into the sorter. */ | |
| 2806 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); | |
| 2807 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); | |
| 2808 regRecord = sqlite3GetTempReg(pParse); | |
| 2809 | |
| 2810 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); | |
| 2811 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); | |
| 2812 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); | |
| 2813 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); | |
| 2814 sqlite3VdbeJumpHere(v, addr1); | |
| 2815 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); | |
| 2816 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, | |
| 2817 (char *)pKey, P4_KEYINFO); | |
| 2818 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); | |
| 2819 | |
| 2820 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); | |
| 2821 assert( pKey!=0 || db->mallocFailed || pParse->nErr ); | |
| 2822 if( IsUniqueIndex(pIndex) && pKey!=0 ){ | |
| 2823 int j2 = sqlite3VdbeCurrentAddr(v) + 3; | |
| 2824 sqlite3VdbeGoto(v, j2); | |
| 2825 addr2 = sqlite3VdbeCurrentAddr(v); | |
| 2826 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, | |
| 2827 pIndex->nKeyCol); VdbeCoverage(v); | |
| 2828 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); | |
| 2829 }else{ | |
| 2830 addr2 = sqlite3VdbeCurrentAddr(v); | |
| 2831 } | |
| 2832 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); | |
| 2833 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); | |
| 2834 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0); | |
| 2835 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); | |
| 2836 sqlite3ReleaseTempReg(pParse, regRecord); | |
| 2837 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); | |
| 2838 sqlite3VdbeJumpHere(v, addr1); | |
| 2839 | |
| 2840 sqlite3VdbeAddOp1(v, OP_Close, iTab); | |
| 2841 sqlite3VdbeAddOp1(v, OP_Close, iIdx); | |
| 2842 sqlite3VdbeAddOp1(v, OP_Close, iSorter); | |
| 2843 } | |
| 2844 | |
| 2845 /* | |
| 2846 ** Allocate heap space to hold an Index object with nCol columns. | |
| 2847 ** | |
| 2848 ** Increase the allocation size to provide an extra nExtra bytes | |
| 2849 ** of 8-byte aligned space after the Index object and return a | |
| 2850 ** pointer to this extra space in *ppExtra. | |
| 2851 */ | |
| 2852 Index *sqlite3AllocateIndexObject( | |
| 2853 sqlite3 *db, /* Database connection */ | |
| 2854 i16 nCol, /* Total number of columns in the index */ | |
| 2855 int nExtra, /* Number of bytes of extra space to alloc */ | |
| 2856 char **ppExtra /* Pointer to the "extra" space */ | |
| 2857 ){ | |
| 2858 Index *p; /* Allocated index object */ | |
| 2859 int nByte; /* Bytes of space for Index object + arrays */ | |
| 2860 | |
| 2861 nByte = ROUND8(sizeof(Index)) + /* Index structure */ | |
| 2862 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ | |
| 2863 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ | |
| 2864 sizeof(i16)*nCol + /* Index.aiColumn */ | |
| 2865 sizeof(u8)*nCol); /* Index.aSortOrder */ | |
| 2866 p = sqlite3DbMallocZero(db, nByte + nExtra); | |
| 2867 if( p ){ | |
| 2868 char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); | |
| 2869 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); | |
| 2870 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); | |
| 2871 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; | |
| 2872 p->aSortOrder = (u8*)pExtra; | |
| 2873 p->nColumn = nCol; | |
| 2874 p->nKeyCol = nCol - 1; | |
| 2875 *ppExtra = ((char*)p) + nByte; | |
| 2876 } | |
| 2877 return p; | |
| 2878 } | |
| 2879 | |
| 2880 /* | |
| 2881 ** Create a new index for an SQL table. pName1.pName2 is the name of the index | |
| 2882 ** and pTblList is the name of the table that is to be indexed. Both will | |
| 2883 ** be NULL for a primary key or an index that is created to satisfy a | |
| 2884 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable | |
| 2885 ** as the table to be indexed. pParse->pNewTable is a table that is | |
| 2886 ** currently being constructed by a CREATE TABLE statement. | |
| 2887 ** | |
| 2888 ** pList is a list of columns to be indexed. pList will be NULL if this | |
| 2889 ** is a primary key or unique-constraint on the most recent column added | |
| 2890 ** to the table currently under construction. | |
| 2891 ** | |
| 2892 ** If the index is created successfully, return a pointer to the new Index | |
| 2893 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index | |
| 2894 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY) | |
| 2895 */ | |
| 2896 Index *sqlite3CreateIndex( | |
| 2897 Parse *pParse, /* All information about this parse */ | |
| 2898 Token *pName1, /* First part of index name. May be NULL */ | |
| 2899 Token *pName2, /* Second part of index name. May be NULL */ | |
| 2900 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ | |
| 2901 ExprList *pList, /* A list of columns to be indexed */ | |
| 2902 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ | |
| 2903 Token *pStart, /* The CREATE token that begins this statement */ | |
| 2904 Expr *pPIWhere, /* WHERE clause for partial indices */ | |
| 2905 int sortOrder, /* Sort order of primary key when pList==NULL */ | |
| 2906 int ifNotExist /* Omit error if index already exists */ | |
| 2907 ){ | |
| 2908 Index *pRet = 0; /* Pointer to return */ | |
| 2909 Table *pTab = 0; /* Table to be indexed */ | |
| 2910 Index *pIndex = 0; /* The index to be created */ | |
| 2911 char *zName = 0; /* Name of the index */ | |
| 2912 int nName; /* Number of characters in zName */ | |
| 2913 int i, j; | |
| 2914 DbFixer sFix; /* For assigning database names to pTable */ | |
| 2915 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ | |
| 2916 sqlite3 *db = pParse->db; | |
| 2917 Db *pDb; /* The specific table containing the indexed database */ | |
| 2918 int iDb; /* Index of the database that is being written */ | |
| 2919 Token *pName = 0; /* Unqualified name of the index to create */ | |
| 2920 struct ExprList_item *pListItem; /* For looping over pList */ | |
| 2921 int nExtra = 0; /* Space allocated for zExtra[] */ | |
| 2922 int nExtraCol; /* Number of extra columns needed */ | |
| 2923 char *zExtra = 0; /* Extra space after the Index object */ | |
| 2924 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ | |
| 2925 | |
| 2926 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){ | |
| 2927 goto exit_create_index; | |
| 2928 } | |
| 2929 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ | |
| 2930 goto exit_create_index; | |
| 2931 } | |
| 2932 | |
| 2933 /* | |
| 2934 ** Find the table that is to be indexed. Return early if not found. | |
| 2935 */ | |
| 2936 if( pTblName!=0 ){ | |
| 2937 | |
| 2938 /* Use the two-part index name to determine the database | |
| 2939 ** to search for the table. 'Fix' the table name to this db | |
| 2940 ** before looking up the table. | |
| 2941 */ | |
| 2942 assert( pName1 && pName2 ); | |
| 2943 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); | |
| 2944 if( iDb<0 ) goto exit_create_index; | |
| 2945 assert( pName && pName->z ); | |
| 2946 | |
| 2947 #ifndef SQLITE_OMIT_TEMPDB | |
| 2948 /* If the index name was unqualified, check if the table | |
| 2949 ** is a temp table. If so, set the database to 1. Do not do this | |
| 2950 ** if initialising a database schema. | |
| 2951 */ | |
| 2952 if( !db->init.busy ){ | |
| 2953 pTab = sqlite3SrcListLookup(pParse, pTblName); | |
| 2954 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ | |
| 2955 iDb = 1; | |
| 2956 } | |
| 2957 } | |
| 2958 #endif | |
| 2959 | |
| 2960 sqlite3FixInit(&sFix, pParse, iDb, "index", pName); | |
| 2961 if( sqlite3FixSrcList(&sFix, pTblName) ){ | |
| 2962 /* Because the parser constructs pTblName from a single identifier, | |
| 2963 ** sqlite3FixSrcList can never fail. */ | |
| 2964 assert(0); | |
| 2965 } | |
| 2966 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); | |
| 2967 assert( db->mallocFailed==0 || pTab==0 ); | |
| 2968 if( pTab==0 ) goto exit_create_index; | |
| 2969 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ | |
| 2970 sqlite3ErrorMsg(pParse, | |
| 2971 "cannot create a TEMP index on non-TEMP table \"%s\"", | |
| 2972 pTab->zName); | |
| 2973 goto exit_create_index; | |
| 2974 } | |
| 2975 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); | |
| 2976 }else{ | |
| 2977 assert( pName==0 ); | |
| 2978 assert( pStart==0 ); | |
| 2979 pTab = pParse->pNewTable; | |
| 2980 if( !pTab ) goto exit_create_index; | |
| 2981 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); | |
| 2982 } | |
| 2983 pDb = &db->aDb[iDb]; | |
| 2984 | |
| 2985 assert( pTab!=0 ); | |
| 2986 assert( pParse->nErr==0 ); | |
| 2987 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 | |
| 2988 && db->init.busy==0 | |
| 2989 #if SQLITE_USER_AUTHENTICATION | |
| 2990 && sqlite3UserAuthTable(pTab->zName)==0 | |
| 2991 #endif | |
| 2992 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ | |
| 2993 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); | |
| 2994 goto exit_create_index; | |
| 2995 } | |
| 2996 #ifndef SQLITE_OMIT_VIEW | |
| 2997 if( pTab->pSelect ){ | |
| 2998 sqlite3ErrorMsg(pParse, "views may not be indexed"); | |
| 2999 goto exit_create_index; | |
| 3000 } | |
| 3001 #endif | |
| 3002 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 3003 if( IsVirtual(pTab) ){ | |
| 3004 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); | |
| 3005 goto exit_create_index; | |
| 3006 } | |
| 3007 #endif | |
| 3008 | |
| 3009 /* | |
| 3010 ** Find the name of the index. Make sure there is not already another | |
| 3011 ** index or table with the same name. | |
| 3012 ** | |
| 3013 ** Exception: If we are reading the names of permanent indices from the | |
| 3014 ** sqlite_master table (because some other process changed the schema) and | |
| 3015 ** one of the index names collides with the name of a temporary table or | |
| 3016 ** index, then we will continue to process this index. | |
| 3017 ** | |
| 3018 ** If pName==0 it means that we are | |
| 3019 ** dealing with a primary key or UNIQUE constraint. We have to invent our | |
| 3020 ** own name. | |
| 3021 */ | |
| 3022 if( pName ){ | |
| 3023 zName = sqlite3NameFromToken(db, pName); | |
| 3024 if( zName==0 ) goto exit_create_index; | |
| 3025 assert( pName->z!=0 ); | |
| 3026 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ | |
| 3027 goto exit_create_index; | |
| 3028 } | |
| 3029 if( !db->init.busy ){ | |
| 3030 if( sqlite3FindTable(db, zName, 0)!=0 ){ | |
| 3031 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); | |
| 3032 goto exit_create_index; | |
| 3033 } | |
| 3034 } | |
| 3035 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ | |
| 3036 if( !ifNotExist ){ | |
| 3037 sqlite3ErrorMsg(pParse, "index %s already exists", zName); | |
| 3038 }else{ | |
| 3039 assert( !db->init.busy ); | |
| 3040 sqlite3CodeVerifySchema(pParse, iDb); | |
| 3041 } | |
| 3042 goto exit_create_index; | |
| 3043 } | |
| 3044 }else{ | |
| 3045 int n; | |
| 3046 Index *pLoop; | |
| 3047 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} | |
| 3048 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); | |
| 3049 if( zName==0 ){ | |
| 3050 goto exit_create_index; | |
| 3051 } | |
| 3052 } | |
| 3053 | |
| 3054 /* Check for authorization to create an index. | |
| 3055 */ | |
| 3056 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 3057 { | |
| 3058 const char *zDb = pDb->zName; | |
| 3059 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ | |
| 3060 goto exit_create_index; | |
| 3061 } | |
| 3062 i = SQLITE_CREATE_INDEX; | |
| 3063 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; | |
| 3064 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ | |
| 3065 goto exit_create_index; | |
| 3066 } | |
| 3067 } | |
| 3068 #endif | |
| 3069 | |
| 3070 /* If pList==0, it means this routine was called to make a primary | |
| 3071 ** key out of the last column added to the table under construction. | |
| 3072 ** So create a fake list to simulate this. | |
| 3073 */ | |
| 3074 if( pList==0 ){ | |
| 3075 Token prevCol; | |
| 3076 prevCol.z = pTab->aCol[pTab->nCol-1].zName; | |
| 3077 prevCol.n = sqlite3Strlen30(prevCol.z); | |
| 3078 pList = sqlite3ExprListAppend(pParse, 0, | |
| 3079 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); | |
| 3080 if( pList==0 ) goto exit_create_index; | |
| 3081 assert( pList->nExpr==1 ); | |
| 3082 sqlite3ExprListSetSortOrder(pList, sortOrder); | |
| 3083 }else{ | |
| 3084 sqlite3ExprListCheckLength(pParse, pList, "index"); | |
| 3085 } | |
| 3086 | |
| 3087 /* Figure out how many bytes of space are required to store explicitly | |
| 3088 ** specified collation sequence names. | |
| 3089 */ | |
| 3090 for(i=0; i<pList->nExpr; i++){ | |
| 3091 Expr *pExpr = pList->a[i].pExpr; | |
| 3092 assert( pExpr!=0 ); | |
| 3093 if( pExpr->op==TK_COLLATE ){ | |
| 3094 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); | |
| 3095 } | |
| 3096 } | |
| 3097 | |
| 3098 /* | |
| 3099 ** Allocate the index structure. | |
| 3100 */ | |
| 3101 nName = sqlite3Strlen30(zName); | |
| 3102 nExtraCol = pPk ? pPk->nKeyCol : 1; | |
| 3103 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, | |
| 3104 nName + nExtra + 1, &zExtra); | |
| 3105 if( db->mallocFailed ){ | |
| 3106 goto exit_create_index; | |
| 3107 } | |
| 3108 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); | |
| 3109 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); | |
| 3110 pIndex->zName = zExtra; | |
| 3111 zExtra += nName + 1; | |
| 3112 memcpy(pIndex->zName, zName, nName+1); | |
| 3113 pIndex->pTable = pTab; | |
| 3114 pIndex->onError = (u8)onError; | |
| 3115 pIndex->uniqNotNull = onError!=OE_None; | |
| 3116 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE; | |
| 3117 pIndex->pSchema = db->aDb[iDb].pSchema; | |
| 3118 pIndex->nKeyCol = pList->nExpr; | |
| 3119 if( pPIWhere ){ | |
| 3120 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); | |
| 3121 pIndex->pPartIdxWhere = pPIWhere; | |
| 3122 pPIWhere = 0; | |
| 3123 } | |
| 3124 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 3125 | |
| 3126 /* Check to see if we should honor DESC requests on index columns | |
| 3127 */ | |
| 3128 if( pDb->pSchema->file_format>=4 ){ | |
| 3129 sortOrderMask = -1; /* Honor DESC */ | |
| 3130 }else{ | |
| 3131 sortOrderMask = 0; /* Ignore DESC */ | |
| 3132 } | |
| 3133 | |
| 3134 /* Analyze the list of expressions that form the terms of the index and | |
| 3135 ** report any errors. In the common case where the expression is exactly | |
| 3136 ** a table column, store that column in aiColumn[]. For general expressions, | |
| 3137 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. | |
| 3138 ** | |
| 3139 ** TODO: Issue a warning if two or more columns of the index are identical. | |
| 3140 ** TODO: Issue a warning if the table primary key is used as part of the | |
| 3141 ** index key. | |
| 3142 */ | |
| 3143 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ | |
| 3144 Expr *pCExpr; /* The i-th index expression */ | |
| 3145 int requestedSortOrder; /* ASC or DESC on the i-th expression */ | |
| 3146 const char *zColl; /* Collation sequence name */ | |
| 3147 | |
| 3148 sqlite3StringToId(pListItem->pExpr); | |
| 3149 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); | |
| 3150 if( pParse->nErr ) goto exit_create_index; | |
| 3151 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); | |
| 3152 if( pCExpr->op!=TK_COLUMN ){ | |
| 3153 if( pTab==pParse->pNewTable ){ | |
| 3154 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " | |
| 3155 "UNIQUE constraints"); | |
| 3156 goto exit_create_index; | |
| 3157 } | |
| 3158 if( pIndex->aColExpr==0 ){ | |
| 3159 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); | |
| 3160 pIndex->aColExpr = pCopy; | |
| 3161 if( !db->mallocFailed ){ | |
| 3162 assert( pCopy!=0 ); | |
| 3163 pListItem = &pCopy->a[i]; | |
| 3164 } | |
| 3165 } | |
| 3166 j = XN_EXPR; | |
| 3167 pIndex->aiColumn[i] = XN_EXPR; | |
| 3168 pIndex->uniqNotNull = 0; | |
| 3169 }else{ | |
| 3170 j = pCExpr->iColumn; | |
| 3171 assert( j<=0x7fff ); | |
| 3172 if( j<0 ){ | |
| 3173 j = pTab->iPKey; | |
| 3174 }else if( pTab->aCol[j].notNull==0 ){ | |
| 3175 pIndex->uniqNotNull = 0; | |
| 3176 } | |
| 3177 pIndex->aiColumn[i] = (i16)j; | |
| 3178 } | |
| 3179 zColl = 0; | |
| 3180 if( pListItem->pExpr->op==TK_COLLATE ){ | |
| 3181 int nColl; | |
| 3182 zColl = pListItem->pExpr->u.zToken; | |
| 3183 nColl = sqlite3Strlen30(zColl) + 1; | |
| 3184 assert( nExtra>=nColl ); | |
| 3185 memcpy(zExtra, zColl, nColl); | |
| 3186 zColl = zExtra; | |
| 3187 zExtra += nColl; | |
| 3188 nExtra -= nColl; | |
| 3189 }else if( j>=0 ){ | |
| 3190 zColl = pTab->aCol[j].zColl; | |
| 3191 } | |
| 3192 if( !zColl ) zColl = sqlite3StrBINARY; | |
| 3193 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ | |
| 3194 goto exit_create_index; | |
| 3195 } | |
| 3196 pIndex->azColl[i] = zColl; | |
| 3197 requestedSortOrder = pListItem->sortOrder & sortOrderMask; | |
| 3198 pIndex->aSortOrder[i] = (u8)requestedSortOrder; | |
| 3199 } | |
| 3200 | |
| 3201 /* Append the table key to the end of the index. For WITHOUT ROWID | |
| 3202 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For | |
| 3203 ** normal tables (when pPk==0) this will be the rowid. | |
| 3204 */ | |
| 3205 if( pPk ){ | |
| 3206 for(j=0; j<pPk->nKeyCol; j++){ | |
| 3207 int x = pPk->aiColumn[j]; | |
| 3208 assert( x>=0 ); | |
| 3209 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ | |
| 3210 pIndex->nColumn--; | |
| 3211 }else{ | |
| 3212 pIndex->aiColumn[i] = x; | |
| 3213 pIndex->azColl[i] = pPk->azColl[j]; | |
| 3214 pIndex->aSortOrder[i] = pPk->aSortOrder[j]; | |
| 3215 i++; | |
| 3216 } | |
| 3217 } | |
| 3218 assert( i==pIndex->nColumn ); | |
| 3219 }else{ | |
| 3220 pIndex->aiColumn[i] = XN_ROWID; | |
| 3221 pIndex->azColl[i] = sqlite3StrBINARY; | |
| 3222 } | |
| 3223 sqlite3DefaultRowEst(pIndex); | |
| 3224 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); | |
| 3225 | |
| 3226 if( pTab==pParse->pNewTable ){ | |
| 3227 /* This routine has been called to create an automatic index as a | |
| 3228 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or | |
| 3229 ** a PRIMARY KEY or UNIQUE clause following the column definitions. | |
| 3230 ** i.e. one of: | |
| 3231 ** | |
| 3232 ** CREATE TABLE t(x PRIMARY KEY, y); | |
| 3233 ** CREATE TABLE t(x, y, UNIQUE(x, y)); | |
| 3234 ** | |
| 3235 ** Either way, check to see if the table already has such an index. If | |
| 3236 ** so, don't bother creating this one. This only applies to | |
| 3237 ** automatically created indices. Users can do as they wish with | |
| 3238 ** explicit indices. | |
| 3239 ** | |
| 3240 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent | |
| 3241 ** (and thus suppressing the second one) even if they have different | |
| 3242 ** sort orders. | |
| 3243 ** | |
| 3244 ** If there are different collating sequences or if the columns of | |
| 3245 ** the constraint occur in different orders, then the constraints are | |
| 3246 ** considered distinct and both result in separate indices. | |
| 3247 */ | |
| 3248 Index *pIdx; | |
| 3249 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | |
| 3250 int k; | |
| 3251 assert( IsUniqueIndex(pIdx) ); | |
| 3252 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); | |
| 3253 assert( IsUniqueIndex(pIndex) ); | |
| 3254 | |
| 3255 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; | |
| 3256 for(k=0; k<pIdx->nKeyCol; k++){ | |
| 3257 const char *z1; | |
| 3258 const char *z2; | |
| 3259 assert( pIdx->aiColumn[k]>=0 ); | |
| 3260 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; | |
| 3261 z1 = pIdx->azColl[k]; | |
| 3262 z2 = pIndex->azColl[k]; | |
| 3263 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; | |
| 3264 } | |
| 3265 if( k==pIdx->nKeyCol ){ | |
| 3266 if( pIdx->onError!=pIndex->onError ){ | |
| 3267 /* This constraint creates the same index as a previous | |
| 3268 ** constraint specified somewhere in the CREATE TABLE statement. | |
| 3269 ** However the ON CONFLICT clauses are different. If both this | |
| 3270 ** constraint and the previous equivalent constraint have explicit | |
| 3271 ** ON CONFLICT clauses this is an error. Otherwise, use the | |
| 3272 ** explicitly specified behavior for the index. | |
| 3273 */ | |
| 3274 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ | |
| 3275 sqlite3ErrorMsg(pParse, | |
| 3276 "conflicting ON CONFLICT clauses specified", 0); | |
| 3277 } | |
| 3278 if( pIdx->onError==OE_Default ){ | |
| 3279 pIdx->onError = pIndex->onError; | |
| 3280 } | |
| 3281 } | |
| 3282 pRet = pIdx; | |
| 3283 goto exit_create_index; | |
| 3284 } | |
| 3285 } | |
| 3286 } | |
| 3287 | |
| 3288 /* Link the new Index structure to its table and to the other | |
| 3289 ** in-memory database structures. | |
| 3290 */ | |
| 3291 assert( pParse->nErr==0 ); | |
| 3292 if( db->init.busy ){ | |
| 3293 Index *p; | |
| 3294 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); | |
| 3295 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, | |
| 3296 pIndex->zName, pIndex); | |
| 3297 if( p ){ | |
| 3298 assert( p==pIndex ); /* Malloc must have failed */ | |
| 3299 db->mallocFailed = 1; | |
| 3300 goto exit_create_index; | |
| 3301 } | |
| 3302 db->flags |= SQLITE_InternChanges; | |
| 3303 if( pTblName!=0 ){ | |
| 3304 pIndex->tnum = db->init.newTnum; | |
| 3305 } | |
| 3306 } | |
| 3307 | |
| 3308 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the | |
| 3309 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then | |
| 3310 ** emit code to allocate the index rootpage on disk and make an entry for | |
| 3311 ** the index in the sqlite_master table and populate the index with | |
| 3312 ** content. But, do not do this if we are simply reading the sqlite_master | |
| 3313 ** table to parse the schema, or if this index is the PRIMARY KEY index | |
| 3314 ** of a WITHOUT ROWID table. | |
| 3315 ** | |
| 3316 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY | |
| 3317 ** or UNIQUE index in a CREATE TABLE statement. Since the table | |
| 3318 ** has just been created, it contains no data and the index initialization | |
| 3319 ** step can be skipped. | |
| 3320 */ | |
| 3321 else if( HasRowid(pTab) || pTblName!=0 ){ | |
| 3322 Vdbe *v; | |
| 3323 char *zStmt; | |
| 3324 int iMem = ++pParse->nMem; | |
| 3325 | |
| 3326 v = sqlite3GetVdbe(pParse); | |
| 3327 if( v==0 ) goto exit_create_index; | |
| 3328 | |
| 3329 sqlite3BeginWriteOperation(pParse, 1, iDb); | |
| 3330 | |
| 3331 /* Create the rootpage for the index using CreateIndex. But before | |
| 3332 ** doing so, code a Noop instruction and store its address in | |
| 3333 ** Index.tnum. This is required in case this index is actually a | |
| 3334 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In | |
| 3335 ** that case the convertToWithoutRowidTable() routine will replace | |
| 3336 ** the Noop with a Goto to jump over the VDBE code generated below. */ | |
| 3337 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); | |
| 3338 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); | |
| 3339 | |
| 3340 /* Gather the complete text of the CREATE INDEX statement into | |
| 3341 ** the zStmt variable | |
| 3342 */ | |
| 3343 if( pStart ){ | |
| 3344 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; | |
| 3345 if( pName->z[n-1]==';' ) n--; | |
| 3346 /* A named index with an explicit CREATE INDEX statement */ | |
| 3347 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", | |
| 3348 onError==OE_None ? "" : " UNIQUE", n, pName->z); | |
| 3349 }else{ | |
| 3350 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ | |
| 3351 /* zStmt = sqlite3MPrintf(""); */ | |
| 3352 zStmt = 0; | |
| 3353 } | |
| 3354 | |
| 3355 /* Add an entry in sqlite_master for this index | |
| 3356 */ | |
| 3357 sqlite3NestedParse(pParse, | |
| 3358 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", | |
| 3359 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), | |
| 3360 pIndex->zName, | |
| 3361 pTab->zName, | |
| 3362 iMem, | |
| 3363 zStmt | |
| 3364 ); | |
| 3365 sqlite3DbFree(db, zStmt); | |
| 3366 | |
| 3367 /* Fill the index with data and reparse the schema. Code an OP_Expire | |
| 3368 ** to invalidate all pre-compiled statements. | |
| 3369 */ | |
| 3370 if( pTblName ){ | |
| 3371 sqlite3RefillIndex(pParse, pIndex, iMem); | |
| 3372 sqlite3ChangeCookie(pParse, iDb); | |
| 3373 sqlite3VdbeAddParseSchemaOp(v, iDb, | |
| 3374 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); | |
| 3375 sqlite3VdbeAddOp1(v, OP_Expire, 0); | |
| 3376 } | |
| 3377 | |
| 3378 sqlite3VdbeJumpHere(v, pIndex->tnum); | |
| 3379 } | |
| 3380 | |
| 3381 /* When adding an index to the list of indices for a table, make | |
| 3382 ** sure all indices labeled OE_Replace come after all those labeled | |
| 3383 ** OE_Ignore. This is necessary for the correct constraint check | |
| 3384 ** processing (in sqlite3GenerateConstraintChecks()) as part of | |
| 3385 ** UPDATE and INSERT statements. | |
| 3386 */ | |
| 3387 if( db->init.busy || pTblName==0 ){ | |
| 3388 if( onError!=OE_Replace || pTab->pIndex==0 | |
| 3389 || pTab->pIndex->onError==OE_Replace){ | |
| 3390 pIndex->pNext = pTab->pIndex; | |
| 3391 pTab->pIndex = pIndex; | |
| 3392 }else{ | |
| 3393 Index *pOther = pTab->pIndex; | |
| 3394 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ | |
| 3395 pOther = pOther->pNext; | |
| 3396 } | |
| 3397 pIndex->pNext = pOther->pNext; | |
| 3398 pOther->pNext = pIndex; | |
| 3399 } | |
| 3400 pRet = pIndex; | |
| 3401 pIndex = 0; | |
| 3402 } | |
| 3403 | |
| 3404 /* Clean up before exiting */ | |
| 3405 exit_create_index: | |
| 3406 if( pIndex ) freeIndex(db, pIndex); | |
| 3407 sqlite3ExprDelete(db, pPIWhere); | |
| 3408 sqlite3ExprListDelete(db, pList); | |
| 3409 sqlite3SrcListDelete(db, pTblName); | |
| 3410 sqlite3DbFree(db, zName); | |
| 3411 return pRet; | |
| 3412 } | |
| 3413 | |
| 3414 /* | |
| 3415 ** Fill the Index.aiRowEst[] array with default information - information | |
| 3416 ** to be used when we have not run the ANALYZE command. | |
| 3417 ** | |
| 3418 ** aiRowEst[0] is supposed to contain the number of elements in the index. | |
| 3419 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the | |
| 3420 ** number of rows in the table that match any particular value of the | |
| 3421 ** first column of the index. aiRowEst[2] is an estimate of the number | |
| 3422 ** of rows that match any particular combination of the first 2 columns | |
| 3423 ** of the index. And so forth. It must always be the case that | |
| 3424 * | |
| 3425 ** aiRowEst[N]<=aiRowEst[N-1] | |
| 3426 ** aiRowEst[N]>=1 | |
| 3427 ** | |
| 3428 ** Apart from that, we have little to go on besides intuition as to | |
| 3429 ** how aiRowEst[] should be initialized. The numbers generated here | |
| 3430 ** are based on typical values found in actual indices. | |
| 3431 */ | |
| 3432 void sqlite3DefaultRowEst(Index *pIdx){ | |
| 3433 /* 10, 9, 8, 7, 6 */ | |
| 3434 LogEst aVal[] = { 33, 32, 30, 28, 26 }; | |
| 3435 LogEst *a = pIdx->aiRowLogEst; | |
| 3436 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); | |
| 3437 int i; | |
| 3438 | |
| 3439 /* Set the first entry (number of rows in the index) to the estimated | |
| 3440 ** number of rows in the table. Or 10, if the estimated number of rows | |
| 3441 ** in the table is less than that. */ | |
| 3442 a[0] = pIdx->pTable->nRowLogEst; | |
| 3443 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); | |
| 3444 | |
| 3445 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is | |
| 3446 ** 6 and each subsequent value (if any) is 5. */ | |
| 3447 memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); | |
| 3448 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ | |
| 3449 a[i] = 23; assert( 23==sqlite3LogEst(5) ); | |
| 3450 } | |
| 3451 | |
| 3452 assert( 0==sqlite3LogEst(1) ); | |
| 3453 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; | |
| 3454 } | |
| 3455 | |
| 3456 /* | |
| 3457 ** This routine will drop an existing named index. This routine | |
| 3458 ** implements the DROP INDEX statement. | |
| 3459 */ | |
| 3460 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ | |
| 3461 Index *pIndex; | |
| 3462 Vdbe *v; | |
| 3463 sqlite3 *db = pParse->db; | |
| 3464 int iDb; | |
| 3465 | |
| 3466 assert( pParse->nErr==0 ); /* Never called with prior errors */ | |
| 3467 if( db->mallocFailed ){ | |
| 3468 goto exit_drop_index; | |
| 3469 } | |
| 3470 assert( pName->nSrc==1 ); | |
| 3471 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ | |
| 3472 goto exit_drop_index; | |
| 3473 } | |
| 3474 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); | |
| 3475 if( pIndex==0 ){ | |
| 3476 if( !ifExists ){ | |
| 3477 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); | |
| 3478 }else{ | |
| 3479 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); | |
| 3480 } | |
| 3481 pParse->checkSchema = 1; | |
| 3482 goto exit_drop_index; | |
| 3483 } | |
| 3484 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ | |
| 3485 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " | |
| 3486 "or PRIMARY KEY constraint cannot be dropped", 0); | |
| 3487 goto exit_drop_index; | |
| 3488 } | |
| 3489 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); | |
| 3490 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 3491 { | |
| 3492 int code = SQLITE_DROP_INDEX; | |
| 3493 Table *pTab = pIndex->pTable; | |
| 3494 const char *zDb = db->aDb[iDb].zName; | |
| 3495 const char *zTab = SCHEMA_TABLE(iDb); | |
| 3496 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ | |
| 3497 goto exit_drop_index; | |
| 3498 } | |
| 3499 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; | |
| 3500 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ | |
| 3501 goto exit_drop_index; | |
| 3502 } | |
| 3503 } | |
| 3504 #endif | |
| 3505 | |
| 3506 /* Generate code to remove the index and from the master table */ | |
| 3507 v = sqlite3GetVdbe(pParse); | |
| 3508 if( v ){ | |
| 3509 sqlite3BeginWriteOperation(pParse, 1, iDb); | |
| 3510 sqlite3NestedParse(pParse, | |
| 3511 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", | |
| 3512 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName | |
| 3513 ); | |
| 3514 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); | |
| 3515 sqlite3ChangeCookie(pParse, iDb); | |
| 3516 destroyRootPage(pParse, pIndex->tnum, iDb); | |
| 3517 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); | |
| 3518 } | |
| 3519 | |
| 3520 exit_drop_index: | |
| 3521 sqlite3SrcListDelete(db, pName); | |
| 3522 } | |
| 3523 | |
| 3524 /* | |
| 3525 ** pArray is a pointer to an array of objects. Each object in the | |
| 3526 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() | |
| 3527 ** to extend the array so that there is space for a new object at the end. | |
| 3528 ** | |
| 3529 ** When this function is called, *pnEntry contains the current size of | |
| 3530 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes | |
| 3531 ** in total). | |
| 3532 ** | |
| 3533 ** If the realloc() is successful (i.e. if no OOM condition occurs), the | |
| 3534 ** space allocated for the new object is zeroed, *pnEntry updated to | |
| 3535 ** reflect the new size of the array and a pointer to the new allocation | |
| 3536 ** returned. *pIdx is set to the index of the new array entry in this case. | |
| 3537 ** | |
| 3538 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains | |
| 3539 ** unchanged and a copy of pArray returned. | |
| 3540 */ | |
| 3541 void *sqlite3ArrayAllocate( | |
| 3542 sqlite3 *db, /* Connection to notify of malloc failures */ | |
| 3543 void *pArray, /* Array of objects. Might be reallocated */ | |
| 3544 int szEntry, /* Size of each object in the array */ | |
| 3545 int *pnEntry, /* Number of objects currently in use */ | |
| 3546 int *pIdx /* Write the index of a new slot here */ | |
| 3547 ){ | |
| 3548 char *z; | |
| 3549 int n = *pnEntry; | |
| 3550 if( (n & (n-1))==0 ){ | |
| 3551 int sz = (n==0) ? 1 : 2*n; | |
| 3552 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); | |
| 3553 if( pNew==0 ){ | |
| 3554 *pIdx = -1; | |
| 3555 return pArray; | |
| 3556 } | |
| 3557 pArray = pNew; | |
| 3558 } | |
| 3559 z = (char*)pArray; | |
| 3560 memset(&z[n * szEntry], 0, szEntry); | |
| 3561 *pIdx = n; | |
| 3562 ++*pnEntry; | |
| 3563 return pArray; | |
| 3564 } | |
| 3565 | |
| 3566 /* | |
| 3567 ** Append a new element to the given IdList. Create a new IdList if | |
| 3568 ** need be. | |
| 3569 ** | |
| 3570 ** A new IdList is returned, or NULL if malloc() fails. | |
| 3571 */ | |
| 3572 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ | |
| 3573 int i; | |
| 3574 if( pList==0 ){ | |
| 3575 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); | |
| 3576 if( pList==0 ) return 0; | |
| 3577 } | |
| 3578 pList->a = sqlite3ArrayAllocate( | |
| 3579 db, | |
| 3580 pList->a, | |
| 3581 sizeof(pList->a[0]), | |
| 3582 &pList->nId, | |
| 3583 &i | |
| 3584 ); | |
| 3585 if( i<0 ){ | |
| 3586 sqlite3IdListDelete(db, pList); | |
| 3587 return 0; | |
| 3588 } | |
| 3589 pList->a[i].zName = sqlite3NameFromToken(db, pToken); | |
| 3590 return pList; | |
| 3591 } | |
| 3592 | |
| 3593 /* | |
| 3594 ** Delete an IdList. | |
| 3595 */ | |
| 3596 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ | |
| 3597 int i; | |
| 3598 if( pList==0 ) return; | |
| 3599 for(i=0; i<pList->nId; i++){ | |
| 3600 sqlite3DbFree(db, pList->a[i].zName); | |
| 3601 } | |
| 3602 sqlite3DbFree(db, pList->a); | |
| 3603 sqlite3DbFree(db, pList); | |
| 3604 } | |
| 3605 | |
| 3606 /* | |
| 3607 ** Return the index in pList of the identifier named zId. Return -1 | |
| 3608 ** if not found. | |
| 3609 */ | |
| 3610 int sqlite3IdListIndex(IdList *pList, const char *zName){ | |
| 3611 int i; | |
| 3612 if( pList==0 ) return -1; | |
| 3613 for(i=0; i<pList->nId; i++){ | |
| 3614 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; | |
| 3615 } | |
| 3616 return -1; | |
| 3617 } | |
| 3618 | |
| 3619 /* | |
| 3620 ** Expand the space allocated for the given SrcList object by | |
| 3621 ** creating nExtra new slots beginning at iStart. iStart is zero based. | |
| 3622 ** New slots are zeroed. | |
| 3623 ** | |
| 3624 ** For example, suppose a SrcList initially contains two entries: A,B. | |
| 3625 ** To append 3 new entries onto the end, do this: | |
| 3626 ** | |
| 3627 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); | |
| 3628 ** | |
| 3629 ** After the call above it would contain: A, B, nil, nil, nil. | |
| 3630 ** If the iStart argument had been 1 instead of 2, then the result | |
| 3631 ** would have been: A, nil, nil, nil, B. To prepend the new slots, | |
| 3632 ** the iStart value would be 0. The result then would | |
| 3633 ** be: nil, nil, nil, A, B. | |
| 3634 ** | |
| 3635 ** If a memory allocation fails the SrcList is unchanged. The | |
| 3636 ** db->mallocFailed flag will be set to true. | |
| 3637 */ | |
| 3638 SrcList *sqlite3SrcListEnlarge( | |
| 3639 sqlite3 *db, /* Database connection to notify of OOM errors */ | |
| 3640 SrcList *pSrc, /* The SrcList to be enlarged */ | |
| 3641 int nExtra, /* Number of new slots to add to pSrc->a[] */ | |
| 3642 int iStart /* Index in pSrc->a[] of first new slot */ | |
| 3643 ){ | |
| 3644 int i; | |
| 3645 | |
| 3646 /* Sanity checking on calling parameters */ | |
| 3647 assert( iStart>=0 ); | |
| 3648 assert( nExtra>=1 ); | |
| 3649 assert( pSrc!=0 ); | |
| 3650 assert( iStart<=pSrc->nSrc ); | |
| 3651 | |
| 3652 /* Allocate additional space if needed */ | |
| 3653 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ | |
| 3654 SrcList *pNew; | |
| 3655 int nAlloc = pSrc->nSrc+nExtra; | |
| 3656 int nGot; | |
| 3657 pNew = sqlite3DbRealloc(db, pSrc, | |
| 3658 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); | |
| 3659 if( pNew==0 ){ | |
| 3660 assert( db->mallocFailed ); | |
| 3661 return pSrc; | |
| 3662 } | |
| 3663 pSrc = pNew; | |
| 3664 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; | |
| 3665 pSrc->nAlloc = nGot; | |
| 3666 } | |
| 3667 | |
| 3668 /* Move existing slots that come after the newly inserted slots | |
| 3669 ** out of the way */ | |
| 3670 for(i=pSrc->nSrc-1; i>=iStart; i--){ | |
| 3671 pSrc->a[i+nExtra] = pSrc->a[i]; | |
| 3672 } | |
| 3673 pSrc->nSrc += nExtra; | |
| 3674 | |
| 3675 /* Zero the newly allocated slots */ | |
| 3676 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); | |
| 3677 for(i=iStart; i<iStart+nExtra; i++){ | |
| 3678 pSrc->a[i].iCursor = -1; | |
| 3679 } | |
| 3680 | |
| 3681 /* Return a pointer to the enlarged SrcList */ | |
| 3682 return pSrc; | |
| 3683 } | |
| 3684 | |
| 3685 | |
| 3686 /* | |
| 3687 ** Append a new table name to the given SrcList. Create a new SrcList if | |
| 3688 ** need be. A new entry is created in the SrcList even if pTable is NULL. | |
| 3689 ** | |
| 3690 ** A SrcList is returned, or NULL if there is an OOM error. The returned | |
| 3691 ** SrcList might be the same as the SrcList that was input or it might be | |
| 3692 ** a new one. If an OOM error does occurs, then the prior value of pList | |
| 3693 ** that is input to this routine is automatically freed. | |
| 3694 ** | |
| 3695 ** If pDatabase is not null, it means that the table has an optional | |
| 3696 ** database name prefix. Like this: "database.table". The pDatabase | |
| 3697 ** points to the table name and the pTable points to the database name. | |
| 3698 ** The SrcList.a[].zName field is filled with the table name which might | |
| 3699 ** come from pTable (if pDatabase is NULL) or from pDatabase. | |
| 3700 ** SrcList.a[].zDatabase is filled with the database name from pTable, | |
| 3701 ** or with NULL if no database is specified. | |
| 3702 ** | |
| 3703 ** In other words, if call like this: | |
| 3704 ** | |
| 3705 ** sqlite3SrcListAppend(D,A,B,0); | |
| 3706 ** | |
| 3707 ** Then B is a table name and the database name is unspecified. If called | |
| 3708 ** like this: | |
| 3709 ** | |
| 3710 ** sqlite3SrcListAppend(D,A,B,C); | |
| 3711 ** | |
| 3712 ** Then C is the table name and B is the database name. If C is defined | |
| 3713 ** then so is B. In other words, we never have a case where: | |
| 3714 ** | |
| 3715 ** sqlite3SrcListAppend(D,A,0,C); | |
| 3716 ** | |
| 3717 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted | |
| 3718 ** before being added to the SrcList. | |
| 3719 */ | |
| 3720 SrcList *sqlite3SrcListAppend( | |
| 3721 sqlite3 *db, /* Connection to notify of malloc failures */ | |
| 3722 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ | |
| 3723 Token *pTable, /* Table to append */ | |
| 3724 Token *pDatabase /* Database of the table */ | |
| 3725 ){ | |
| 3726 struct SrcList_item *pItem; | |
| 3727 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ | |
| 3728 if( pList==0 ){ | |
| 3729 pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); | |
| 3730 if( pList==0 ) return 0; | |
| 3731 pList->nAlloc = 1; | |
| 3732 } | |
| 3733 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); | |
| 3734 if( db->mallocFailed ){ | |
| 3735 sqlite3SrcListDelete(db, pList); | |
| 3736 return 0; | |
| 3737 } | |
| 3738 pItem = &pList->a[pList->nSrc-1]; | |
| 3739 if( pDatabase && pDatabase->z==0 ){ | |
| 3740 pDatabase = 0; | |
| 3741 } | |
| 3742 if( pDatabase ){ | |
| 3743 Token *pTemp = pDatabase; | |
| 3744 pDatabase = pTable; | |
| 3745 pTable = pTemp; | |
| 3746 } | |
| 3747 pItem->zName = sqlite3NameFromToken(db, pTable); | |
| 3748 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); | |
| 3749 return pList; | |
| 3750 } | |
| 3751 | |
| 3752 /* | |
| 3753 ** Assign VdbeCursor index numbers to all tables in a SrcList | |
| 3754 */ | |
| 3755 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ | |
| 3756 int i; | |
| 3757 struct SrcList_item *pItem; | |
| 3758 assert(pList || pParse->db->mallocFailed ); | |
| 3759 if( pList ){ | |
| 3760 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ | |
| 3761 if( pItem->iCursor>=0 ) break; | |
| 3762 pItem->iCursor = pParse->nTab++; | |
| 3763 if( pItem->pSelect ){ | |
| 3764 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); | |
| 3765 } | |
| 3766 } | |
| 3767 } | |
| 3768 } | |
| 3769 | |
| 3770 /* | |
| 3771 ** Delete an entire SrcList including all its substructure. | |
| 3772 */ | |
| 3773 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ | |
| 3774 int i; | |
| 3775 struct SrcList_item *pItem; | |
| 3776 if( pList==0 ) return; | |
| 3777 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ | |
| 3778 sqlite3DbFree(db, pItem->zDatabase); | |
| 3779 sqlite3DbFree(db, pItem->zName); | |
| 3780 sqlite3DbFree(db, pItem->zAlias); | |
| 3781 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); | |
| 3782 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); | |
| 3783 sqlite3DeleteTable(db, pItem->pTab); | |
| 3784 sqlite3SelectDelete(db, pItem->pSelect); | |
| 3785 sqlite3ExprDelete(db, pItem->pOn); | |
| 3786 sqlite3IdListDelete(db, pItem->pUsing); | |
| 3787 } | |
| 3788 sqlite3DbFree(db, pList); | |
| 3789 } | |
| 3790 | |
| 3791 /* | |
| 3792 ** This routine is called by the parser to add a new term to the | |
| 3793 ** end of a growing FROM clause. The "p" parameter is the part of | |
| 3794 ** the FROM clause that has already been constructed. "p" is NULL | |
| 3795 ** if this is the first term of the FROM clause. pTable and pDatabase | |
| 3796 ** are the name of the table and database named in the FROM clause term. | |
| 3797 ** pDatabase is NULL if the database name qualifier is missing - the | |
| 3798 ** usual case. If the term has an alias, then pAlias points to the | |
| 3799 ** alias token. If the term is a subquery, then pSubquery is the | |
| 3800 ** SELECT statement that the subquery encodes. The pTable and | |
| 3801 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing | |
| 3802 ** parameters are the content of the ON and USING clauses. | |
| 3803 ** | |
| 3804 ** Return a new SrcList which encodes is the FROM with the new | |
| 3805 ** term added. | |
| 3806 */ | |
| 3807 SrcList *sqlite3SrcListAppendFromTerm( | |
| 3808 Parse *pParse, /* Parsing context */ | |
| 3809 SrcList *p, /* The left part of the FROM clause already seen */ | |
| 3810 Token *pTable, /* Name of the table to add to the FROM clause */ | |
| 3811 Token *pDatabase, /* Name of the database containing pTable */ | |
| 3812 Token *pAlias, /* The right-hand side of the AS subexpression */ | |
| 3813 Select *pSubquery, /* A subquery used in place of a table name */ | |
| 3814 Expr *pOn, /* The ON clause of a join */ | |
| 3815 IdList *pUsing /* The USING clause of a join */ | |
| 3816 ){ | |
| 3817 struct SrcList_item *pItem; | |
| 3818 sqlite3 *db = pParse->db; | |
| 3819 if( !p && (pOn || pUsing) ){ | |
| 3820 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", | |
| 3821 (pOn ? "ON" : "USING") | |
| 3822 ); | |
| 3823 goto append_from_error; | |
| 3824 } | |
| 3825 p = sqlite3SrcListAppend(db, p, pTable, pDatabase); | |
| 3826 if( p==0 || NEVER(p->nSrc==0) ){ | |
| 3827 goto append_from_error; | |
| 3828 } | |
| 3829 pItem = &p->a[p->nSrc-1]; | |
| 3830 assert( pAlias!=0 ); | |
| 3831 if( pAlias->n ){ | |
| 3832 pItem->zAlias = sqlite3NameFromToken(db, pAlias); | |
| 3833 } | |
| 3834 pItem->pSelect = pSubquery; | |
| 3835 pItem->pOn = pOn; | |
| 3836 pItem->pUsing = pUsing; | |
| 3837 return p; | |
| 3838 | |
| 3839 append_from_error: | |
| 3840 assert( p==0 ); | |
| 3841 sqlite3ExprDelete(db, pOn); | |
| 3842 sqlite3IdListDelete(db, pUsing); | |
| 3843 sqlite3SelectDelete(db, pSubquery); | |
| 3844 return 0; | |
| 3845 } | |
| 3846 | |
| 3847 /* | |
| 3848 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added | |
| 3849 ** element of the source-list passed as the second argument. | |
| 3850 */ | |
| 3851 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ | |
| 3852 assert( pIndexedBy!=0 ); | |
| 3853 if( p && ALWAYS(p->nSrc>0) ){ | |
| 3854 struct SrcList_item *pItem = &p->a[p->nSrc-1]; | |
| 3855 assert( pItem->fg.notIndexed==0 ); | |
| 3856 assert( pItem->fg.isIndexedBy==0 ); | |
| 3857 assert( pItem->fg.isTabFunc==0 ); | |
| 3858 if( pIndexedBy->n==1 && !pIndexedBy->z ){ | |
| 3859 /* A "NOT INDEXED" clause was supplied. See parse.y | |
| 3860 ** construct "indexed_opt" for details. */ | |
| 3861 pItem->fg.notIndexed = 1; | |
| 3862 }else{ | |
| 3863 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); | |
| 3864 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); | |
| 3865 } | |
| 3866 } | |
| 3867 } | |
| 3868 | |
| 3869 /* | |
| 3870 ** Add the list of function arguments to the SrcList entry for a | |
| 3871 ** table-valued-function. | |
| 3872 */ | |
| 3873 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ | |
| 3874 if( p ){ | |
| 3875 struct SrcList_item *pItem = &p->a[p->nSrc-1]; | |
| 3876 assert( pItem->fg.notIndexed==0 ); | |
| 3877 assert( pItem->fg.isIndexedBy==0 ); | |
| 3878 assert( pItem->fg.isTabFunc==0 ); | |
| 3879 pItem->u1.pFuncArg = pList; | |
| 3880 pItem->fg.isTabFunc = 1; | |
| 3881 }else{ | |
| 3882 sqlite3ExprListDelete(pParse->db, pList); | |
| 3883 } | |
| 3884 } | |
| 3885 | |
| 3886 /* | |
| 3887 ** When building up a FROM clause in the parser, the join operator | |
| 3888 ** is initially attached to the left operand. But the code generator | |
| 3889 ** expects the join operator to be on the right operand. This routine | |
| 3890 ** Shifts all join operators from left to right for an entire FROM | |
| 3891 ** clause. | |
| 3892 ** | |
| 3893 ** Example: Suppose the join is like this: | |
| 3894 ** | |
| 3895 ** A natural cross join B | |
| 3896 ** | |
| 3897 ** The operator is "natural cross join". The A and B operands are stored | |
| 3898 ** in p->a[0] and p->a[1], respectively. The parser initially stores the | |
| 3899 ** operator with A. This routine shifts that operator over to B. | |
| 3900 */ | |
| 3901 void sqlite3SrcListShiftJoinType(SrcList *p){ | |
| 3902 if( p ){ | |
| 3903 int i; | |
| 3904 for(i=p->nSrc-1; i>0; i--){ | |
| 3905 p->a[i].fg.jointype = p->a[i-1].fg.jointype; | |
| 3906 } | |
| 3907 p->a[0].fg.jointype = 0; | |
| 3908 } | |
| 3909 } | |
| 3910 | |
| 3911 /* | |
| 3912 ** Begin a transaction | |
| 3913 */ | |
| 3914 void sqlite3BeginTransaction(Parse *pParse, int type){ | |
| 3915 sqlite3 *db; | |
| 3916 Vdbe *v; | |
| 3917 int i; | |
| 3918 | |
| 3919 assert( pParse!=0 ); | |
| 3920 db = pParse->db; | |
| 3921 assert( db!=0 ); | |
| 3922 /* if( db->aDb[0].pBt==0 ) return; */ | |
| 3923 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ | |
| 3924 return; | |
| 3925 } | |
| 3926 v = sqlite3GetVdbe(pParse); | |
| 3927 if( !v ) return; | |
| 3928 if( type!=TK_DEFERRED ){ | |
| 3929 for(i=0; i<db->nDb; i++){ | |
| 3930 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); | |
| 3931 sqlite3VdbeUsesBtree(v, i); | |
| 3932 } | |
| 3933 } | |
| 3934 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); | |
| 3935 } | |
| 3936 | |
| 3937 /* | |
| 3938 ** Commit a transaction | |
| 3939 */ | |
| 3940 void sqlite3CommitTransaction(Parse *pParse){ | |
| 3941 Vdbe *v; | |
| 3942 | |
| 3943 assert( pParse!=0 ); | |
| 3944 assert( pParse->db!=0 ); | |
| 3945 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ | |
| 3946 return; | |
| 3947 } | |
| 3948 v = sqlite3GetVdbe(pParse); | |
| 3949 if( v ){ | |
| 3950 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); | |
| 3951 } | |
| 3952 } | |
| 3953 | |
| 3954 /* | |
| 3955 ** Rollback a transaction | |
| 3956 */ | |
| 3957 void sqlite3RollbackTransaction(Parse *pParse){ | |
| 3958 Vdbe *v; | |
| 3959 | |
| 3960 assert( pParse!=0 ); | |
| 3961 assert( pParse->db!=0 ); | |
| 3962 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ | |
| 3963 return; | |
| 3964 } | |
| 3965 v = sqlite3GetVdbe(pParse); | |
| 3966 if( v ){ | |
| 3967 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); | |
| 3968 } | |
| 3969 } | |
| 3970 | |
| 3971 /* | |
| 3972 ** This function is called by the parser when it parses a command to create, | |
| 3973 ** release or rollback an SQL savepoint. | |
| 3974 */ | |
| 3975 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ | |
| 3976 char *zName = sqlite3NameFromToken(pParse->db, pName); | |
| 3977 if( zName ){ | |
| 3978 Vdbe *v = sqlite3GetVdbe(pParse); | |
| 3979 #ifndef SQLITE_OMIT_AUTHORIZATION | |
| 3980 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; | |
| 3981 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); | |
| 3982 #endif | |
| 3983 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ | |
| 3984 sqlite3DbFree(pParse->db, zName); | |
| 3985 return; | |
| 3986 } | |
| 3987 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); | |
| 3988 } | |
| 3989 } | |
| 3990 | |
| 3991 /* | |
| 3992 ** Make sure the TEMP database is open and available for use. Return | |
| 3993 ** the number of errors. Leave any error messages in the pParse structure. | |
| 3994 */ | |
| 3995 int sqlite3OpenTempDatabase(Parse *pParse){ | |
| 3996 sqlite3 *db = pParse->db; | |
| 3997 if( db->aDb[1].pBt==0 && !pParse->explain ){ | |
| 3998 int rc; | |
| 3999 Btree *pBt; | |
| 4000 static const int flags = | |
| 4001 SQLITE_OPEN_READWRITE | | |
| 4002 SQLITE_OPEN_CREATE | | |
| 4003 SQLITE_OPEN_EXCLUSIVE | | |
| 4004 SQLITE_OPEN_DELETEONCLOSE | | |
| 4005 SQLITE_OPEN_TEMP_DB; | |
| 4006 | |
| 4007 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); | |
| 4008 if( rc!=SQLITE_OK ){ | |
| 4009 sqlite3ErrorMsg(pParse, "unable to open a temporary database " | |
| 4010 "file for storing temporary tables"); | |
| 4011 pParse->rc = rc; | |
| 4012 return 1; | |
| 4013 } | |
| 4014 db->aDb[1].pBt = pBt; | |
| 4015 assert( db->aDb[1].pSchema ); | |
| 4016 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ | |
| 4017 db->mallocFailed = 1; | |
| 4018 return 1; | |
| 4019 } | |
| 4020 } | |
| 4021 return 0; | |
| 4022 } | |
| 4023 | |
| 4024 /* | |
| 4025 ** Record the fact that the schema cookie will need to be verified | |
| 4026 ** for database iDb. The code to actually verify the schema cookie | |
| 4027 ** will occur at the end of the top-level VDBE and will be generated | |
| 4028 ** later, by sqlite3FinishCoding(). | |
| 4029 */ | |
| 4030 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ | |
| 4031 Parse *pToplevel = sqlite3ParseToplevel(pParse); | |
| 4032 sqlite3 *db = pToplevel->db; | |
| 4033 | |
| 4034 assert( iDb>=0 && iDb<db->nDb ); | |
| 4035 assert( db->aDb[iDb].pBt!=0 || iDb==1 ); | |
| 4036 assert( iDb<SQLITE_MAX_ATTACHED+2 ); | |
| 4037 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); | |
| 4038 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ | |
| 4039 DbMaskSet(pToplevel->cookieMask, iDb); | |
| 4040 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; | |
| 4041 if( !OMIT_TEMPDB && iDb==1 ){ | |
| 4042 sqlite3OpenTempDatabase(pToplevel); | |
| 4043 } | |
| 4044 } | |
| 4045 } | |
| 4046 | |
| 4047 /* | |
| 4048 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each | |
| 4049 ** attached database. Otherwise, invoke it for the database named zDb only. | |
| 4050 */ | |
| 4051 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ | |
| 4052 sqlite3 *db = pParse->db; | |
| 4053 int i; | |
| 4054 for(i=0; i<db->nDb; i++){ | |
| 4055 Db *pDb = &db->aDb[i]; | |
| 4056 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){ | |
| 4057 sqlite3CodeVerifySchema(pParse, i); | |
| 4058 } | |
| 4059 } | |
| 4060 } | |
| 4061 | |
| 4062 /* | |
| 4063 ** Generate VDBE code that prepares for doing an operation that | |
| 4064 ** might change the database. | |
| 4065 ** | |
| 4066 ** This routine starts a new transaction if we are not already within | |
| 4067 ** a transaction. If we are already within a transaction, then a checkpoint | |
| 4068 ** is set if the setStatement parameter is true. A checkpoint should | |
| 4069 ** be set for operations that might fail (due to a constraint) part of | |
| 4070 ** the way through and which will need to undo some writes without having to | |
| 4071 ** rollback the whole transaction. For operations where all constraints | |
| 4072 ** can be checked before any changes are made to the database, it is never | |
| 4073 ** necessary to undo a write and the checkpoint should not be set. | |
| 4074 */ | |
| 4075 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ | |
| 4076 Parse *pToplevel = sqlite3ParseToplevel(pParse); | |
| 4077 sqlite3CodeVerifySchema(pParse, iDb); | |
| 4078 DbMaskSet(pToplevel->writeMask, iDb); | |
| 4079 pToplevel->isMultiWrite |= setStatement; | |
| 4080 } | |
| 4081 | |
| 4082 /* | |
| 4083 ** Indicate that the statement currently under construction might write | |
| 4084 ** more than one entry (example: deleting one row then inserting another, | |
| 4085 ** inserting multiple rows in a table, or inserting a row and index entries.) | |
| 4086 ** If an abort occurs after some of these writes have completed, then it will | |
| 4087 ** be necessary to undo the completed writes. | |
| 4088 */ | |
| 4089 void sqlite3MultiWrite(Parse *pParse){ | |
| 4090 Parse *pToplevel = sqlite3ParseToplevel(pParse); | |
| 4091 pToplevel->isMultiWrite = 1; | |
| 4092 } | |
| 4093 | |
| 4094 /* | |
| 4095 ** The code generator calls this routine if is discovers that it is | |
| 4096 ** possible to abort a statement prior to completion. In order to | |
| 4097 ** perform this abort without corrupting the database, we need to make | |
| 4098 ** sure that the statement is protected by a statement transaction. | |
| 4099 ** | |
| 4100 ** Technically, we only need to set the mayAbort flag if the | |
| 4101 ** isMultiWrite flag was previously set. There is a time dependency | |
| 4102 ** such that the abort must occur after the multiwrite. This makes | |
| 4103 ** some statements involving the REPLACE conflict resolution algorithm | |
| 4104 ** go a little faster. But taking advantage of this time dependency | |
| 4105 ** makes it more difficult to prove that the code is correct (in | |
| 4106 ** particular, it prevents us from writing an effective | |
| 4107 ** implementation of sqlite3AssertMayAbort()) and so we have chosen | |
| 4108 ** to take the safe route and skip the optimization. | |
| 4109 */ | |
| 4110 void sqlite3MayAbort(Parse *pParse){ | |
| 4111 Parse *pToplevel = sqlite3ParseToplevel(pParse); | |
| 4112 pToplevel->mayAbort = 1; | |
| 4113 } | |
| 4114 | |
| 4115 /* | |
| 4116 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT | |
| 4117 ** error. The onError parameter determines which (if any) of the statement | |
| 4118 ** and/or current transaction is rolled back. | |
| 4119 */ | |
| 4120 void sqlite3HaltConstraint( | |
| 4121 Parse *pParse, /* Parsing context */ | |
| 4122 int errCode, /* extended error code */ | |
| 4123 int onError, /* Constraint type */ | |
| 4124 char *p4, /* Error message */ | |
| 4125 i8 p4type, /* P4_STATIC or P4_TRANSIENT */ | |
| 4126 u8 p5Errmsg /* P5_ErrMsg type */ | |
| 4127 ){ | |
| 4128 Vdbe *v = sqlite3GetVdbe(pParse); | |
| 4129 assert( (errCode&0xff)==SQLITE_CONSTRAINT ); | |
| 4130 if( onError==OE_Abort ){ | |
| 4131 sqlite3MayAbort(pParse); | |
| 4132 } | |
| 4133 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); | |
| 4134 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg); | |
| 4135 } | |
| 4136 | |
| 4137 /* | |
| 4138 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. | |
| 4139 */ | |
| 4140 void sqlite3UniqueConstraint( | |
| 4141 Parse *pParse, /* Parsing context */ | |
| 4142 int onError, /* Constraint type */ | |
| 4143 Index *pIdx /* The index that triggers the constraint */ | |
| 4144 ){ | |
| 4145 char *zErr; | |
| 4146 int j; | |
| 4147 StrAccum errMsg; | |
| 4148 Table *pTab = pIdx->pTable; | |
| 4149 | |
| 4150 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); | |
| 4151 if( pIdx->aColExpr ){ | |
| 4152 sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName); | |
| 4153 }else{ | |
| 4154 for(j=0; j<pIdx->nKeyCol; j++){ | |
| 4155 char *zCol; | |
| 4156 assert( pIdx->aiColumn[j]>=0 ); | |
| 4157 zCol = pTab->aCol[pIdx->aiColumn[j]].zName; | |
| 4158 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); | |
| 4159 sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol); | |
| 4160 } | |
| 4161 } | |
| 4162 zErr = sqlite3StrAccumFinish(&errMsg); | |
| 4163 sqlite3HaltConstraint(pParse, | |
| 4164 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY | |
| 4165 : SQLITE_CONSTRAINT_UNIQUE, | |
| 4166 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); | |
| 4167 } | |
| 4168 | |
| 4169 | |
| 4170 /* | |
| 4171 ** Code an OP_Halt due to non-unique rowid. | |
| 4172 */ | |
| 4173 void sqlite3RowidConstraint( | |
| 4174 Parse *pParse, /* Parsing context */ | |
| 4175 int onError, /* Conflict resolution algorithm */ | |
| 4176 Table *pTab /* The table with the non-unique rowid */ | |
| 4177 ){ | |
| 4178 char *zMsg; | |
| 4179 int rc; | |
| 4180 if( pTab->iPKey>=0 ){ | |
| 4181 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, | |
| 4182 pTab->aCol[pTab->iPKey].zName); | |
| 4183 rc = SQLITE_CONSTRAINT_PRIMARYKEY; | |
| 4184 }else{ | |
| 4185 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); | |
| 4186 rc = SQLITE_CONSTRAINT_ROWID; | |
| 4187 } | |
| 4188 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, | |
| 4189 P5_ConstraintUnique); | |
| 4190 } | |
| 4191 | |
| 4192 /* | |
| 4193 ** Check to see if pIndex uses the collating sequence pColl. Return | |
| 4194 ** true if it does and false if it does not. | |
| 4195 */ | |
| 4196 #ifndef SQLITE_OMIT_REINDEX | |
| 4197 static int collationMatch(const char *zColl, Index *pIndex){ | |
| 4198 int i; | |
| 4199 assert( zColl!=0 ); | |
| 4200 for(i=0; i<pIndex->nColumn; i++){ | |
| 4201 const char *z = pIndex->azColl[i]; | |
| 4202 assert( z!=0 || pIndex->aiColumn[i]<0 ); | |
| 4203 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ | |
| 4204 return 1; | |
| 4205 } | |
| 4206 } | |
| 4207 return 0; | |
| 4208 } | |
| 4209 #endif | |
| 4210 | |
| 4211 /* | |
| 4212 ** Recompute all indices of pTab that use the collating sequence pColl. | |
| 4213 ** If pColl==0 then recompute all indices of pTab. | |
| 4214 */ | |
| 4215 #ifndef SQLITE_OMIT_REINDEX | |
| 4216 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ | |
| 4217 Index *pIndex; /* An index associated with pTab */ | |
| 4218 | |
| 4219 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ | |
| 4220 if( zColl==0 || collationMatch(zColl, pIndex) ){ | |
| 4221 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); | |
| 4222 sqlite3BeginWriteOperation(pParse, 0, iDb); | |
| 4223 sqlite3RefillIndex(pParse, pIndex, -1); | |
| 4224 } | |
| 4225 } | |
| 4226 } | |
| 4227 #endif | |
| 4228 | |
| 4229 /* | |
| 4230 ** Recompute all indices of all tables in all databases where the | |
| 4231 ** indices use the collating sequence pColl. If pColl==0 then recompute | |
| 4232 ** all indices everywhere. | |
| 4233 */ | |
| 4234 #ifndef SQLITE_OMIT_REINDEX | |
| 4235 static void reindexDatabases(Parse *pParse, char const *zColl){ | |
| 4236 Db *pDb; /* A single database */ | |
| 4237 int iDb; /* The database index number */ | |
| 4238 sqlite3 *db = pParse->db; /* The database connection */ | |
| 4239 HashElem *k; /* For looping over tables in pDb */ | |
| 4240 Table *pTab; /* A table in the database */ | |
| 4241 | |
| 4242 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ | |
| 4243 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ | |
| 4244 assert( pDb!=0 ); | |
| 4245 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ | |
| 4246 pTab = (Table*)sqliteHashData(k); | |
| 4247 reindexTable(pParse, pTab, zColl); | |
| 4248 } | |
| 4249 } | |
| 4250 } | |
| 4251 #endif | |
| 4252 | |
| 4253 /* | |
| 4254 ** Generate code for the REINDEX command. | |
| 4255 ** | |
| 4256 ** REINDEX -- 1 | |
| 4257 ** REINDEX <collation> -- 2 | |
| 4258 ** REINDEX ?<database>.?<tablename> -- 3 | |
| 4259 ** REINDEX ?<database>.?<indexname> -- 4 | |
| 4260 ** | |
| 4261 ** Form 1 causes all indices in all attached databases to be rebuilt. | |
| 4262 ** Form 2 rebuilds all indices in all databases that use the named | |
| 4263 ** collating function. Forms 3 and 4 rebuild the named index or all | |
| 4264 ** indices associated with the named table. | |
| 4265 */ | |
| 4266 #ifndef SQLITE_OMIT_REINDEX | |
| 4267 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ | |
| 4268 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ | |
| 4269 char *z; /* Name of a table or index */ | |
| 4270 const char *zDb; /* Name of the database */ | |
| 4271 Table *pTab; /* A table in the database */ | |
| 4272 Index *pIndex; /* An index associated with pTab */ | |
| 4273 int iDb; /* The database index number */ | |
| 4274 sqlite3 *db = pParse->db; /* The database connection */ | |
| 4275 Token *pObjName; /* Name of the table or index to be reindexed */ | |
| 4276 | |
| 4277 /* Read the database schema. If an error occurs, leave an error message | |
| 4278 ** and code in pParse and return NULL. */ | |
| 4279 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ | |
| 4280 return; | |
| 4281 } | |
| 4282 | |
| 4283 if( pName1==0 ){ | |
| 4284 reindexDatabases(pParse, 0); | |
| 4285 return; | |
| 4286 }else if( NEVER(pName2==0) || pName2->z==0 ){ | |
| 4287 char *zColl; | |
| 4288 assert( pName1->z ); | |
| 4289 zColl = sqlite3NameFromToken(pParse->db, pName1); | |
| 4290 if( !zColl ) return; | |
| 4291 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); | |
| 4292 if( pColl ){ | |
| 4293 reindexDatabases(pParse, zColl); | |
| 4294 sqlite3DbFree(db, zColl); | |
| 4295 return; | |
| 4296 } | |
| 4297 sqlite3DbFree(db, zColl); | |
| 4298 } | |
| 4299 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); | |
| 4300 if( iDb<0 ) return; | |
| 4301 z = sqlite3NameFromToken(db, pObjName); | |
| 4302 if( z==0 ) return; | |
| 4303 zDb = db->aDb[iDb].zName; | |
| 4304 pTab = sqlite3FindTable(db, z, zDb); | |
| 4305 if( pTab ){ | |
| 4306 reindexTable(pParse, pTab, 0); | |
| 4307 sqlite3DbFree(db, z); | |
| 4308 return; | |
| 4309 } | |
| 4310 pIndex = sqlite3FindIndex(db, z, zDb); | |
| 4311 sqlite3DbFree(db, z); | |
| 4312 if( pIndex ){ | |
| 4313 sqlite3BeginWriteOperation(pParse, 0, iDb); | |
| 4314 sqlite3RefillIndex(pParse, pIndex, -1); | |
| 4315 return; | |
| 4316 } | |
| 4317 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); | |
| 4318 } | |
| 4319 #endif | |
| 4320 | |
| 4321 /* | |
| 4322 ** Return a KeyInfo structure that is appropriate for the given Index. | |
| 4323 ** | |
| 4324 ** The KeyInfo structure for an index is cached in the Index object. | |
| 4325 ** So there might be multiple references to the returned pointer. The | |
| 4326 ** caller should not try to modify the KeyInfo object. | |
| 4327 ** | |
| 4328 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object | |
| 4329 ** when it has finished using it. | |
| 4330 */ | |
| 4331 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ | |
| 4332 int i; | |
| 4333 int nCol = pIdx->nColumn; | |
| 4334 int nKey = pIdx->nKeyCol; | |
| 4335 KeyInfo *pKey; | |
| 4336 if( pParse->nErr ) return 0; | |
| 4337 if( pIdx->uniqNotNull ){ | |
| 4338 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); | |
| 4339 }else{ | |
| 4340 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); | |
| 4341 } | |
| 4342 if( pKey ){ | |
| 4343 assert( sqlite3KeyInfoIsWriteable(pKey) ); | |
| 4344 for(i=0; i<nCol; i++){ | |
| 4345 const char *zColl = pIdx->azColl[i]; | |
| 4346 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : | |
| 4347 sqlite3LocateCollSeq(pParse, zColl); | |
| 4348 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; | |
| 4349 } | |
| 4350 if( pParse->nErr ){ | |
| 4351 sqlite3KeyInfoUnref(pKey); | |
| 4352 pKey = 0; | |
| 4353 } | |
| 4354 } | |
| 4355 return pKey; | |
| 4356 } | |
| 4357 | |
| 4358 #ifndef SQLITE_OMIT_CTE | |
| 4359 /* | |
| 4360 ** This routine is invoked once per CTE by the parser while parsing a | |
| 4361 ** WITH clause. | |
| 4362 */ | |
| 4363 With *sqlite3WithAdd( | |
| 4364 Parse *pParse, /* Parsing context */ | |
| 4365 With *pWith, /* Existing WITH clause, or NULL */ | |
| 4366 Token *pName, /* Name of the common-table */ | |
| 4367 ExprList *pArglist, /* Optional column name list for the table */ | |
| 4368 Select *pQuery /* Query used to initialize the table */ | |
| 4369 ){ | |
| 4370 sqlite3 *db = pParse->db; | |
| 4371 With *pNew; | |
| 4372 char *zName; | |
| 4373 | |
| 4374 /* Check that the CTE name is unique within this WITH clause. If | |
| 4375 ** not, store an error in the Parse structure. */ | |
| 4376 zName = sqlite3NameFromToken(pParse->db, pName); | |
| 4377 if( zName && pWith ){ | |
| 4378 int i; | |
| 4379 for(i=0; i<pWith->nCte; i++){ | |
| 4380 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ | |
| 4381 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); | |
| 4382 } | |
| 4383 } | |
| 4384 } | |
| 4385 | |
| 4386 if( pWith ){ | |
| 4387 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); | |
| 4388 pNew = sqlite3DbRealloc(db, pWith, nByte); | |
| 4389 }else{ | |
| 4390 pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); | |
| 4391 } | |
| 4392 assert( zName!=0 || pNew==0 ); | |
| 4393 assert( db->mallocFailed==0 || pNew==0 ); | |
| 4394 | |
| 4395 if( pNew==0 ){ | |
| 4396 sqlite3ExprListDelete(db, pArglist); | |
| 4397 sqlite3SelectDelete(db, pQuery); | |
| 4398 sqlite3DbFree(db, zName); | |
| 4399 pNew = pWith; | |
| 4400 }else{ | |
| 4401 pNew->a[pNew->nCte].pSelect = pQuery; | |
| 4402 pNew->a[pNew->nCte].pCols = pArglist; | |
| 4403 pNew->a[pNew->nCte].zName = zName; | |
| 4404 pNew->a[pNew->nCte].zCteErr = 0; | |
| 4405 pNew->nCte++; | |
| 4406 } | |
| 4407 | |
| 4408 return pNew; | |
| 4409 } | |
| 4410 | |
| 4411 /* | |
| 4412 ** Free the contents of the With object passed as the second argument. | |
| 4413 */ | |
| 4414 void sqlite3WithDelete(sqlite3 *db, With *pWith){ | |
| 4415 if( pWith ){ | |
| 4416 int i; | |
| 4417 for(i=0; i<pWith->nCte; i++){ | |
| 4418 struct Cte *pCte = &pWith->a[i]; | |
| 4419 sqlite3ExprListDelete(db, pCte->pCols); | |
| 4420 sqlite3SelectDelete(db, pCte->pSelect); | |
| 4421 sqlite3DbFree(db, pCte->zName); | |
| 4422 } | |
| 4423 sqlite3DbFree(db, pWith); | |
| 4424 } | |
| 4425 } | |
| 4426 #endif /* !defined(SQLITE_OMIT_CTE) */ | |
| OLD | NEW |