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 ** $Id: build.c,v 1.480 2008/04/11 17:11:27 danielk1977 Exp $ 26 */ 27 #include "sqliteInt.h" 28 #include <ctype.h> 29 30 /* 31 ** This routine is called when a new SQL statement is beginning to 32 ** be parsed. Initialize the pParse structure as needed. 33 */ 34 void sqlite3BeginParse(Parse *pParse, int explainFlag){ 35 pParse->explain = explainFlag; 36 pParse->nVar = 0; 37 } 38 39 #ifndef SQLITE_OMIT_SHARED_CACHE 40 /* 41 ** The TableLock structure is only used by the sqlite3TableLock() and 42 ** codeTableLocks() functions. 43 */ 44 struct TableLock { 45 int iDb; /* The database containing the table to be locked */ 46 int iTab; /* The root page of the table to be locked */ 47 u8 isWriteLock; /* True for write lock. False for a read lock */ 48 const char *zName; /* Name of the table */ 49 }; 50 51 /* 52 ** Record the fact that we want to lock a table at run-time. 53 ** 54 ** The table to be locked has root page iTab and is found in database iDb. 55 ** A read or a write lock can be taken depending on isWritelock. 56 ** 57 ** This routine just records the fact that the lock is desired. The 58 ** code to make the lock occur is generated by a later call to 59 ** codeTableLocks() which occurs during sqlite3FinishCoding(). 60 */ 61 void sqlite3TableLock( 62 Parse *pParse, /* Parsing context */ 63 int iDb, /* Index of the database containing the table to lock */ 64 int iTab, /* Root page number of the table to be locked */ 65 u8 isWriteLock, /* True for a write lock */ 66 const char *zName /* Name of the table to be locked */ 67 ){ 68 int i; 69 int nBytes; 70 TableLock *p; 71 72 if( iDb<0 ){ 73 return; 74 } 75 76 for(i=0; i<pParse->nTableLock; i++){ 77 p = &pParse->aTableLock[i]; 78 if( p->iDb==iDb && p->iTab==iTab ){ 79 p->isWriteLock = (p->isWriteLock || isWriteLock); 80 return; 81 } 82 } 83 84 nBytes = sizeof(TableLock) * (pParse->nTableLock+1); 85 pParse->aTableLock = 86 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes); 87 if( pParse->aTableLock ){ 88 p = &pParse->aTableLock[pParse->nTableLock++]; 89 p->iDb = iDb; 90 p->iTab = iTab; 91 p->isWriteLock = isWriteLock; 92 p->zName = zName; 93 }else{ 94 pParse->nTableLock = 0; 95 pParse->db->mallocFailed = 1; 96 } 97 } 98 99 /* 100 ** Code an OP_TableLock instruction for each table locked by the 101 ** statement (configured by calls to sqlite3TableLock()). 102 */ 103 static void codeTableLocks(Parse *pParse){ 104 int i; 105 Vdbe *pVdbe; 106 107 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){ 108 return; 109 } 110 111 for(i=0; i<pParse->nTableLock; i++){ 112 TableLock *p = &pParse->aTableLock[i]; 113 int p1 = p->iDb; 114 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 115 p->zName, P4_STATIC); 116 } 117 } 118 #else 119 #define codeTableLocks(x) 120 #endif 121 122 /* 123 ** This routine is called after a single SQL statement has been 124 ** parsed and a VDBE program to execute that statement has been 125 ** prepared. This routine puts the finishing touches on the 126 ** VDBE program and resets the pParse structure for the next 127 ** parse. 128 ** 129 ** Note that if an error occurred, it might be the case that 130 ** no VDBE code was generated. 131 */ 132 void sqlite3FinishCoding(Parse *pParse){ 133 sqlite3 *db; 134 Vdbe *v; 135 136 db = pParse->db; 137 if( db->mallocFailed ) return; 138 if( pParse->nested ) return; 139 if( pParse->nErr ) return; 140 if( !pParse->pVdbe ){ 141 if( pParse->rc==SQLITE_OK && pParse->nErr ){ 142 pParse->rc = SQLITE_ERROR; 143 return; 144 } 145 } 146 147 /* Begin by generating some termination code at the end of the 148 ** vdbe program 149 */ 150 v = sqlite3GetVdbe(pParse); 151 if( v ){ 152 sqlite3VdbeAddOp0(v, OP_Halt); 153 154 /* The cookie mask contains one bit for each database file open. 155 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 156 ** set for each database that is used. Generate code to start a 157 ** transaction on each used database and to verify the schema cookie 158 ** on each used database. 159 */ 160 if( pParse->cookieGoto>0 ){ 161 u32 mask; 162 int iDb; 163 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); 164 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){ 165 if( (mask & pParse->cookieMask)==0 ) continue; 166 sqlite3VdbeUsesBtree(v, iDb); 167 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); 168 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); 169 } 170 #ifndef SQLITE_OMIT_VIRTUALTABLE 171 if( pParse->pVirtualLock ){ 172 char *vtab = (char *)pParse->pVirtualLock->pVtab; 173 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 174 } 175 #endif 176 177 /* Once all the cookies have been verified and transactions opened, 178 ** obtain the required table-locks. This is a no-op unless the 179 ** shared-cache feature is enabled. 180 */ 181 codeTableLocks(pParse); 182 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); 183 } 184 185 #ifndef SQLITE_OMIT_TRACE 186 if( !db->init.busy ){ 187 /* Change the P4 argument of the first opcode (which will always be 188 ** an OP_Trace) to be the complete text of the current SQL statement. 189 */ 190 VdbeOp *pOp = sqlite3VdbeGetOp(v, 0); 191 if( pOp && pOp->opcode==OP_Trace ){ 192 sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql); 193 } 194 } 195 #endif /* SQLITE_OMIT_TRACE */ 196 } 197 198 199 /* Get the VDBE program ready for execution 200 */ 201 if( v && pParse->nErr==0 && !db->mallocFailed ){ 202 #ifdef SQLITE_DEBUG 203 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; 204 sqlite3VdbeTrace(v, trace); 205 #endif 206 assert( pParse->disableColCache==0 ); /* Disables and re-enables match */ 207 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3, 208 pParse->nTab+3, pParse->explain); 209 pParse->rc = SQLITE_DONE; 210 pParse->colNamesSet = 0; 211 }else if( pParse->rc==SQLITE_OK ){ 212 pParse->rc = SQLITE_ERROR; 213 } 214 pParse->nTab = 0; 215 pParse->nMem = 0; 216 pParse->nSet = 0; 217 pParse->nVar = 0; 218 pParse->cookieMask = 0; 219 pParse->cookieGoto = 0; 220 } 221 222 /* 223 ** Run the parser and code generator recursively in order to generate 224 ** code for the SQL statement given onto the end of the pParse context 225 ** currently under construction. When the parser is run recursively 226 ** this way, the final OP_Halt is not appended and other initialization 227 ** and finalization steps are omitted because those are handling by the 228 ** outermost parser. 229 ** 230 ** Not everything is nestable. This facility is designed to permit 231 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use 232 ** care if you decide to try to use this routine for some other purposes. 233 */ 234 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 235 va_list ap; 236 char *zSql; 237 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) 238 char saveBuf[SAVE_SZ]; 239 240 if( pParse->nErr ) return; 241 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 242 va_start(ap, zFormat); 243 zSql = sqlite3VMPrintf(pParse->db, zFormat, ap); 244 va_end(ap); 245 if( zSql==0 ){ 246 pParse->db->mallocFailed = 1; 247 return; /* A malloc must have failed */ 248 } 249 pParse->nested++; 250 memcpy(saveBuf, &pParse->nVar, SAVE_SZ); 251 memset(&pParse->nVar, 0, SAVE_SZ); 252 sqlite3RunParser(pParse, zSql, 0); 253 sqlite3_free(zSql); 254 memcpy(&pParse->nVar, saveBuf, SAVE_SZ); 255 pParse->nested--; 256 } 257 258 /* 259 ** Locate the in-memory structure that describes a particular database 260 ** table given the name of that table and (optionally) the name of the 261 ** database containing the table. Return NULL if not found. 262 ** 263 ** If zDatabase is 0, all databases are searched for the table and the 264 ** first matching table is returned. (No checking for duplicate table 265 ** names is done.) The search order is TEMP first, then MAIN, then any 266 ** auxiliary databases added using the ATTACH command. 267 ** 268 ** See also sqlite3LocateTable(). 269 */ 270 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 271 Table *p = 0; 272 int i; 273 assert( zName!=0 ); 274 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 275 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 276 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; 277 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1); 278 if( p ) break; 279 } 280 return p; 281 } 282 283 /* 284 ** Locate the in-memory structure that describes a particular database 285 ** table given the name of that table and (optionally) the name of the 286 ** database containing the table. Return NULL if not found. Also leave an 287 ** error message in pParse->zErrMsg. 288 ** 289 ** The difference between this routine and sqlite3FindTable() is that this 290 ** routine leaves an error message in pParse->zErrMsg where 291 ** sqlite3FindTable() does not. 292 */ 293 Table *sqlite3LocateTable( 294 Parse *pParse, /* context in which to report errors */ 295 int isView, /* True if looking for a VIEW rather than a TABLE */ 296 const char *zName, /* Name of the table we are looking for */ 297 const char *zDbase /* Name of the database. Might be NULL */ 298 ){ 299 Table *p; 300 301 /* Read the database schema. If an error occurs, leave an error message 302 ** and code in pParse and return NULL. */ 303 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 304 return 0; 305 } 306 307 p = sqlite3FindTable(pParse->db, zName, zDbase); 308 if( p==0 ){ 309 const char *zMsg = isView ? "no such view" : "no such table"; 310 if( zDbase ){ 311 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 312 }else{ 313 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 314 } 315 pParse->checkSchema = 1; 316 } 317 return p; 318 } 319 320 /* 321 ** Locate the in-memory structure that describes 322 ** a particular index given the name of that index 323 ** and the name of the database that contains the index. 324 ** Return NULL if not found. 325 ** 326 ** If zDatabase is 0, all databases are searched for the 327 ** table and the first matching index is returned. (No checking 328 ** for duplicate index names is done.) The search order is 329 ** TEMP first, then MAIN, then any auxiliary databases added 330 ** using the ATTACH command. 331 */ 332 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 333 Index *p = 0; 334 int i; 335 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 336 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 337 Schema *pSchema = db->aDb[j].pSchema; 338 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; 339 assert( pSchema || (j==1 && !db->aDb[1].pBt) ); 340 if( pSchema ){ 341 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1); 342 } 343 if( p ) break; 344 } 345 return p; 346 } 347 348 /* 349 ** Reclaim the memory used by an index 350 */ 351 static void freeIndex(Index *p){ 352 sqlite3_free(p->zColAff); 353 sqlite3_free(p); 354 } 355 356 /* 357 ** Remove the given index from the index hash table, and free 358 ** its memory structures. 359 ** 360 ** The index is removed from the database hash tables but 361 ** it is not unlinked from the Table that it indexes. 362 ** Unlinking from the Table must be done by the calling function. 363 */ 364 static void sqliteDeleteIndex(Index *p){ 365 Index *pOld; 366 const char *zName = p->zName; 367 368 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0); 369 assert( pOld==0 || pOld==p ); 370 freeIndex(p); 371 } 372 373 /* 374 ** For the index called zIdxName which is found in the database iDb, 375 ** unlike that index from its Table then remove the index from 376 ** the index hash table and free all memory structures associated 377 ** with the index. 378 */ 379 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 380 Index *pIndex; 381 int len; 382 Hash *pHash = &db->aDb[iDb].pSchema->idxHash; 383 384 len = strlen(zIdxName); 385 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0); 386 if( pIndex ){ 387 if( pIndex->pTable->pIndex==pIndex ){ 388 pIndex->pTable->pIndex = pIndex->pNext; 389 }else{ 390 Index *p; 391 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){} 392 if( p && p->pNext==pIndex ){ 393 p->pNext = pIndex->pNext; 394 } 395 } 396 freeIndex(pIndex); 397 } 398 db->flags |= SQLITE_InternChanges; 399 } 400 401 /* 402 ** Erase all schema information from the in-memory hash tables of 403 ** a single database. This routine is called to reclaim memory 404 ** before the database closes. It is also called during a rollback 405 ** if there were schema changes during the transaction or if a 406 ** schema-cookie mismatch occurs. 407 ** 408 ** If iDb<=0 then reset the internal schema tables for all database 409 ** files. If iDb>=2 then reset the internal schema for only the 410 ** single file indicated. 411 */ 412 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ 413 int i, j; 414 assert( iDb>=0 && iDb<db->nDb ); 415 416 if( iDb==0 ){ 417 sqlite3BtreeEnterAll(db); 418 } 419 for(i=iDb; i<db->nDb; i++){ 420 Db *pDb = &db->aDb[i]; 421 if( pDb->pSchema ){ 422 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt))); 423 sqlite3SchemaFree(pDb->pSchema); 424 } 425 if( iDb>0 ) return; 426 } 427 assert( iDb==0 ); 428 db->flags &= ~SQLITE_InternChanges; 429 sqlite3BtreeLeaveAll(db); 430 431 /* If one or more of the auxiliary database files has been closed, 432 ** then remove them from the auxiliary database list. We take the 433 ** opportunity to do this here since we have just deleted all of the 434 ** schema hash tables and therefore do not have to make any changes 435 ** to any of those tables. 436 */ 437 for(i=0; i<db->nDb; i++){ 438 struct Db *pDb = &db->aDb[i]; 439 if( pDb->pBt==0 ){ 440 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux); 441 pDb->pAux = 0; 442 } 443 } 444 for(i=j=2; i<db->nDb; i++){ 445 struct Db *pDb = &db->aDb[i]; 446 if( pDb->pBt==0 ){ 447 sqlite3_free(pDb->zName); 448 pDb->zName = 0; 449 continue; 450 } 451 if( j<i ){ 452 db->aDb[j] = db->aDb[i]; 453 } 454 j++; 455 } 456 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); 457 db->nDb = j; 458 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 459 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 460 sqlite3_free(db->aDb); 461 db->aDb = db->aDbStatic; 462 } 463 } 464 465 /* 466 ** This routine is called when a commit occurs. 467 */ 468 void sqlite3CommitInternalChanges(sqlite3 *db){ 469 db->flags &= ~SQLITE_InternChanges; 470 } 471 472 /* 473 ** Clear the column names from a table or view. 474 */ 475 static void sqliteResetColumnNames(Table *pTable){ 476 int i; 477 Column *pCol; 478 assert( pTable!=0 ); 479 if( (pCol = pTable->aCol)!=0 ){ 480 for(i=0; i<pTable->nCol; i++, pCol++){ 481 sqlite3_free(pCol->zName); 482 sqlite3ExprDelete(pCol->pDflt); 483 sqlite3_free(pCol->zType); 484 sqlite3_free(pCol->zColl); 485 } 486 sqlite3_free(pTable->aCol); 487 } 488 pTable->aCol = 0; 489 pTable->nCol = 0; 490 } 491 492 /* 493 ** Remove the memory data structures associated with the given 494 ** Table. No changes are made to disk by this routine. 495 ** 496 ** This routine just deletes the data structure. It does not unlink 497 ** the table data structure from the hash table. Nor does it remove 498 ** foreign keys from the sqlite.aFKey hash table. But it does destroy 499 ** memory structures of the indices and foreign keys associated with 500 ** the table. 501 */ 502 void sqlite3DeleteTable(Table *pTable){ 503 Index *pIndex, *pNext; 504 FKey *pFKey, *pNextFKey; 505 506 if( pTable==0 ) return; 507 508 /* Do not delete the table until the reference count reaches zero. */ 509 pTable->nRef--; 510 if( pTable->nRef>0 ){ 511 return; 512 } 513 assert( pTable->nRef==0 ); 514 515 /* Delete all indices associated with this table 516 */ 517 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 518 pNext = pIndex->pNext; 519 assert( pIndex->pSchema==pTable->pSchema ); 520 sqliteDeleteIndex(pIndex); 521 } 522 523 #ifndef SQLITE_OMIT_FOREIGN_KEY 524 /* Delete all foreign keys associated with this table. The keys 525 ** should have already been unlinked from the pSchema->aFKey hash table 526 */ 527 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){ 528 pNextFKey = pFKey->pNextFrom; 529 assert( sqlite3HashFind(&pTable->pSchema->aFKey, 530 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey ); 531 sqlite3_free(pFKey); 532 } 533 #endif 534 535 /* Delete the Table structure itself. 536 */ 537 sqliteResetColumnNames(pTable); 538 sqlite3_free(pTable->zName); 539 sqlite3_free(pTable->zColAff); 540 sqlite3SelectDelete(pTable->pSelect); 541 #ifndef SQLITE_OMIT_CHECK 542 sqlite3ExprDelete(pTable->pCheck); 543 #endif 544 sqlite3VtabClear(pTable); 545 sqlite3_free(pTable); 546 } 547 548 /* 549 ** Unlink the given table from the hash tables and the delete the 550 ** table structure with all its indices and foreign keys. 551 */ 552 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 553 Table *p; 554 FKey *pF1, *pF2; 555 Db *pDb; 556 557 assert( db!=0 ); 558 assert( iDb>=0 && iDb<db->nDb ); 559 assert( zTabName && zTabName[0] ); 560 pDb = &db->aDb[iDb]; 561 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0); 562 if( p ){ 563 #ifndef SQLITE_OMIT_FOREIGN_KEY 564 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){ 565 int nTo = strlen(pF1->zTo) + 1; 566 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo); 567 if( pF2==pF1 ){ 568 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo); 569 }else{ 570 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; } 571 if( pF2 ){ 572 pF2->pNextTo = pF1->pNextTo; 573 } 574 } 575 } 576 #endif 577 sqlite3DeleteTable(p); 578 } 579 db->flags |= SQLITE_InternChanges; 580 } 581 582 /* 583 ** Given a token, return a string that consists of the text of that 584 ** token with any quotations removed. Space to hold the returned string 585 ** is obtained from sqliteMalloc() and must be freed by the calling 586 ** function. 587 ** 588 ** Tokens are often just pointers into the original SQL text and so 589 ** are not \000 terminated and are not persistent. The returned string 590 ** is \000 terminated and is persistent. 591 */ 592 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ 593 char *zName; 594 if( pName ){ 595 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); 596 sqlite3Dequote(zName); 597 }else{ 598 zName = 0; 599 } 600 return zName; 601 } 602 603 /* 604 ** Open the sqlite_master table stored in database number iDb for 605 ** writing. The table is opened using cursor 0. 606 */ 607 void sqlite3OpenMasterTable(Parse *p, int iDb){ 608 Vdbe *v = sqlite3GetVdbe(p); 609 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); 610 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */ 611 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); 612 } 613 614 /* 615 ** The token *pName contains the name of a database (either "main" or 616 ** "temp" or the name of an attached db). This routine returns the 617 ** index of the named database in db->aDb[], or -1 if the named db 618 ** does not exist. 619 */ 620 int sqlite3FindDb(sqlite3 *db, Token *pName){ 621 int i = -1; /* Database number */ 622 int n; /* Number of characters in the name */ 623 Db *pDb; /* A database whose name space is being searched */ 624 char *zName; /* Name we are searching for */ 625 626 zName = sqlite3NameFromToken(db, pName); 627 if( zName ){ 628 n = strlen(zName); 629 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 630 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 631 0==sqlite3StrICmp(pDb->zName, zName) ){ 632 break; 633 } 634 } 635 sqlite3_free(zName); 636 } 637 return i; 638 } 639 640 /* The table or view or trigger name is passed to this routine via tokens 641 ** pName1 and pName2. If the table name was fully qualified, for example: 642 ** 643 ** CREATE TABLE xxx.yyy (...); 644 ** 645 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 646 ** the table name is not fully qualified, i.e.: 647 ** 648 ** CREATE TABLE yyy(...); 649 ** 650 ** Then pName1 is set to "yyy" and pName2 is "". 651 ** 652 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 653 ** pName2) that stores the unqualified table name. The index of the 654 ** database "xxx" is returned. 655 */ 656 int sqlite3TwoPartName( 657 Parse *pParse, /* Parsing and code generating context */ 658 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 659 Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 660 Token **pUnqual /* Write the unqualified object name here */ 661 ){ 662 int iDb; /* Database holding the object */ 663 sqlite3 *db = pParse->db; 664 665 if( pName2 && pName2->n>0 ){ 666 assert( !db->init.busy ); 667 *pUnqual = pName2; 668 iDb = sqlite3FindDb(db, pName1); 669 if( iDb<0 ){ 670 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 671 pParse->nErr++; 672 return -1; 673 } 674 }else{ 675 assert( db->init.iDb==0 || db->init.busy ); 676 iDb = db->init.iDb; 677 *pUnqual = pName1; 678 } 679 return iDb; 680 } 681 682 /* 683 ** This routine is used to check if the UTF-8 string zName is a legal 684 ** unqualified name for a new schema object (table, index, view or 685 ** trigger). All names are legal except those that begin with the string 686 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 687 ** is reserved for internal use. 688 */ 689 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ 690 if( !pParse->db->init.busy && pParse->nested==0 691 && (pParse->db->flags & SQLITE_WriteSchema)==0 692 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 693 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 694 return SQLITE_ERROR; 695 } 696 return SQLITE_OK; 697 } 698 699 /* 700 ** Begin constructing a new table representation in memory. This is 701 ** the first of several action routines that get called in response 702 ** to a CREATE TABLE statement. In particular, this routine is called 703 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 704 ** flag is true if the table should be stored in the auxiliary database 705 ** file instead of in the main database file. This is normally the case 706 ** when the "TEMP" or "TEMPORARY" keyword occurs in between 707 ** CREATE and TABLE. 708 ** 709 ** The new table record is initialized and put in pParse->pNewTable. 710 ** As more of the CREATE TABLE statement is parsed, additional action 711 ** routines will be called to add more information to this record. 712 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 713 ** is called to complete the construction of the new table record. 714 */ 715 void sqlite3StartTable( 716 Parse *pParse, /* Parser context */ 717 Token *pName1, /* First part of the name of the table or view */ 718 Token *pName2, /* Second part of the name of the table or view */ 719 int isTemp, /* True if this is a TEMP table */ 720 int isView, /* True if this is a VIEW */ 721 int isVirtual, /* True if this is a VIRTUAL table */ 722 int noErr /* Do nothing if table already exists */ 723 ){ 724 Table *pTable; 725 char *zName = 0; /* The name of the new table */ 726 sqlite3 *db = pParse->db; 727 Vdbe *v; 728 int iDb; /* Database number to create the table in */ 729 Token *pName; /* Unqualified name of the table to create */ 730 731 /* The table or view name to create is passed to this routine via tokens 732 ** pName1 and pName2. If the table name was fully qualified, for example: 733 ** 734 ** CREATE TABLE xxx.yyy (...); 735 ** 736 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 737 ** the table name is not fully qualified, i.e.: 738 ** 739 ** CREATE TABLE yyy(...); 740 ** 741 ** Then pName1 is set to "yyy" and pName2 is "". 742 ** 743 ** The call below sets the pName pointer to point at the token (pName1 or 744 ** pName2) that stores the unqualified table name. The variable iDb is 745 ** set to the index of the database that the table or view is to be 746 ** created in. 747 */ 748 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 749 if( iDb<0 ) return; 750 if( !OMIT_TEMPDB && isTemp && iDb>1 ){ 751 /* If creating a temp table, the name may not be qualified */ 752 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 753 return; 754 } 755 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 756 757 pParse->sNameToken = *pName; 758 zName = sqlite3NameFromToken(db, pName); 759 if( zName==0 ) return; 760 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 761 goto begin_table_error; 762 } 763 if( db->init.iDb==1 ) isTemp = 1; 764 #ifndef SQLITE_OMIT_AUTHORIZATION 765 assert( (isTemp & 1)==isTemp ); 766 { 767 int code; 768 char *zDb = db->aDb[iDb].zName; 769 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 770 goto begin_table_error; 771 } 772 if( isView ){ 773 if( !OMIT_TEMPDB && isTemp ){ 774 code = SQLITE_CREATE_TEMP_VIEW; 775 }else{ 776 code = SQLITE_CREATE_VIEW; 777 } 778 }else{ 779 if( !OMIT_TEMPDB && isTemp ){ 780 code = SQLITE_CREATE_TEMP_TABLE; 781 }else{ 782 code = SQLITE_CREATE_TABLE; 783 } 784 } 785 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ 786 goto begin_table_error; 787 } 788 } 789 #endif 790 791 /* Make sure the new table name does not collide with an existing 792 ** index or table name in the same database. Issue an error message if 793 ** it does. The exception is if the statement being parsed was passed 794 ** to an sqlite3_declare_vtab() call. In that case only the column names 795 ** and types will be used, so there is no need to test for namespace 796 ** collisions. 797 */ 798 if( !IN_DECLARE_VTAB ){ 799 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 800 goto begin_table_error; 801 } 802 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName); 803 if( pTable ){ 804 if( !noErr ){ 805 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 806 } 807 goto begin_table_error; 808 } 809 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){ 810 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 811 goto begin_table_error; 812 } 813 } 814 815 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 816 if( pTable==0 ){ 817 db->mallocFailed = 1; 818 pParse->rc = SQLITE_NOMEM; 819 pParse->nErr++; 820 goto begin_table_error; 821 } 822 pTable->zName = zName; 823 pTable->iPKey = -1; 824 pTable->pSchema = db->aDb[iDb].pSchema; 825 pTable->nRef = 1; 826 if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable); 827 pParse->pNewTable = pTable; 828 829 /* If this is the magic sqlite_sequence table used by autoincrement, 830 ** then record a pointer to this table in the main database structure 831 ** so that INSERT can find the table easily. 832 */ 833 #ifndef SQLITE_OMIT_AUTOINCREMENT 834 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 835 pTable->pSchema->pSeqTab = pTable; 836 } 837 #endif 838 839 /* Begin generating the code that will insert the table record into 840 ** the SQLITE_MASTER table. Note in particular that we must go ahead 841 ** and allocate the record number for the table entry now. Before any 842 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 843 ** indices to be created and the table record must come before the 844 ** indices. Hence, the record number for the table must be allocated 845 ** now. 846 */ 847 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 848 int j1; 849 int fileFormat; 850 int reg1, reg2, reg3; 851 sqlite3BeginWriteOperation(pParse, 0, iDb); 852 853 #ifndef SQLITE_OMIT_VIRTUALTABLE 854 if( isVirtual ){ 855 sqlite3VdbeAddOp0(v, OP_VBegin); 856 } 857 #endif 858 859 /* If the file format and encoding in the database have not been set, 860 ** set them now. 861 */ 862 reg1 = pParse->regRowid = ++pParse->nMem; 863 reg2 = pParse->regRoot = ++pParse->nMem; 864 reg3 = ++pParse->nMem; 865 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */ 866 sqlite3VdbeUsesBtree(v, iDb); 867 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); 868 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 869 1 : SQLITE_MAX_FILE_FORMAT; 870 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); 871 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3); 872 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); 873 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3); 874 sqlite3VdbeJumpHere(v, j1); 875 876 /* This just creates a place-holder record in the sqlite_master table. 877 ** The record created does not contain anything yet. It will be replaced 878 ** by the real entry in code generated at sqlite3EndTable(). 879 ** 880 ** The rowid for the new entry is left on the top of the stack. 881 ** The rowid value is needed by the code that sqlite3EndTable will 882 ** generate. 883 */ 884 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 885 if( isView || isVirtual ){ 886 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 887 }else 888 #endif 889 { 890 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); 891 } 892 sqlite3OpenMasterTable(pParse, iDb); 893 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 894 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); 895 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 896 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 897 sqlite3VdbeAddOp0(v, OP_Close); 898 } 899 900 /* Normal (non-error) return. */ 901 return; 902 903 /* If an error occurs, we jump here */ 904 begin_table_error: 905 sqlite3_free(zName); 906 return; 907 } 908 909 /* 910 ** This macro is used to compare two strings in a case-insensitive manner. 911 ** It is slightly faster than calling sqlite3StrICmp() directly, but 912 ** produces larger code. 913 ** 914 ** WARNING: This macro is not compatible with the strcmp() family. It 915 ** returns true if the two strings are equal, otherwise false. 916 */ 917 #define STRICMP(x, y) (\ 918 sqlite3UpperToLower[*(unsigned char *)(x)]== \ 919 sqlite3UpperToLower[*(unsigned char *)(y)] \ 920 && sqlite3StrICmp((x)+1,(y)+1)==0 ) 921 922 /* 923 ** Add a new column to the table currently being constructed. 924 ** 925 ** The parser calls this routine once for each column declaration 926 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 927 ** first to get things going. Then this routine is called for each 928 ** column. 929 */ 930 void sqlite3AddColumn(Parse *pParse, Token *pName){ 931 Table *p; 932 int i; 933 char *z; 934 Column *pCol; 935 sqlite3 *db = pParse->db; 936 if( (p = pParse->pNewTable)==0 ) return; 937 #if SQLITE_MAX_COLUMN 938 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 939 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 940 return; 941 } 942 #endif 943 z = sqlite3NameFromToken(pParse->db, pName); 944 if( z==0 ) return; 945 for(i=0; i<p->nCol; i++){ 946 if( STRICMP(z, p->aCol[i].zName) ){ 947 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 948 sqlite3_free(z); 949 return; 950 } 951 } 952 if( (p->nCol & 0x7)==0 ){ 953 Column *aNew; 954 aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); 955 if( aNew==0 ){ 956 sqlite3_free(z); 957 return; 958 } 959 p->aCol = aNew; 960 } 961 pCol = &p->aCol[p->nCol]; 962 memset(pCol, 0, sizeof(p->aCol[0])); 963 pCol->zName = z; 964 965 /* If there is no type specified, columns have the default affinity 966 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will 967 ** be called next to set pCol->affinity correctly. 968 */ 969 pCol->affinity = SQLITE_AFF_NONE; 970 p->nCol++; 971 } 972 973 /* 974 ** This routine is called by the parser while in the middle of 975 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 976 ** been seen on a column. This routine sets the notNull flag on 977 ** the column currently under construction. 978 */ 979 void sqlite3AddNotNull(Parse *pParse, int onError){ 980 Table *p; 981 int i; 982 if( (p = pParse->pNewTable)==0 ) return; 983 i = p->nCol-1; 984 if( i>=0 ) p->aCol[i].notNull = onError; 985 } 986 987 /* 988 ** Scan the column type name zType (length nType) and return the 989 ** associated affinity type. 990 ** 991 ** This routine does a case-independent search of zType for the 992 ** substrings in the following table. If one of the substrings is 993 ** found, the corresponding affinity is returned. If zType contains 994 ** more than one of the substrings, entries toward the top of 995 ** the table take priority. For example, if zType is 'BLOBINT', 996 ** SQLITE_AFF_INTEGER is returned. 997 ** 998 ** Substring | Affinity 999 ** -------------------------------- 1000 ** 'INT' | SQLITE_AFF_INTEGER 1001 ** 'CHAR' | SQLITE_AFF_TEXT 1002 ** 'CLOB' | SQLITE_AFF_TEXT 1003 ** 'TEXT' | SQLITE_AFF_TEXT 1004 ** 'BLOB' | SQLITE_AFF_NONE 1005 ** 'REAL' | SQLITE_AFF_REAL 1006 ** 'FLOA' | SQLITE_AFF_REAL 1007 ** 'DOUB' | SQLITE_AFF_REAL 1008 ** 1009 ** If none of the substrings in the above table are found, 1010 ** SQLITE_AFF_NUMERIC is returned. 1011 */ 1012 char sqlite3AffinityType(const Token *pType){ 1013 u32 h = 0; 1014 char aff = SQLITE_AFF_NUMERIC; 1015 const unsigned char *zIn = pType->z; 1016 const unsigned char *zEnd = &pType->z[pType->n]; 1017 1018 while( zIn!=zEnd ){ 1019 h = (h<<8) + sqlite3UpperToLower[*zIn]; 1020 zIn++; 1021 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 1022 aff = SQLITE_AFF_TEXT; 1023 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 1024 aff = SQLITE_AFF_TEXT; 1025 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 1026 aff = SQLITE_AFF_TEXT; 1027 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 1028 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 1029 aff = SQLITE_AFF_NONE; 1030 #ifndef SQLITE_OMIT_FLOATING_POINT 1031 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 1032 && aff==SQLITE_AFF_NUMERIC ){ 1033 aff = SQLITE_AFF_REAL; 1034 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 1035 && aff==SQLITE_AFF_NUMERIC ){ 1036 aff = SQLITE_AFF_REAL; 1037 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 1038 && aff==SQLITE_AFF_NUMERIC ){ 1039 aff = SQLITE_AFF_REAL; 1040 #endif 1041 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 1042 aff = SQLITE_AFF_INTEGER; 1043 break; 1044 } 1045 } 1046 1047 return aff; 1048 } 1049 1050 /* 1051 ** This routine is called by the parser while in the middle of 1052 ** parsing a CREATE TABLE statement. The pFirst token is the first 1053 ** token in the sequence of tokens that describe the type of the 1054 ** column currently under construction. pLast is the last token 1055 ** in the sequence. Use this information to construct a string 1056 ** that contains the typename of the column and store that string 1057 ** in zType. 1058 */ 1059 void sqlite3AddColumnType(Parse *pParse, Token *pType){ 1060 Table *p; 1061 int i; 1062 Column *pCol; 1063 1064 if( (p = pParse->pNewTable)==0 ) return; 1065 i = p->nCol-1; 1066 if( i<0 ) return; 1067 pCol = &p->aCol[i]; 1068 sqlite3_free(pCol->zType); 1069 pCol->zType = sqlite3NameFromToken(pParse->db, pType); 1070 pCol->affinity = sqlite3AffinityType(pType); 1071 } 1072 1073 /* 1074 ** The expression is the default value for the most recently added column 1075 ** of the table currently under construction. 1076 ** 1077 ** Default value expressions must be constant. Raise an exception if this 1078 ** is not the case. 1079 ** 1080 ** This routine is called by the parser while in the middle of 1081 ** parsing a CREATE TABLE statement. 1082 */ 1083 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){ 1084 Table *p; 1085 Column *pCol; 1086 if( (p = pParse->pNewTable)!=0 ){ 1087 pCol = &(p->aCol[p->nCol-1]); 1088 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){ 1089 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 1090 pCol->zName); 1091 }else{ 1092 Expr *pCopy; 1093 sqlite3 *db = pParse->db; 1094 sqlite3ExprDelete(pCol->pDflt); 1095 pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr); 1096 if( pCopy ){ 1097 sqlite3TokenCopy(db, &pCopy->span, &pExpr->span); 1098 } 1099 } 1100 } 1101 sqlite3ExprDelete(pExpr); 1102 } 1103 1104 /* 1105 ** Designate the PRIMARY KEY for the table. pList is a list of names 1106 ** of columns that form the primary key. If pList is NULL, then the 1107 ** most recently added column of the table is the primary key. 1108 ** 1109 ** A table can have at most one primary key. If the table already has 1110 ** a primary key (and this is the second primary key) then create an 1111 ** error. 1112 ** 1113 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 1114 ** then we will try to use that column as the rowid. Set the Table.iPKey 1115 ** field of the table under construction to be the index of the 1116 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 1117 ** no INTEGER PRIMARY KEY. 1118 ** 1119 ** If the key is not an INTEGER PRIMARY KEY, then create a unique 1120 ** index for the key. No index is created for INTEGER PRIMARY KEYs. 1121 */ 1122 void sqlite3AddPrimaryKey( 1123 Parse *pParse, /* Parsing context */ 1124 ExprList *pList, /* List of field names to be indexed */ 1125 int onError, /* What to do with a uniqueness conflict */ 1126 int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1127 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1128 ){ 1129 Table *pTab = pParse->pNewTable; 1130 char *zType = 0; 1131 int iCol = -1, i; 1132 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; 1133 if( pTab->hasPrimKey ){ 1134 sqlite3ErrorMsg(pParse, 1135 "table \"%s\" has more than one primary key", pTab->zName); 1136 goto primary_key_exit; 1137 } 1138 pTab->hasPrimKey = 1; 1139 if( pList==0 ){ 1140 iCol = pTab->nCol - 1; 1141 pTab->aCol[iCol].isPrimKey = 1; 1142 }else{ 1143 for(i=0; i<pList->nExpr; i++){ 1144 for(iCol=0; iCol<pTab->nCol; iCol++){ 1145 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ 1146 break; 1147 } 1148 } 1149 if( iCol<pTab->nCol ){ 1150 pTab->aCol[iCol].isPrimKey = 1; 1151 } 1152 } 1153 if( pList->nExpr>1 ) iCol = -1; 1154 } 1155 if( iCol>=0 && iCol<pTab->nCol ){ 1156 zType = pTab->aCol[iCol].zType; 1157 } 1158 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 1159 && sortOrder==SQLITE_SO_ASC ){ 1160 pTab->iPKey = iCol; 1161 pTab->keyConf = onError; 1162 pTab->autoInc = autoInc; 1163 }else if( autoInc ){ 1164 #ifndef SQLITE_OMIT_AUTOINCREMENT 1165 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1166 "INTEGER PRIMARY KEY"); 1167 #endif 1168 }else{ 1169 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); 1170 pList = 0; 1171 } 1172 1173 primary_key_exit: 1174 sqlite3ExprListDelete(pList); 1175 return; 1176 } 1177 1178 /* 1179 ** Add a new CHECK constraint to the table currently under construction. 1180 */ 1181 void sqlite3AddCheckConstraint( 1182 Parse *pParse, /* Parsing context */ 1183 Expr *pCheckExpr /* The check expression */ 1184 ){ 1185 #ifndef SQLITE_OMIT_CHECK 1186 Table *pTab = pParse->pNewTable; 1187 sqlite3 *db = pParse->db; 1188 if( pTab && !IN_DECLARE_VTAB ){ 1189 /* The CHECK expression must be duplicated so that tokens refer 1190 ** to malloced space and not the (ephemeral) text of the CREATE TABLE 1191 ** statement */ 1192 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 1193 sqlite3ExprDup(db, pCheckExpr)); 1194 } 1195 #endif 1196 sqlite3ExprDelete(pCheckExpr); 1197 } 1198 1199 /* 1200 ** Set the collation function of the most recently parsed table column 1201 ** to the CollSeq given. 1202 */ 1203 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 1204 Table *p; 1205 int i; 1206 char *zColl; /* Dequoted name of collation sequence */ 1207 1208 if( (p = pParse->pNewTable)==0 ) return; 1209 i = p->nCol-1; 1210 1211 zColl = sqlite3NameFromToken(pParse->db, pToken); 1212 if( !zColl ) return; 1213 1214 if( sqlite3LocateCollSeq(pParse, zColl, -1) ){ 1215 Index *pIdx; 1216 p->aCol[i].zColl = zColl; 1217 1218 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 1219 ** then an index may have been created on this column before the 1220 ** collation type was added. Correct this if it is the case. 1221 */ 1222 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1223 assert( pIdx->nColumn==1 ); 1224 if( pIdx->aiColumn[0]==i ){ 1225 pIdx->azColl[0] = p->aCol[i].zColl; 1226 } 1227 } 1228 }else{ 1229 sqlite3_free(zColl); 1230 } 1231 } 1232 1233 /* 1234 ** This function returns the collation sequence for database native text 1235 ** encoding identified by the string zName, length nName. 1236 ** 1237 ** If the requested collation sequence is not available, or not available 1238 ** in the database native encoding, the collation factory is invoked to 1239 ** request it. If the collation factory does not supply such a sequence, 1240 ** and the sequence is available in another text encoding, then that is 1241 ** returned instead. 1242 ** 1243 ** If no versions of the requested collations sequence are available, or 1244 ** another error occurs, NULL is returned and an error message written into 1245 ** pParse. 1246 ** 1247 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine 1248 ** invokes the collation factory if the named collation cannot be found 1249 ** and generates an error message. 1250 */ 1251 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){ 1252 sqlite3 *db = pParse->db; 1253 u8 enc = ENC(db); 1254 u8 initbusy = db->init.busy; 1255 CollSeq *pColl; 1256 1257 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy); 1258 if( !initbusy && (!pColl || !pColl->xCmp) ){ 1259 pColl = sqlite3GetCollSeq(db, pColl, zName, nName); 1260 if( !pColl ){ 1261 if( nName<0 ){ 1262 nName = strlen(zName); 1263 } 1264 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName); 1265 pColl = 0; 1266 } 1267 } 1268 1269 return pColl; 1270 } 1271 1272 1273 /* 1274 ** Generate code that will increment the schema cookie. 1275 ** 1276 ** The schema cookie is used to determine when the schema for the 1277 ** database changes. After each schema change, the cookie value 1278 ** changes. When a process first reads the schema it records the 1279 ** cookie. Thereafter, whenever it goes to access the database, 1280 ** it checks the cookie to make sure the schema has not changed 1281 ** since it was last read. 1282 ** 1283 ** This plan is not completely bullet-proof. It is possible for 1284 ** the schema to change multiple times and for the cookie to be 1285 ** set back to prior value. But schema changes are infrequent 1286 ** and the probability of hitting the same cookie value is only 1287 ** 1 chance in 2^32. So we're safe enough. 1288 */ 1289 void sqlite3ChangeCookie(Parse *pParse, int iDb){ 1290 int r1 = sqlite3GetTempReg(pParse); 1291 sqlite3 *db = pParse->db; 1292 Vdbe *v = pParse->pVdbe; 1293 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); 1294 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1); 1295 sqlite3ReleaseTempReg(pParse, r1); 1296 } 1297 1298 /* 1299 ** Measure the number of characters needed to output the given 1300 ** identifier. The number returned includes any quotes used 1301 ** but does not include the null terminator. 1302 ** 1303 ** The estimate is conservative. It might be larger that what is 1304 ** really needed. 1305 */ 1306 static int identLength(const char *z){ 1307 int n; 1308 for(n=0; *z; n++, z++){ 1309 if( *z=='"' ){ n++; } 1310 } 1311 return n + 2; 1312 } 1313 1314 /* 1315 ** Write an identifier onto the end of the given string. Add 1316 ** quote characters as needed. 1317 */ 1318 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 1319 unsigned char *zIdent = (unsigned char*)zSignedIdent; 1320 int i, j, needQuote; 1321 i = *pIdx; 1322 for(j=0; zIdent[j]; j++){ 1323 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 1324 } 1325 needQuote = zIdent[j]!=0 || isdigit(zIdent[0]) 1326 || sqlite3KeywordCode(zIdent, j)!=TK_ID; 1327 if( needQuote ) z[i++] = '"'; 1328 for(j=0; zIdent[j]; j++){ 1329 z[i++] = zIdent[j]; 1330 if( zIdent[j]=='"' ) z[i++] = '"'; 1331 } 1332 if( needQuote ) z[i++] = '"'; 1333 z[i] = 0; 1334 *pIdx = i; 1335 } 1336 1337 /* 1338 ** Generate a CREATE TABLE statement appropriate for the given 1339 ** table. Memory to hold the text of the statement is obtained 1340 ** from sqliteMalloc() and must be freed by the calling function. 1341 */ 1342 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){ 1343 int i, k, n; 1344 char *zStmt; 1345 char *zSep, *zSep2, *zEnd, *z; 1346 Column *pCol; 1347 n = 0; 1348 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 1349 n += identLength(pCol->zName); 1350 z = pCol->zType; 1351 if( z ){ 1352 n += (strlen(z) + 1); 1353 } 1354 } 1355 n += identLength(p->zName); 1356 if( n<50 ){ 1357 zSep = ""; 1358 zSep2 = ","; 1359 zEnd = ")"; 1360 }else{ 1361 zSep = "\n "; 1362 zSep2 = ",\n "; 1363 zEnd = "\n)"; 1364 } 1365 n += 35 + 6*p->nCol; 1366 zStmt = sqlite3_malloc( n ); 1367 if( zStmt==0 ){ 1368 db->mallocFailed = 1; 1369 return 0; 1370 } 1371 sqlite3_snprintf(n, zStmt, 1372 !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE "); 1373 k = strlen(zStmt); 1374 identPut(zStmt, &k, p->zName); 1375 zStmt[k++] = '('; 1376 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1377 sqlite3_snprintf(n-k, &zStmt[k], zSep); 1378 k += strlen(&zStmt[k]); 1379 zSep = zSep2; 1380 identPut(zStmt, &k, pCol->zName); 1381 if( (z = pCol->zType)!=0 ){ 1382 zStmt[k++] = ' '; 1383 assert( strlen(z)+k+1<=n ); 1384 sqlite3_snprintf(n-k, &zStmt[k], "%s", z); 1385 k += strlen(z); 1386 } 1387 } 1388 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 1389 return zStmt; 1390 } 1391 1392 /* 1393 ** This routine is called to report the final ")" that terminates 1394 ** a CREATE TABLE statement. 1395 ** 1396 ** The table structure that other action routines have been building 1397 ** is added to the internal hash tables, assuming no errors have 1398 ** occurred. 1399 ** 1400 ** An entry for the table is made in the master table on disk, unless 1401 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 1402 ** it means we are reading the sqlite_master table because we just 1403 ** connected to the database or because the sqlite_master table has 1404 ** recently changed, so the entry for this table already exists in 1405 ** the sqlite_master table. We do not want to create it again. 1406 ** 1407 ** If the pSelect argument is not NULL, it means that this routine 1408 ** was called to create a table generated from a 1409 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 1410 ** the new table will match the result set of the SELECT. 1411 */ 1412 void sqlite3EndTable( 1413 Parse *pParse, /* Parse context */ 1414 Token *pCons, /* The ',' token after the last column defn. */ 1415 Token *pEnd, /* The final ')' token in the CREATE TABLE */ 1416 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 1417 ){ 1418 Table *p; 1419 sqlite3 *db = pParse->db; 1420 int iDb; 1421 1422 if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) { 1423 return; 1424 } 1425 p = pParse->pNewTable; 1426 if( p==0 ) return; 1427 1428 assert( !db->init.busy || !pSelect ); 1429 1430 iDb = sqlite3SchemaToIndex(db, p->pSchema); 1431 1432 #ifndef SQLITE_OMIT_CHECK 1433 /* Resolve names in all CHECK constraint expressions. 1434 */ 1435 if( p->pCheck ){ 1436 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ 1437 NameContext sNC; /* Name context for pParse->pNewTable */ 1438 1439 memset(&sNC, 0, sizeof(sNC)); 1440 memset(&sSrc, 0, sizeof(sSrc)); 1441 sSrc.nSrc = 1; 1442 sSrc.a[0].zName = p->zName; 1443 sSrc.a[0].pTab = p; 1444 sSrc.a[0].iCursor = -1; 1445 sNC.pParse = pParse; 1446 sNC.pSrcList = &sSrc; 1447 sNC.isCheck = 1; 1448 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){ 1449 return; 1450 } 1451 } 1452 #endif /* !defined(SQLITE_OMIT_CHECK) */ 1453 1454 /* If the db->init.busy is 1 it means we are reading the SQL off the 1455 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 1456 ** So do not write to the disk again. Extract the root page number 1457 ** for the table from the db->init.newTnum field. (The page number 1458 ** should have been put there by the sqliteOpenCb routine.) 1459 */ 1460 if( db->init.busy ){ 1461 p->tnum = db->init.newTnum; 1462 } 1463 1464 /* If not initializing, then create a record for the new table 1465 ** in the SQLITE_MASTER table of the database. The record number 1466 ** for the new table entry should already be on the stack. 1467 ** 1468 ** If this is a TEMPORARY table, write the entry into the auxiliary 1469 ** file instead of into the main database file. 1470 */ 1471 if( !db->init.busy ){ 1472 int n; 1473 Vdbe *v; 1474 char *zType; /* "view" or "table" */ 1475 char *zType2; /* "VIEW" or "TABLE" */ 1476 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 1477 1478 v = sqlite3GetVdbe(pParse); 1479 if( v==0 ) return; 1480 1481 sqlite3VdbeAddOp1(v, OP_Close, 0); 1482 1483 /* Create the rootpage for the new table and push it onto the stack. 1484 ** A view has no rootpage, so just push a zero onto the stack for 1485 ** views. Initialize zType at the same time. 1486 */ 1487 if( p->pSelect==0 ){ 1488 /* A regular table */ 1489 zType = "table"; 1490 zType2 = "TABLE"; 1491 #ifndef SQLITE_OMIT_VIEW 1492 }else{ 1493 /* A view */ 1494 zType = "view"; 1495 zType2 = "VIEW"; 1496 #endif 1497 } 1498 1499 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 1500 ** statement to populate the new table. The root-page number for the 1501 ** new table is on the top of the vdbe stack. 1502 ** 1503 ** Once the SELECT has been coded by sqlite3Select(), it is in a 1504 ** suitable state to query for the column names and types to be used 1505 ** by the new table. 1506 ** 1507 ** A shared-cache write-lock is not required to write to the new table, 1508 ** as a schema-lock must have already been obtained to create it. Since 1509 ** a schema-lock excludes all other database users, the write-lock would 1510 ** be redundant. 1511 */ 1512 if( pSelect ){ 1513 SelectDest dest; 1514 Table *pSelTab; 1515 1516 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 1517 sqlite3VdbeChangeP5(v, 1); 1518 pParse->nTab = 2; 1519 sqlite3SelectDestInit(&dest, SRT_Table, 1); 1520 sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0); 1521 sqlite3VdbeAddOp1(v, OP_Close, 1); 1522 if( pParse->nErr==0 ){ 1523 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect); 1524 if( pSelTab==0 ) return; 1525 assert( p->aCol==0 ); 1526 p->nCol = pSelTab->nCol; 1527 p->aCol = pSelTab->aCol; 1528 pSelTab->nCol = 0; 1529 pSelTab->aCol = 0; 1530 sqlite3DeleteTable(pSelTab); 1531 } 1532 } 1533 1534 /* Compute the complete text of the CREATE statement */ 1535 if( pSelect ){ 1536 zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema); 1537 }else{ 1538 n = pEnd->z - pParse->sNameToken.z + 1; 1539 zStmt = sqlite3MPrintf(db, 1540 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 1541 ); 1542 } 1543 1544 /* A slot for the record has already been allocated in the 1545 ** SQLITE_MASTER table. We just need to update that slot with all 1546 ** the information we've collected. The rowid for the preallocated 1547 ** slot is the 2nd item on the stack. The top of the stack is the 1548 ** root page for the new table (or a 0 if this is a view). 1549 */ 1550 sqlite3NestedParse(pParse, 1551 "UPDATE %Q.%s " 1552 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " 1553 "WHERE rowid=#%d", 1554 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 1555 zType, 1556 p->zName, 1557 p->zName, 1558 pParse->regRoot, 1559 zStmt, 1560 pParse->regRowid 1561 ); 1562 sqlite3_free(zStmt); 1563 sqlite3ChangeCookie(pParse, iDb); 1564 1565 #ifndef SQLITE_OMIT_AUTOINCREMENT 1566 /* Check to see if we need to create an sqlite_sequence table for 1567 ** keeping track of autoincrement keys. 1568 */ 1569 if( p->autoInc ){ 1570 Db *pDb = &db->aDb[iDb]; 1571 if( pDb->pSchema->pSeqTab==0 ){ 1572 sqlite3NestedParse(pParse, 1573 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 1574 pDb->zName 1575 ); 1576 } 1577 } 1578 #endif 1579 1580 /* Reparse everything to update our internal data structures */ 1581 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 1582 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC); 1583 } 1584 1585 1586 /* Add the table to the in-memory representation of the database. 1587 */ 1588 if( db->init.busy && pParse->nErr==0 ){ 1589 Table *pOld; 1590 FKey *pFKey; 1591 Schema *pSchema = p->pSchema; 1592 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p); 1593 if( pOld ){ 1594 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 1595 db->mallocFailed = 1; 1596 return; 1597 } 1598 #ifndef SQLITE_OMIT_FOREIGN_KEY 1599 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1600 void *data; 1601 int nTo = strlen(pFKey->zTo) + 1; 1602 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo); 1603 data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey); 1604 if( data==(void *)pFKey ){ 1605 db->mallocFailed = 1; 1606 } 1607 } 1608 #endif 1609 pParse->pNewTable = 0; 1610 db->nTable++; 1611 db->flags |= SQLITE_InternChanges; 1612 1613 #ifndef SQLITE_OMIT_ALTERTABLE 1614 if( !p->pSelect ){ 1615 const char *zName = (const char *)pParse->sNameToken.z; 1616 int nName; 1617 assert( !pSelect && pCons && pEnd ); 1618 if( pCons->z==0 ){ 1619 pCons = pEnd; 1620 } 1621 nName = (const char *)pCons->z - zName; 1622 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); 1623 } 1624 #endif 1625 } 1626 } 1627 1628 #ifndef SQLITE_OMIT_VIEW 1629 /* 1630 ** The parser calls this routine in order to create a new VIEW 1631 */ 1632 void sqlite3CreateView( 1633 Parse *pParse, /* The parsing context */ 1634 Token *pBegin, /* The CREATE token that begins the statement */ 1635 Token *pName1, /* The token that holds the name of the view */ 1636 Token *pName2, /* The token that holds the name of the view */ 1637 Select *pSelect, /* A SELECT statement that will become the new view */ 1638 int isTemp, /* TRUE for a TEMPORARY view */ 1639 int noErr /* Suppress error messages if VIEW already exists */ 1640 ){ 1641 Table *p; 1642 int n; 1643 const unsigned char *z; 1644 Token sEnd; 1645 DbFixer sFix; 1646 Token *pName; 1647 int iDb; 1648 sqlite3 *db = pParse->db; 1649 1650 if( pParse->nVar>0 ){ 1651 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 1652 sqlite3SelectDelete(pSelect); 1653 return; 1654 } 1655 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 1656 p = pParse->pNewTable; 1657 if( p==0 || pParse->nErr ){ 1658 sqlite3SelectDelete(pSelect); 1659 return; 1660 } 1661 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 1662 iDb = sqlite3SchemaToIndex(db, p->pSchema); 1663 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName) 1664 && sqlite3FixSelect(&sFix, pSelect) 1665 ){ 1666 sqlite3SelectDelete(pSelect); 1667 return; 1668 } 1669 1670 /* Make a copy of the entire SELECT statement that defines the view. 1671 ** This will force all the Expr.token.z values to be dynamically 1672 ** allocated rather than point to the input string - which means that 1673 ** they will persist after the current sqlite3_exec() call returns. 1674 */ 1675 p->pSelect = sqlite3SelectDup(db, pSelect); 1676 sqlite3SelectDelete(pSelect); 1677 if( db->mallocFailed ){ 1678 return; 1679 } 1680 if( !db->init.busy ){ 1681 sqlite3ViewGetColumnNames(pParse, p); 1682 } 1683 1684 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 1685 ** the end. 1686 */ 1687 sEnd = pParse->sLastToken; 1688 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){ 1689 sEnd.z += sEnd.n; 1690 } 1691 sEnd.n = 0; 1692 n = sEnd.z - pBegin->z; 1693 z = (const unsigned char*)pBegin->z; 1694 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; } 1695 sEnd.z = &z[n-1]; 1696 sEnd.n = 1; 1697 1698 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 1699 sqlite3EndTable(pParse, 0, &sEnd, 0); 1700 return; 1701 } 1702 #endif /* SQLITE_OMIT_VIEW */ 1703 1704 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 1705 /* 1706 ** The Table structure pTable is really a VIEW. Fill in the names of 1707 ** the columns of the view in the pTable structure. Return the number 1708 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 1709 */ 1710 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 1711 Table *pSelTab; /* A fake table from which we get the result set */ 1712 Select *pSel; /* Copy of the SELECT that implements the view */ 1713 int nErr = 0; /* Number of errors encountered */ 1714 int n; /* Temporarily holds the number of cursors assigned */ 1715 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 1716 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); 1717 1718 assert( pTable ); 1719 1720 #ifndef SQLITE_OMIT_VIRTUALTABLE 1721 if( sqlite3VtabCallConnect(pParse, pTable) ){ 1722 return SQLITE_ERROR; 1723 } 1724 if( IsVirtual(pTable) ) return 0; 1725 #endif 1726 1727 #ifndef SQLITE_OMIT_VIEW 1728 /* A positive nCol means the columns names for this view are 1729 ** already known. 1730 */ 1731 if( pTable->nCol>0 ) return 0; 1732 1733 /* A negative nCol is a special marker meaning that we are currently 1734 ** trying to compute the column names. If we enter this routine with 1735 ** a negative nCol, it means two or more views form a loop, like this: 1736 ** 1737 ** CREATE VIEW one AS SELECT * FROM two; 1738 ** CREATE VIEW two AS SELECT * FROM one; 1739 ** 1740 ** Actually, this error is caught previously and so the following test 1741 ** should always fail. But we will leave it in place just to be safe. 1742 */ 1743 if( pTable->nCol<0 ){ 1744 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 1745 return 1; 1746 } 1747 assert( pTable->nCol>=0 ); 1748 1749 /* If we get this far, it means we need to compute the table names. 1750 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 1751 ** "*" elements in the results set of the view and will assign cursors 1752 ** to the elements of the FROM clause. But we do not want these changes 1753 ** to be permanent. So the computation is done on a copy of the SELECT 1754 ** statement that defines the view. 1755 */ 1756 assert( pTable->pSelect ); 1757 pSel = sqlite3SelectDup(db, pTable->pSelect); 1758 if( pSel ){ 1759 n = pParse->nTab; 1760 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 1761 pTable->nCol = -1; 1762 #ifndef SQLITE_OMIT_AUTHORIZATION 1763 xAuth = db->xAuth; 1764 db->xAuth = 0; 1765 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel); 1766 db->xAuth = xAuth; 1767 #else 1768 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel); 1769 #endif 1770 pParse->nTab = n; 1771 if( pSelTab ){ 1772 assert( pTable->aCol==0 ); 1773 pTable->nCol = pSelTab->nCol; 1774 pTable->aCol = pSelTab->aCol; 1775 pSelTab->nCol = 0; 1776 pSelTab->aCol = 0; 1777 sqlite3DeleteTable(pSelTab); 1778 pTable->pSchema->flags |= DB_UnresetViews; 1779 }else{ 1780 pTable->nCol = 0; 1781 nErr++; 1782 } 1783 sqlite3SelectDelete(pSel); 1784 } else { 1785 nErr++; 1786 } 1787 #endif /* SQLITE_OMIT_VIEW */ 1788 return nErr; 1789 } 1790 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 1791 1792 #ifndef SQLITE_OMIT_VIEW 1793 /* 1794 ** Clear the column names from every VIEW in database idx. 1795 */ 1796 static void sqliteViewResetAll(sqlite3 *db, int idx){ 1797 HashElem *i; 1798 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 1799 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 1800 Table *pTab = sqliteHashData(i); 1801 if( pTab->pSelect ){ 1802 sqliteResetColumnNames(pTab); 1803 } 1804 } 1805 DbClearProperty(db, idx, DB_UnresetViews); 1806 } 1807 #else 1808 # define sqliteViewResetAll(A,B) 1809 #endif /* SQLITE_OMIT_VIEW */ 1810 1811 /* 1812 ** This function is called by the VDBE to adjust the internal schema 1813 ** used by SQLite when the btree layer moves a table root page. The 1814 ** root-page of a table or index in database iDb has changed from iFrom 1815 ** to iTo. 1816 ** 1817 ** Ticket #1728: The symbol table might still contain information 1818 ** on tables and/or indices that are the process of being deleted. 1819 ** If you are unlucky, one of those deleted indices or tables might 1820 ** have the same rootpage number as the real table or index that is 1821 ** being moved. So we cannot stop searching after the first match 1822 ** because the first match might be for one of the deleted indices 1823 ** or tables and not the table/index that is actually being moved. 1824 ** We must continue looping until all tables and indices with 1825 ** rootpage==iFrom have been converted to have a rootpage of iTo 1826 ** in order to be certain that we got the right one. 1827 */ 1828 #ifndef SQLITE_OMIT_AUTOVACUUM 1829 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){ 1830 HashElem *pElem; 1831 Hash *pHash; 1832 1833 pHash = &pDb->pSchema->tblHash; 1834 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 1835 Table *pTab = sqliteHashData(pElem); 1836 if( pTab->tnum==iFrom ){ 1837 pTab->tnum = iTo; 1838 } 1839 } 1840 pHash = &pDb->pSchema->idxHash; 1841 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 1842 Index *pIdx = sqliteHashData(pElem); 1843 if( pIdx->tnum==iFrom ){ 1844 pIdx->tnum = iTo; 1845 } 1846 } 1847 } 1848 #endif 1849 1850 /* 1851 ** Write code to erase the table with root-page iTable from database iDb. 1852 ** Also write code to modify the sqlite_master table and internal schema 1853 ** if a root-page of another table is moved by the btree-layer whilst 1854 ** erasing iTable (this can happen with an auto-vacuum database). 1855 */ 1856 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 1857 Vdbe *v = sqlite3GetVdbe(pParse); 1858 int r1 = sqlite3GetTempReg(pParse); 1859 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 1860 #ifndef SQLITE_OMIT_AUTOVACUUM 1861 /* OP_Destroy stores an in integer r1. If this integer 1862 ** is non-zero, then it is the root page number of a table moved to 1863 ** location iTable. The following code modifies the sqlite_master table to 1864 ** reflect this. 1865 ** 1866 ** The "#%d" in the SQL is a special constant that means whatever value 1867 ** is on the top of the stack. See sqlite3RegisterExpr(). 1868 */ 1869 sqlite3NestedParse(pParse, 1870 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", 1871 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); 1872 #endif 1873 sqlite3ReleaseTempReg(pParse, r1); 1874 } 1875 1876 /* 1877 ** Write VDBE code to erase table pTab and all associated indices on disk. 1878 ** Code to update the sqlite_master tables and internal schema definitions 1879 ** in case a root-page belonging to another table is moved by the btree layer 1880 ** is also added (this can happen with an auto-vacuum database). 1881 */ 1882 static void destroyTable(Parse *pParse, Table *pTab){ 1883 #ifdef SQLITE_OMIT_AUTOVACUUM 1884 Index *pIdx; 1885 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1886 destroyRootPage(pParse, pTab->tnum, iDb); 1887 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1888 destroyRootPage(pParse, pIdx->tnum, iDb); 1889 } 1890 #else 1891 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 1892 ** is not defined), then it is important to call OP_Destroy on the 1893 ** table and index root-pages in order, starting with the numerically 1894 ** largest root-page number. This guarantees that none of the root-pages 1895 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 1896 ** following were coded: 1897 ** 1898 ** OP_Destroy 4 0 1899 ** ... 1900 ** OP_Destroy 5 0 1901 ** 1902 ** and root page 5 happened to be the largest root-page number in the 1903 ** database, then root page 5 would be moved to page 4 by the 1904 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 1905 ** a free-list page. 1906 */ 1907 int iTab = pTab->tnum; 1908 int iDestroyed = 0; 1909 1910 while( 1 ){ 1911 Index *pIdx; 1912 int iLargest = 0; 1913 1914 if( iDestroyed==0 || iTab<iDestroyed ){ 1915 iLargest = iTab; 1916 } 1917 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1918 int iIdx = pIdx->tnum; 1919 assert( pIdx->pSchema==pTab->pSchema ); 1920 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 1921 iLargest = iIdx; 1922 } 1923 } 1924 if( iLargest==0 ){ 1925 return; 1926 }else{ 1927 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1928 destroyRootPage(pParse, iLargest, iDb); 1929 iDestroyed = iLargest; 1930 } 1931 } 1932 #endif 1933 } 1934 1935 /* 1936 ** This routine is called to do the work of a DROP TABLE statement. 1937 ** pName is the name of the table to be dropped. 1938 */ 1939 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 1940 Table *pTab; 1941 Vdbe *v; 1942 sqlite3 *db = pParse->db; 1943 int iDb; 1944 1945 if( pParse->nErr || db->mallocFailed ){ 1946 goto exit_drop_table; 1947 } 1948 assert( pName->nSrc==1 ); 1949 pTab = sqlite3LocateTable(pParse, isView, 1950 pName->a[0].zName, pName->a[0].zDatabase); 1951 1952 if( pTab==0 ){ 1953 if( noErr ){ 1954 sqlite3ErrorClear(pParse); 1955 } 1956 goto exit_drop_table; 1957 } 1958 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1959 assert( iDb>=0 && iDb<db->nDb ); 1960 1961 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 1962 ** it is initialized. 1963 */ 1964 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 1965 goto exit_drop_table; 1966 } 1967 #ifndef SQLITE_OMIT_AUTHORIZATION 1968 { 1969 int code; 1970 const char *zTab = SCHEMA_TABLE(iDb); 1971 const char *zDb = db->aDb[iDb].zName; 1972 const char *zArg2 = 0; 1973 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 1974 goto exit_drop_table; 1975 } 1976 if( isView ){ 1977 if( !OMIT_TEMPDB && iDb==1 ){ 1978 code = SQLITE_DROP_TEMP_VIEW; 1979 }else{ 1980 code = SQLITE_DROP_VIEW; 1981 } 1982 #ifndef SQLITE_OMIT_VIRTUALTABLE 1983 }else if( IsVirtual(pTab) ){ 1984 code = SQLITE_DROP_VTABLE; 1985 zArg2 = pTab->pMod->zName; 1986 #endif 1987 }else{ 1988 if( !OMIT_TEMPDB && iDb==1 ){ 1989 code = SQLITE_DROP_TEMP_TABLE; 1990 }else{ 1991 code = SQLITE_DROP_TABLE; 1992 } 1993 } 1994 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 1995 goto exit_drop_table; 1996 } 1997 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 1998 goto exit_drop_table; 1999 } 2000 } 2001 #endif 2002 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){ 2003 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 2004 goto exit_drop_table; 2005 } 2006 2007 #ifndef SQLITE_OMIT_VIEW 2008 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 2009 ** on a table. 2010 */ 2011 if( isView && pTab->pSelect==0 ){ 2012 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 2013 goto exit_drop_table; 2014 } 2015 if( !isView && pTab->pSelect ){ 2016 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 2017 goto exit_drop_table; 2018 } 2019 #endif 2020 2021 /* Generate code to remove the table from the master table 2022 ** on disk. 2023 */ 2024 v = sqlite3GetVdbe(pParse); 2025 if( v ){ 2026 Trigger *pTrigger; 2027 Db *pDb = &db->aDb[iDb]; 2028 sqlite3BeginWriteOperation(pParse, 1, iDb); 2029 2030 #ifndef SQLITE_OMIT_VIRTUALTABLE 2031 if( IsVirtual(pTab) ){ 2032 Vdbe *v = sqlite3GetVdbe(pParse); 2033 if( v ){ 2034 sqlite3VdbeAddOp0(v, OP_VBegin); 2035 } 2036 } 2037 #endif 2038 2039 /* Drop all triggers associated with the table being dropped. Code 2040 ** is generated to remove entries from sqlite_master and/or 2041 ** sqlite_temp_master if required. 2042 */ 2043 pTrigger = pTab->pTrigger; 2044 while( pTrigger ){ 2045 assert( pTrigger->pSchema==pTab->pSchema || 2046 pTrigger->pSchema==db->aDb[1].pSchema ); 2047 sqlite3DropTriggerPtr(pParse, pTrigger); 2048 pTrigger = pTrigger->pNext; 2049 } 2050 2051 #ifndef SQLITE_OMIT_AUTOINCREMENT 2052 /* Remove any entries of the sqlite_sequence table associated with 2053 ** the table being dropped. This is done before the table is dropped 2054 ** at the btree level, in case the sqlite_sequence table needs to 2055 ** move as a result of the drop (can happen in auto-vacuum mode). 2056 */ 2057 if( pTab->autoInc ){ 2058 sqlite3NestedParse(pParse, 2059 "DELETE FROM %s.sqlite_sequence WHERE name=%Q", 2060 pDb->zName, pTab->zName 2061 ); 2062 } 2063 #endif 2064 2065 /* Drop all SQLITE_MASTER table and index entries that refer to the 2066 ** table. The program name loops through the master table and deletes 2067 ** every row that refers to a table of the same name as the one being 2068 ** dropped. Triggers are handled seperately because a trigger can be 2069 ** created in the temp database that refers to a table in another 2070 ** database. 2071 */ 2072 sqlite3NestedParse(pParse, 2073 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 2074 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); 2075 2076 /* Drop any statistics from the sqlite_stat1 table, if it exists */ 2077 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 2078 sqlite3NestedParse(pParse, 2079 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName 2080 ); 2081 } 2082 2083 if( !isView && !IsVirtual(pTab) ){ 2084 destroyTable(pParse, pTab); 2085 } 2086 2087 /* Remove the table entry from SQLite's internal schema and modify 2088 ** the schema cookie. 2089 */ 2090 if( IsVirtual(pTab) ){ 2091 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 2092 } 2093 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 2094 sqlite3ChangeCookie(pParse, iDb); 2095 } 2096 sqliteViewResetAll(db, iDb); 2097 2098 exit_drop_table: 2099 sqlite3SrcListDelete(pName); 2100 } 2101 2102 /* 2103 ** This routine is called to create a new foreign key on the table 2104 ** currently under construction. pFromCol determines which columns 2105 ** in the current table point to the foreign key. If pFromCol==0 then 2106 ** connect the key to the last column inserted. pTo is the name of 2107 ** the table referred to. pToCol is a list of tables in the other 2108 ** pTo table that the foreign key points to. flags contains all 2109 ** information about the conflict resolution algorithms specified 2110 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 2111 ** 2112 ** An FKey structure is created and added to the table currently 2113 ** under construction in the pParse->pNewTable field. The new FKey 2114 ** is not linked into db->aFKey at this point - that does not happen 2115 ** until sqlite3EndTable(). 2116 ** 2117 ** The foreign key is set for IMMEDIATE processing. A subsequent call 2118 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 2119 */ 2120 void sqlite3CreateForeignKey( 2121 Parse *pParse, /* Parsing context */ 2122 ExprList *pFromCol, /* Columns in this table that point to other table */ 2123 Token *pTo, /* Name of the other table */ 2124 ExprList *pToCol, /* Columns in the other table */ 2125 int flags /* Conflict resolution algorithms. */ 2126 ){ 2127 #ifndef SQLITE_OMIT_FOREIGN_KEY 2128 FKey *pFKey = 0; 2129 Table *p = pParse->pNewTable; 2130 int nByte; 2131 int i; 2132 int nCol; 2133 char *z; 2134 2135 assert( pTo!=0 ); 2136 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end; 2137 if( pFromCol==0 ){ 2138 int iCol = p->nCol-1; 2139 if( iCol<0 ) goto fk_end; 2140 if( pToCol && pToCol->nExpr!=1 ){ 2141 sqlite3ErrorMsg(pParse, "foreign key on %s" 2142 " should reference only one column of table %T", 2143 p->aCol[iCol].zName, pTo); 2144 goto fk_end; 2145 } 2146 nCol = 1; 2147 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 2148 sqlite3ErrorMsg(pParse, 2149 "number of columns in foreign key does not match the number of " 2150 "columns in the referenced table"); 2151 goto fk_end; 2152 }else{ 2153 nCol = pFromCol->nExpr; 2154 } 2155 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1; 2156 if( pToCol ){ 2157 for(i=0; i<pToCol->nExpr; i++){ 2158 nByte += strlen(pToCol->a[i].zName) + 1; 2159 } 2160 } 2161 pFKey = sqlite3DbMallocZero(pParse->db, nByte ); 2162 if( pFKey==0 ){ 2163 goto fk_end; 2164 } 2165 pFKey->pFrom = p; 2166 pFKey->pNextFrom = p->pFKey; 2167 z = (char*)&pFKey[1]; 2168 pFKey->aCol = (struct sColMap*)z; 2169 z += sizeof(struct sColMap)*nCol; 2170 pFKey->zTo = z; 2171 memcpy(z, pTo->z, pTo->n); 2172 z[pTo->n] = 0; 2173 z += pTo->n+1; 2174 pFKey->pNextTo = 0; 2175 pFKey->nCol = nCol; 2176 if( pFromCol==0 ){ 2177 pFKey->aCol[0].iFrom = p->nCol-1; 2178 }else{ 2179 for(i=0; i<nCol; i++){ 2180 int j; 2181 for(j=0; j<p->nCol; j++){ 2182 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 2183 pFKey->aCol[i].iFrom = j; 2184 break; 2185 } 2186 } 2187 if( j>=p->nCol ){ 2188 sqlite3ErrorMsg(pParse, 2189 "unknown column \"%s\" in foreign key definition", 2190 pFromCol->a[i].zName); 2191 goto fk_end; 2192 } 2193 } 2194 } 2195 if( pToCol ){ 2196 for(i=0; i<nCol; i++){ 2197 int n = strlen(pToCol->a[i].zName); 2198 pFKey->aCol[i].zCol = z; 2199 memcpy(z, pToCol->a[i].zName, n); 2200 z[n] = 0; 2201 z += n+1; 2202 } 2203 } 2204 pFKey->isDeferred = 0; 2205 pFKey->deleteConf = flags & 0xff; 2206 pFKey->updateConf = (flags >> 8 ) & 0xff; 2207 pFKey->insertConf = (flags >> 16 ) & 0xff; 2208 2209 /* Link the foreign key to the table as the last step. 2210 */ 2211 p->pFKey = pFKey; 2212 pFKey = 0; 2213 2214 fk_end: 2215 sqlite3_free(pFKey); 2216 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 2217 sqlite3ExprListDelete(pFromCol); 2218 sqlite3ExprListDelete(pToCol); 2219 } 2220 2221 /* 2222 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 2223 ** clause is seen as part of a foreign key definition. The isDeferred 2224 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 2225 ** The behavior of the most recently created foreign key is adjusted 2226 ** accordingly. 2227 */ 2228 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 2229 #ifndef SQLITE_OMIT_FOREIGN_KEY 2230 Table *pTab; 2231 FKey *pFKey; 2232 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 2233 pFKey->isDeferred = isDeferred; 2234 #endif 2235 } 2236 2237 /* 2238 ** Generate code that will erase and refill index *pIdx. This is 2239 ** used to initialize a newly created index or to recompute the 2240 ** content of an index in response to a REINDEX command. 2241 ** 2242 ** if memRootPage is not negative, it means that the index is newly 2243 ** created. The register specified by memRootPage contains the 2244 ** root page number of the index. If memRootPage is negative, then 2245 ** the index already exists and must be cleared before being refilled and 2246 ** the root page number of the index is taken from pIndex->tnum. 2247 */ 2248 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 2249 Table *pTab = pIndex->pTable; /* The table that is indexed */ 2250 int iTab = pParse->nTab; /* Btree cursor used for pTab */ 2251 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */ 2252 int addr1; /* Address of top of loop */ 2253 int tnum; /* Root page of index */ 2254 Vdbe *v; /* Generate code into this virtual machine */ 2255 KeyInfo *pKey; /* KeyInfo for index */ 2256 int regIdxKey; /* Registers containing the index key */ 2257 int regRecord; /* Register holding assemblied index record */ 2258 sqlite3 *db = pParse->db; /* The database connection */ 2259 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2260 2261 #ifndef SQLITE_OMIT_AUTHORIZATION 2262 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 2263 db->aDb[iDb].zName ) ){ 2264 return; 2265 } 2266 #endif 2267 2268 /* Require a write-lock on the table to perform this operation */ 2269 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 2270 2271 v = sqlite3GetVdbe(pParse); 2272 if( v==0 ) return; 2273 if( memRootPage>=0 ){ 2274 tnum = memRootPage; 2275 }else{ 2276 tnum = pIndex->tnum; 2277 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 2278 } 2279 pKey = sqlite3IndexKeyinfo(pParse, pIndex); 2280 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 2281 (char *)pKey, P4_KEYINFO_HANDOFF); 2282 if( memRootPage>=0 ){ 2283 sqlite3VdbeChangeP5(v, 1); 2284 } 2285 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2286 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); 2287 regRecord = sqlite3GetTempReg(pParse); 2288 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1); 2289 if( pIndex->onError!=OE_None ){ 2290 int j1, j2; 2291 int regRowid; 2292 2293 regRowid = regIdxKey + pIndex->nColumn; 2294 j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn); 2295 j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, 2296 0, regRowid, (char*)(sqlite3_intptr_t)regRecord, P4_INT32); 2297 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0, 2298 "indexed columns are not unique", P4_STATIC); 2299 sqlite3VdbeJumpHere(v, j1); 2300 sqlite3VdbeJumpHere(v, j2); 2301 } 2302 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 2303 sqlite3ReleaseTempReg(pParse, regRecord); 2304 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); 2305 sqlite3VdbeJumpHere(v, addr1); 2306 sqlite3VdbeAddOp1(v, OP_Close, iTab); 2307 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 2308 } 2309 2310 /* 2311 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 2312 ** and pTblList is the name of the table that is to be indexed. Both will 2313 ** be NULL for a primary key or an index that is created to satisfy a 2314 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 2315 ** as the table to be indexed. pParse->pNewTable is a table that is 2316 ** currently being constructed by a CREATE TABLE statement. 2317 ** 2318 ** pList is a list of columns to be indexed. pList will be NULL if this 2319 ** is a primary key or unique-constraint on the most recent column added 2320 ** to the table currently under construction. 2321 */ 2322 void sqlite3CreateIndex( 2323 Parse *pParse, /* All information about this parse */ 2324 Token *pName1, /* First part of index name. May be NULL */ 2325 Token *pName2, /* Second part of index name. May be NULL */ 2326 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 2327 ExprList *pList, /* A list of columns to be indexed */ 2328 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 2329 Token *pStart, /* The CREATE token that begins this statement */ 2330 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */ 2331 int sortOrder, /* Sort order of primary key when pList==NULL */ 2332 int ifNotExist /* Omit error if index already exists */ 2333 ){ 2334 Table *pTab = 0; /* Table to be indexed */ 2335 Index *pIndex = 0; /* The index to be created */ 2336 char *zName = 0; /* Name of the index */ 2337 int nName; /* Number of characters in zName */ 2338 int i, j; 2339 Token nullId; /* Fake token for an empty ID list */ 2340 DbFixer sFix; /* For assigning database names to pTable */ 2341 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 2342 sqlite3 *db = pParse->db; 2343 Db *pDb; /* The specific table containing the indexed database */ 2344 int iDb; /* Index of the database that is being written */ 2345 Token *pName = 0; /* Unqualified name of the index to create */ 2346 struct ExprList_item *pListItem; /* For looping over pList */ 2347 int nCol; 2348 int nExtra = 0; 2349 char *zExtra; 2350 2351 if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){ 2352 goto exit_create_index; 2353 } 2354 2355 /* 2356 ** Find the table that is to be indexed. Return early if not found. 2357 */ 2358 if( pTblName!=0 ){ 2359 2360 /* Use the two-part index name to determine the database 2361 ** to search for the table. 'Fix' the table name to this db 2362 ** before looking up the table. 2363 */ 2364 assert( pName1 && pName2 ); 2365 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2366 if( iDb<0 ) goto exit_create_index; 2367 2368 #ifndef SQLITE_OMIT_TEMPDB 2369 /* If the index name was unqualified, check if the the table 2370 ** is a temp table. If so, set the database to 1. Do not do this 2371 ** if initialising a database schema. 2372 */ 2373 if( !db->init.busy ){ 2374 pTab = sqlite3SrcListLookup(pParse, pTblName); 2375 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 2376 iDb = 1; 2377 } 2378 } 2379 #endif 2380 2381 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && 2382 sqlite3FixSrcList(&sFix, pTblName) 2383 ){ 2384 /* Because the parser constructs pTblName from a single identifier, 2385 ** sqlite3FixSrcList can never fail. */ 2386 assert(0); 2387 } 2388 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 2389 pTblName->a[0].zDatabase); 2390 if( !pTab ) goto exit_create_index; 2391 assert( db->aDb[iDb].pSchema==pTab->pSchema ); 2392 }else{ 2393 assert( pName==0 ); 2394 pTab = pParse->pNewTable; 2395 if( !pTab ) goto exit_create_index; 2396 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2397 } 2398 pDb = &db->aDb[iDb]; 2399 2400 if( pTab==0 || pParse->nErr ) goto exit_create_index; 2401 if( pTab->readOnly ){ 2402 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 2403 goto exit_create_index; 2404 } 2405 #ifndef SQLITE_OMIT_VIEW 2406 if( pTab->pSelect ){ 2407 sqlite3ErrorMsg(pParse, "views may not be indexed"); 2408 goto exit_create_index; 2409 } 2410 #endif 2411 #ifndef SQLITE_OMIT_VIRTUALTABLE 2412 if( IsVirtual(pTab) ){ 2413 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 2414 goto exit_create_index; 2415 } 2416 #endif 2417 2418 /* 2419 ** Find the name of the index. Make sure there is not already another 2420 ** index or table with the same name. 2421 ** 2422 ** Exception: If we are reading the names of permanent indices from the 2423 ** sqlite_master table (because some other process changed the schema) and 2424 ** one of the index names collides with the name of a temporary table or 2425 ** index, then we will continue to process this index. 2426 ** 2427 ** If pName==0 it means that we are 2428 ** dealing with a primary key or UNIQUE constraint. We have to invent our 2429 ** own name. 2430 */ 2431 if( pName ){ 2432 zName = sqlite3NameFromToken(db, pName); 2433 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; 2434 if( zName==0 ) goto exit_create_index; 2435 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 2436 goto exit_create_index; 2437 } 2438 if( !db->init.busy ){ 2439 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; 2440 if( sqlite3FindTable(db, zName, 0)!=0 ){ 2441 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 2442 goto exit_create_index; 2443 } 2444 } 2445 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ 2446 if( !ifNotExist ){ 2447 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 2448 } 2449 goto exit_create_index; 2450 } 2451 }else{ 2452 char zBuf[30]; 2453 int n; 2454 Index *pLoop; 2455 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 2456 sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n); 2457 zName = 0; 2458 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0); 2459 if( zName==0 ){ 2460 db->mallocFailed = 1; 2461 goto exit_create_index; 2462 } 2463 } 2464 2465 /* Check for authorization to create an index. 2466 */ 2467 #ifndef SQLITE_OMIT_AUTHORIZATION 2468 { 2469 const char *zDb = pDb->zName; 2470 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 2471 goto exit_create_index; 2472 } 2473 i = SQLITE_CREATE_INDEX; 2474 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 2475 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 2476 goto exit_create_index; 2477 } 2478 } 2479 #endif 2480 2481 /* If pList==0, it means this routine was called to make a primary 2482 ** key out of the last column added to the table under construction. 2483 ** So create a fake list to simulate this. 2484 */ 2485 if( pList==0 ){ 2486 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName; 2487 nullId.n = strlen((char*)nullId.z); 2488 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId); 2489 if( pList==0 ) goto exit_create_index; 2490 pList->a[0].sortOrder = sortOrder; 2491 } 2492 2493 /* Figure out how many bytes of space are required to store explicitly 2494 ** specified collation sequence names. 2495 */ 2496 for(i=0; i<pList->nExpr; i++){ 2497 Expr *pExpr = pList->a[i].pExpr; 2498 if( pExpr ){ 2499 nExtra += (1 + strlen(pExpr->pColl->zName)); 2500 } 2501 } 2502 2503 /* 2504 ** Allocate the index structure. 2505 */ 2506 nName = strlen(zName); 2507 nCol = pList->nExpr; 2508 pIndex = sqlite3DbMallocZero(db, 2509 sizeof(Index) + /* Index structure */ 2510 sizeof(int)*nCol + /* Index.aiColumn */ 2511 sizeof(int)*(nCol+1) + /* Index.aiRowEst */ 2512 sizeof(char *)*nCol + /* Index.azColl */ 2513 sizeof(u8)*nCol + /* Index.aSortOrder */ 2514 nName + 1 + /* Index.zName */ 2515 nExtra /* Collation sequence names */ 2516 ); 2517 if( db->mallocFailed ){ 2518 goto exit_create_index; 2519 } 2520 pIndex->azColl = (char**)(&pIndex[1]); 2521 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); 2522 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]); 2523 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]); 2524 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); 2525 zExtra = (char *)(&pIndex->zName[nName+1]); 2526 memcpy(pIndex->zName, zName, nName+1); 2527 pIndex->pTable = pTab; 2528 pIndex->nColumn = pList->nExpr; 2529 pIndex->onError = onError; 2530 pIndex->autoIndex = pName==0; 2531 pIndex->pSchema = db->aDb[iDb].pSchema; 2532 2533 /* Check to see if we should honor DESC requests on index columns 2534 */ 2535 if( pDb->pSchema->file_format>=4 ){ 2536 sortOrderMask = -1; /* Honor DESC */ 2537 }else{ 2538 sortOrderMask = 0; /* Ignore DESC */ 2539 } 2540 2541 /* Scan the names of the columns of the table to be indexed and 2542 ** load the column indices into the Index structure. Report an error 2543 ** if any column is not found. 2544 */ 2545 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 2546 const char *zColName = pListItem->zName; 2547 Column *pTabCol; 2548 int requestedSortOrder; 2549 char *zColl; /* Collation sequence name */ 2550 2551 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){ 2552 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; 2553 } 2554 if( j>=pTab->nCol ){ 2555 sqlite3ErrorMsg(pParse, "table %s has no column named %s", 2556 pTab->zName, zColName); 2557 goto exit_create_index; 2558 } 2559 /* TODO: Add a test to make sure that the same column is not named 2560 ** more than once within the same index. Only the first instance of 2561 ** the column will ever be used by the optimizer. Note that using the 2562 ** same column more than once cannot be an error because that would 2563 ** break backwards compatibility - it needs to be a warning. 2564 */ 2565 pIndex->aiColumn[i] = j; 2566 if( pListItem->pExpr ){ 2567 assert( pListItem->pExpr->pColl ); 2568 zColl = zExtra; 2569 sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName); 2570 zExtra += (strlen(zColl) + 1); 2571 }else{ 2572 zColl = pTab->aCol[j].zColl; 2573 if( !zColl ){ 2574 zColl = db->pDfltColl->zName; 2575 } 2576 } 2577 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){ 2578 goto exit_create_index; 2579 } 2580 pIndex->azColl[i] = zColl; 2581 requestedSortOrder = pListItem->sortOrder & sortOrderMask; 2582 pIndex->aSortOrder[i] = requestedSortOrder; 2583 } 2584 sqlite3DefaultRowEst(pIndex); 2585 2586 if( pTab==pParse->pNewTable ){ 2587 /* This routine has been called to create an automatic index as a 2588 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 2589 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 2590 ** i.e. one of: 2591 ** 2592 ** CREATE TABLE t(x PRIMARY KEY, y); 2593 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 2594 ** 2595 ** Either way, check to see if the table already has such an index. If 2596 ** so, don't bother creating this one. This only applies to 2597 ** automatically created indices. Users can do as they wish with 2598 ** explicit indices. 2599 */ 2600 Index *pIdx; 2601 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2602 int k; 2603 assert( pIdx->onError!=OE_None ); 2604 assert( pIdx->autoIndex ); 2605 assert( pIndex->onError!=OE_None ); 2606 2607 if( pIdx->nColumn!=pIndex->nColumn ) continue; 2608 for(k=0; k<pIdx->nColumn; k++){ 2609 const char *z1 = pIdx->azColl[k]; 2610 const char *z2 = pIndex->azColl[k]; 2611 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 2612 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break; 2613 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; 2614 } 2615 if( k==pIdx->nColumn ){ 2616 if( pIdx->onError!=pIndex->onError ){ 2617 /* This constraint creates the same index as a previous 2618 ** constraint specified somewhere in the CREATE TABLE statement. 2619 ** However the ON CONFLICT clauses are different. If both this 2620 ** constraint and the previous equivalent constraint have explicit 2621 ** ON CONFLICT clauses this is an error. Otherwise, use the 2622 ** explicitly specified behaviour for the index. 2623 */ 2624 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 2625 sqlite3ErrorMsg(pParse, 2626 "conflicting ON CONFLICT clauses specified", 0); 2627 } 2628 if( pIdx->onError==OE_Default ){ 2629 pIdx->onError = pIndex->onError; 2630 } 2631 } 2632 goto exit_create_index; 2633 } 2634 } 2635 } 2636 2637 /* Link the new Index structure to its table and to the other 2638 ** in-memory database structures. 2639 */ 2640 if( db->init.busy ){ 2641 Index *p; 2642 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 2643 pIndex->zName, strlen(pIndex->zName)+1, pIndex); 2644 if( p ){ 2645 assert( p==pIndex ); /* Malloc must have failed */ 2646 db->mallocFailed = 1; 2647 goto exit_create_index; 2648 } 2649 db->flags |= SQLITE_InternChanges; 2650 if( pTblName!=0 ){ 2651 pIndex->tnum = db->init.newTnum; 2652 } 2653 } 2654 2655 /* If the db->init.busy is 0 then create the index on disk. This 2656 ** involves writing the index into the master table and filling in the 2657 ** index with the current table contents. 2658 ** 2659 ** The db->init.busy is 0 when the user first enters a CREATE INDEX 2660 ** command. db->init.busy is 1 when a database is opened and 2661 ** CREATE INDEX statements are read out of the master table. In 2662 ** the latter case the index already exists on disk, which is why 2663 ** we don't want to recreate it. 2664 ** 2665 ** If pTblName==0 it means this index is generated as a primary key 2666 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table 2667 ** has just been created, it contains no data and the index initialization 2668 ** step can be skipped. 2669 */ 2670 else if( db->init.busy==0 ){ 2671 Vdbe *v; 2672 char *zStmt; 2673 int iMem = ++pParse->nMem; 2674 2675 v = sqlite3GetVdbe(pParse); 2676 if( v==0 ) goto exit_create_index; 2677 2678 2679 /* Create the rootpage for the index 2680 */ 2681 sqlite3BeginWriteOperation(pParse, 1, iDb); 2682 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 2683 2684 /* Gather the complete text of the CREATE INDEX statement into 2685 ** the zStmt variable 2686 */ 2687 if( pStart && pEnd ){ 2688 /* A named index with an explicit CREATE INDEX statement */ 2689 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 2690 onError==OE_None ? "" : " UNIQUE", 2691 pEnd->z - pName->z + 1, 2692 pName->z); 2693 }else{ 2694 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 2695 /* zStmt = sqlite3MPrintf(""); */ 2696 zStmt = 0; 2697 } 2698 2699 /* Add an entry in sqlite_master for this index 2700 */ 2701 sqlite3NestedParse(pParse, 2702 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 2703 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2704 pIndex->zName, 2705 pTab->zName, 2706 iMem, 2707 zStmt 2708 ); 2709 sqlite3_free(zStmt); 2710 2711 /* Fill the index with data and reparse the schema. Code an OP_Expire 2712 ** to invalidate all pre-compiled statements. 2713 */ 2714 if( pTblName ){ 2715 sqlite3RefillIndex(pParse, pIndex, iMem); 2716 sqlite3ChangeCookie(pParse, iDb); 2717 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 2718 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC); 2719 sqlite3VdbeAddOp1(v, OP_Expire, 0); 2720 } 2721 } 2722 2723 /* When adding an index to the list of indices for a table, make 2724 ** sure all indices labeled OE_Replace come after all those labeled 2725 ** OE_Ignore. This is necessary for the correct operation of UPDATE 2726 ** and INSERT. 2727 */ 2728 if( db->init.busy || pTblName==0 ){ 2729 if( onError!=OE_Replace || pTab->pIndex==0 2730 || pTab->pIndex->onError==OE_Replace){ 2731 pIndex->pNext = pTab->pIndex; 2732 pTab->pIndex = pIndex; 2733 }else{ 2734 Index *pOther = pTab->pIndex; 2735 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 2736 pOther = pOther->pNext; 2737 } 2738 pIndex->pNext = pOther->pNext; 2739 pOther->pNext = pIndex; 2740 } 2741 pIndex = 0; 2742 } 2743 2744 /* Clean up before exiting */ 2745 exit_create_index: 2746 if( pIndex ){ 2747 freeIndex(pIndex); 2748 } 2749 sqlite3ExprListDelete(pList); 2750 sqlite3SrcListDelete(pTblName); 2751 sqlite3_free(zName); 2752 return; 2753 } 2754 2755 /* 2756 ** Generate code to make sure the file format number is at least minFormat. 2757 ** The generated code will increase the file format number if necessary. 2758 */ 2759 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ 2760 Vdbe *v; 2761 v = sqlite3GetVdbe(pParse); 2762 if( v ){ 2763 int r1 = sqlite3GetTempReg(pParse); 2764 int r2 = sqlite3GetTempReg(pParse); 2765 int j1; 2766 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1); 2767 sqlite3VdbeUsesBtree(v, iDb); 2768 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2); 2769 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1); 2770 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2); 2771 sqlite3VdbeJumpHere(v, j1); 2772 sqlite3ReleaseTempReg(pParse, r1); 2773 sqlite3ReleaseTempReg(pParse, r2); 2774 } 2775 } 2776 2777 /* 2778 ** Fill the Index.aiRowEst[] array with default information - information 2779 ** to be used when we have not run the ANALYZE command. 2780 ** 2781 ** aiRowEst[0] is suppose to contain the number of elements in the index. 2782 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 2783 ** number of rows in the table that match any particular value of the 2784 ** first column of the index. aiRowEst[2] is an estimate of the number 2785 ** of rows that match any particular combiniation of the first 2 columns 2786 ** of the index. And so forth. It must always be the case that 2787 * 2788 ** aiRowEst[N]<=aiRowEst[N-1] 2789 ** aiRowEst[N]>=1 2790 ** 2791 ** Apart from that, we have little to go on besides intuition as to 2792 ** how aiRowEst[] should be initialized. The numbers generated here 2793 ** are based on typical values found in actual indices. 2794 */ 2795 void sqlite3DefaultRowEst(Index *pIdx){ 2796 unsigned *a = pIdx->aiRowEst; 2797 int i; 2798 assert( a!=0 ); 2799 a[0] = 1000000; 2800 for(i=pIdx->nColumn; i>=5; i--){ 2801 a[i] = 5; 2802 } 2803 while( i>=1 ){ 2804 a[i] = 11 - i; 2805 i--; 2806 } 2807 if( pIdx->onError!=OE_None ){ 2808 a[pIdx->nColumn] = 1; 2809 } 2810 } 2811 2812 /* 2813 ** This routine will drop an existing named index. This routine 2814 ** implements the DROP INDEX statement. 2815 */ 2816 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 2817 Index *pIndex; 2818 Vdbe *v; 2819 sqlite3 *db = pParse->db; 2820 int iDb; 2821 2822 if( pParse->nErr || db->mallocFailed ){ 2823 goto exit_drop_index; 2824 } 2825 assert( pName->nSrc==1 ); 2826 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2827 goto exit_drop_index; 2828 } 2829 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 2830 if( pIndex==0 ){ 2831 if( !ifExists ){ 2832 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 2833 } 2834 pParse->checkSchema = 1; 2835 goto exit_drop_index; 2836 } 2837 if( pIndex->autoIndex ){ 2838 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 2839 "or PRIMARY KEY constraint cannot be dropped", 0); 2840 goto exit_drop_index; 2841 } 2842 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2843 #ifndef SQLITE_OMIT_AUTHORIZATION 2844 { 2845 int code = SQLITE_DROP_INDEX; 2846 Table *pTab = pIndex->pTable; 2847 const char *zDb = db->aDb[iDb].zName; 2848 const char *zTab = SCHEMA_TABLE(iDb); 2849 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 2850 goto exit_drop_index; 2851 } 2852 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 2853 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 2854 goto exit_drop_index; 2855 } 2856 } 2857 #endif 2858 2859 /* Generate code to remove the index and from the master table */ 2860 v = sqlite3GetVdbe(pParse); 2861 if( v ){ 2862 sqlite3BeginWriteOperation(pParse, 1, iDb); 2863 sqlite3NestedParse(pParse, 2864 "DELETE FROM %Q.%s WHERE name=%Q", 2865 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2866 pIndex->zName 2867 ); 2868 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 2869 sqlite3NestedParse(pParse, 2870 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q", 2871 db->aDb[iDb].zName, pIndex->zName 2872 ); 2873 } 2874 sqlite3ChangeCookie(pParse, iDb); 2875 destroyRootPage(pParse, pIndex->tnum, iDb); 2876 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 2877 } 2878 2879 exit_drop_index: 2880 sqlite3SrcListDelete(pName); 2881 } 2882 2883 /* 2884 ** pArray is a pointer to an array of objects. Each object in the 2885 ** array is szEntry bytes in size. This routine allocates a new 2886 ** object on the end of the array. 2887 ** 2888 ** *pnEntry is the number of entries already in use. *pnAlloc is 2889 ** the previously allocated size of the array. initSize is the 2890 ** suggested initial array size allocation. 2891 ** 2892 ** The index of the new entry is returned in *pIdx. 2893 ** 2894 ** This routine returns a pointer to the array of objects. This 2895 ** might be the same as the pArray parameter or it might be a different 2896 ** pointer if the array was resized. 2897 */ 2898 void *sqlite3ArrayAllocate( 2899 sqlite3 *db, /* Connection to notify of malloc failures */ 2900 void *pArray, /* Array of objects. Might be reallocated */ 2901 int szEntry, /* Size of each object in the array */ 2902 int initSize, /* Suggested initial allocation, in elements */ 2903 int *pnEntry, /* Number of objects currently in use */ 2904 int *pnAlloc, /* Current size of the allocation, in elements */ 2905 int *pIdx /* Write the index of a new slot here */ 2906 ){ 2907 char *z; 2908 if( *pnEntry >= *pnAlloc ){ 2909 void *pNew; 2910 int newSize; 2911 newSize = (*pnAlloc)*2 + initSize; 2912 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry); 2913 if( pNew==0 ){ 2914 *pIdx = -1; 2915 return pArray; 2916 } 2917 *pnAlloc = newSize; 2918 pArray = pNew; 2919 } 2920 z = (char*)pArray; 2921 memset(&z[*pnEntry * szEntry], 0, szEntry); 2922 *pIdx = *pnEntry; 2923 ++*pnEntry; 2924 return pArray; 2925 } 2926 2927 /* 2928 ** Append a new element to the given IdList. Create a new IdList if 2929 ** need be. 2930 ** 2931 ** A new IdList is returned, or NULL if malloc() fails. 2932 */ 2933 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 2934 int i; 2935 if( pList==0 ){ 2936 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 2937 if( pList==0 ) return 0; 2938 pList->nAlloc = 0; 2939 } 2940 pList->a = sqlite3ArrayAllocate( 2941 db, 2942 pList->a, 2943 sizeof(pList->a[0]), 2944 5, 2945 &pList->nId, 2946 &pList->nAlloc, 2947 &i 2948 ); 2949 if( i<0 ){ 2950 sqlite3IdListDelete(pList); 2951 return 0; 2952 } 2953 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 2954 return pList; 2955 } 2956 2957 /* 2958 ** Delete an IdList. 2959 */ 2960 void sqlite3IdListDelete(IdList *pList){ 2961 int i; 2962 if( pList==0 ) return; 2963 for(i=0; i<pList->nId; i++){ 2964 sqlite3_free(pList->a[i].zName); 2965 } 2966 sqlite3_free(pList->a); 2967 sqlite3_free(pList); 2968 } 2969 2970 /* 2971 ** Return the index in pList of the identifier named zId. Return -1 2972 ** if not found. 2973 */ 2974 int sqlite3IdListIndex(IdList *pList, const char *zName){ 2975 int i; 2976 if( pList==0 ) return -1; 2977 for(i=0; i<pList->nId; i++){ 2978 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 2979 } 2980 return -1; 2981 } 2982 2983 /* 2984 ** Append a new table name to the given SrcList. Create a new SrcList if 2985 ** need be. A new entry is created in the SrcList even if pToken is NULL. 2986 ** 2987 ** A new SrcList is returned, or NULL if malloc() fails. 2988 ** 2989 ** If pDatabase is not null, it means that the table has an optional 2990 ** database name prefix. Like this: "database.table". The pDatabase 2991 ** points to the table name and the pTable points to the database name. 2992 ** The SrcList.a[].zName field is filled with the table name which might 2993 ** come from pTable (if pDatabase is NULL) or from pDatabase. 2994 ** SrcList.a[].zDatabase is filled with the database name from pTable, 2995 ** or with NULL if no database is specified. 2996 ** 2997 ** In other words, if call like this: 2998 ** 2999 ** sqlite3SrcListAppend(D,A,B,0); 3000 ** 3001 ** Then B is a table name and the database name is unspecified. If called 3002 ** like this: 3003 ** 3004 ** sqlite3SrcListAppend(D,A,B,C); 3005 ** 3006 ** Then C is the table name and B is the database name. 3007 */ 3008 SrcList *sqlite3SrcListAppend( 3009 sqlite3 *db, /* Connection to notify of malloc failures */ 3010 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 3011 Token *pTable, /* Table to append */ 3012 Token *pDatabase /* Database of the table */ 3013 ){ 3014 struct SrcList_item *pItem; 3015 if( pList==0 ){ 3016 pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); 3017 if( pList==0 ) return 0; 3018 pList->nAlloc = 1; 3019 } 3020 if( pList->nSrc>=pList->nAlloc ){ 3021 SrcList *pNew; 3022 pList->nAlloc *= 2; 3023 pNew = sqlite3DbRealloc(db, pList, 3024 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) ); 3025 if( pNew==0 ){ 3026 sqlite3SrcListDelete(pList); 3027 return 0; 3028 } 3029 pList = pNew; 3030 } 3031 pItem = &pList->a[pList->nSrc]; 3032 memset(pItem, 0, sizeof(pList->a[0])); 3033 if( pDatabase && pDatabase->z==0 ){ 3034 pDatabase = 0; 3035 } 3036 if( pDatabase && pTable ){ 3037 Token *pTemp = pDatabase; 3038 pDatabase = pTable; 3039 pTable = pTemp; 3040 } 3041 pItem->zName = sqlite3NameFromToken(db, pTable); 3042 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); 3043 pItem->iCursor = -1; 3044 pItem->isPopulated = 0; 3045 pList->nSrc++; 3046 return pList; 3047 } 3048 3049 /* 3050 ** Assign cursors to all tables in a SrcList 3051 */ 3052 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 3053 int i; 3054 struct SrcList_item *pItem; 3055 assert(pList || pParse->db->mallocFailed ); 3056 if( pList ){ 3057 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 3058 if( pItem->iCursor>=0 ) break; 3059 pItem->iCursor = pParse->nTab++; 3060 if( pItem->pSelect ){ 3061 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 3062 } 3063 } 3064 } 3065 } 3066 3067 /* 3068 ** Delete an entire SrcList including all its substructure. 3069 */ 3070 void sqlite3SrcListDelete(SrcList *pList){ 3071 int i; 3072 struct SrcList_item *pItem; 3073 if( pList==0 ) return; 3074 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 3075 sqlite3_free(pItem->zDatabase); 3076 sqlite3_free(pItem->zName); 3077 sqlite3_free(pItem->zAlias); 3078 sqlite3DeleteTable(pItem->pTab); 3079 sqlite3SelectDelete(pItem->pSelect); 3080 sqlite3ExprDelete(pItem->pOn); 3081 sqlite3IdListDelete(pItem->pUsing); 3082 } 3083 sqlite3_free(pList); 3084 } 3085 3086 /* 3087 ** This routine is called by the parser to add a new term to the 3088 ** end of a growing FROM clause. The "p" parameter is the part of 3089 ** the FROM clause that has already been constructed. "p" is NULL 3090 ** if this is the first term of the FROM clause. pTable and pDatabase 3091 ** are the name of the table and database named in the FROM clause term. 3092 ** pDatabase is NULL if the database name qualifier is missing - the 3093 ** usual case. If the term has a alias, then pAlias points to the 3094 ** alias token. If the term is a subquery, then pSubquery is the 3095 ** SELECT statement that the subquery encodes. The pTable and 3096 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 3097 ** parameters are the content of the ON and USING clauses. 3098 ** 3099 ** Return a new SrcList which encodes is the FROM with the new 3100 ** term added. 3101 */ 3102 SrcList *sqlite3SrcListAppendFromTerm( 3103 Parse *pParse, /* Parsing context */ 3104 SrcList *p, /* The left part of the FROM clause already seen */ 3105 Token *pTable, /* Name of the table to add to the FROM clause */ 3106 Token *pDatabase, /* Name of the database containing pTable */ 3107 Token *pAlias, /* The right-hand side of the AS subexpression */ 3108 Select *pSubquery, /* A subquery used in place of a table name */ 3109 Expr *pOn, /* The ON clause of a join */ 3110 IdList *pUsing /* The USING clause of a join */ 3111 ){ 3112 struct SrcList_item *pItem; 3113 sqlite3 *db = pParse->db; 3114 p = sqlite3SrcListAppend(db, p, pTable, pDatabase); 3115 if( p==0 || p->nSrc==0 ){ 3116 sqlite3ExprDelete(pOn); 3117 sqlite3IdListDelete(pUsing); 3118 sqlite3SelectDelete(pSubquery); 3119 return p; 3120 } 3121 pItem = &p->a[p->nSrc-1]; 3122 if( pAlias && pAlias->n ){ 3123 pItem->zAlias = sqlite3NameFromToken(db, pAlias); 3124 } 3125 pItem->pSelect = pSubquery; 3126 pItem->pOn = pOn; 3127 pItem->pUsing = pUsing; 3128 return p; 3129 } 3130 3131 /* 3132 ** When building up a FROM clause in the parser, the join operator 3133 ** is initially attached to the left operand. But the code generator 3134 ** expects the join operator to be on the right operand. This routine 3135 ** Shifts all join operators from left to right for an entire FROM 3136 ** clause. 3137 ** 3138 ** Example: Suppose the join is like this: 3139 ** 3140 ** A natural cross join B 3141 ** 3142 ** The operator is "natural cross join". The A and B operands are stored 3143 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 3144 ** operator with A. This routine shifts that operator over to B. 3145 */ 3146 void sqlite3SrcListShiftJoinType(SrcList *p){ 3147 if( p && p->a ){ 3148 int i; 3149 for(i=p->nSrc-1; i>0; i--){ 3150 p->a[i].jointype = p->a[i-1].jointype; 3151 } 3152 p->a[0].jointype = 0; 3153 } 3154 } 3155 3156 /* 3157 ** Begin a transaction 3158 */ 3159 void sqlite3BeginTransaction(Parse *pParse, int type){ 3160 sqlite3 *db; 3161 Vdbe *v; 3162 int i; 3163 3164 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 3165 if( pParse->nErr || db->mallocFailed ) return; 3166 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return; 3167 3168 v = sqlite3GetVdbe(pParse); 3169 if( !v ) return; 3170 if( type!=TK_DEFERRED ){ 3171 for(i=0; i<db->nDb; i++){ 3172 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 3173 sqlite3VdbeUsesBtree(v, i); 3174 } 3175 } 3176 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); 3177 } 3178 3179 /* 3180 ** Commit a transaction 3181 */ 3182 void sqlite3CommitTransaction(Parse *pParse){ 3183 sqlite3 *db; 3184 Vdbe *v; 3185 3186 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 3187 if( pParse->nErr || db->mallocFailed ) return; 3188 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return; 3189 3190 v = sqlite3GetVdbe(pParse); 3191 if( v ){ 3192 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); 3193 } 3194 } 3195 3196 /* 3197 ** Rollback a transaction 3198 */ 3199 void sqlite3RollbackTransaction(Parse *pParse){ 3200 sqlite3 *db; 3201 Vdbe *v; 3202 3203 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 3204 if( pParse->nErr || db->mallocFailed ) return; 3205 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return; 3206 3207 v = sqlite3GetVdbe(pParse); 3208 if( v ){ 3209 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 3210 } 3211 } 3212 3213 /* 3214 ** Make sure the TEMP database is open and available for use. Return 3215 ** the number of errors. Leave any error messages in the pParse structure. 3216 */ 3217 int sqlite3OpenTempDatabase(Parse *pParse){ 3218 sqlite3 *db = pParse->db; 3219 if( db->aDb[1].pBt==0 && !pParse->explain ){ 3220 int rc; 3221 static const int flags = 3222 SQLITE_OPEN_READWRITE | 3223 SQLITE_OPEN_CREATE | 3224 SQLITE_OPEN_EXCLUSIVE | 3225 SQLITE_OPEN_DELETEONCLOSE | 3226 SQLITE_OPEN_TEMP_DB; 3227 3228 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, 3229 &db->aDb[1].pBt); 3230 if( rc!=SQLITE_OK ){ 3231 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 3232 "file for storing temporary tables"); 3233 pParse->rc = rc; 3234 return 1; 3235 } 3236 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit ); 3237 assert( db->aDb[1].pSchema ); 3238 } 3239 return 0; 3240 } 3241 3242 /* 3243 ** Generate VDBE code that will verify the schema cookie and start 3244 ** a read-transaction for all named database files. 3245 ** 3246 ** It is important that all schema cookies be verified and all 3247 ** read transactions be started before anything else happens in 3248 ** the VDBE program. But this routine can be called after much other 3249 ** code has been generated. So here is what we do: 3250 ** 3251 ** The first time this routine is called, we code an OP_Goto that 3252 ** will jump to a subroutine at the end of the program. Then we 3253 ** record every database that needs its schema verified in the 3254 ** pParse->cookieMask field. Later, after all other code has been 3255 ** generated, the subroutine that does the cookie verifications and 3256 ** starts the transactions will be coded and the OP_Goto P2 value 3257 ** will be made to point to that subroutine. The generation of the 3258 ** cookie verification subroutine code happens in sqlite3FinishCoding(). 3259 ** 3260 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the 3261 ** schema on any databases. This can be used to position the OP_Goto 3262 ** early in the code, before we know if any database tables will be used. 3263 */ 3264 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 3265 sqlite3 *db; 3266 Vdbe *v; 3267 int mask; 3268 3269 v = sqlite3GetVdbe(pParse); 3270 if( v==0 ) return; /* This only happens if there was a prior error */ 3271 db = pParse->db; 3272 if( pParse->cookieGoto==0 ){ 3273 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; 3274 } 3275 if( iDb>=0 ){ 3276 assert( iDb<db->nDb ); 3277 assert( db->aDb[iDb].pBt!=0 || iDb==1 ); 3278 assert( iDb<SQLITE_MAX_ATTACHED+2 ); 3279 mask = 1<<iDb; 3280 if( (pParse->cookieMask & mask)==0 ){ 3281 pParse->cookieMask |= mask; 3282 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; 3283 if( !OMIT_TEMPDB && iDb==1 ){ 3284 sqlite3OpenTempDatabase(pParse); 3285 } 3286 } 3287 } 3288 } 3289 3290 /* 3291 ** Generate VDBE code that prepares for doing an operation that 3292 ** might change the database. 3293 ** 3294 ** This routine starts a new transaction if we are not already within 3295 ** a transaction. If we are already within a transaction, then a checkpoint 3296 ** is set if the setStatement parameter is true. A checkpoint should 3297 ** be set for operations that might fail (due to a constraint) part of 3298 ** the way through and which will need to undo some writes without having to 3299 ** rollback the whole transaction. For operations where all constraints 3300 ** can be checked before any changes are made to the database, it is never 3301 ** necessary to undo a write and the checkpoint should not be set. 3302 ** 3303 ** Only database iDb and the temp database are made writable by this call. 3304 ** If iDb==0, then the main and temp databases are made writable. If 3305 ** iDb==1 then only the temp database is made writable. If iDb>1 then the 3306 ** specified auxiliary database and the temp database are made writable. 3307 */ 3308 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 3309 Vdbe *v = sqlite3GetVdbe(pParse); 3310 if( v==0 ) return; 3311 sqlite3CodeVerifySchema(pParse, iDb); 3312 pParse->writeMask |= 1<<iDb; 3313 if( setStatement && pParse->nested==0 ){ 3314 sqlite3VdbeAddOp1(v, OP_Statement, iDb); 3315 } 3316 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){ 3317 sqlite3BeginWriteOperation(pParse, setStatement, 1); 3318 } 3319 } 3320 3321 /* 3322 ** Check to see if pIndex uses the collating sequence pColl. Return 3323 ** true if it does and false if it does not. 3324 */ 3325 #ifndef SQLITE_OMIT_REINDEX 3326 static int collationMatch(const char *zColl, Index *pIndex){ 3327 int i; 3328 for(i=0; i<pIndex->nColumn; i++){ 3329 const char *z = pIndex->azColl[i]; 3330 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){ 3331 return 1; 3332 } 3333 } 3334 return 0; 3335 } 3336 #endif 3337 3338 /* 3339 ** Recompute all indices of pTab that use the collating sequence pColl. 3340 ** If pColl==0 then recompute all indices of pTab. 3341 */ 3342 #ifndef SQLITE_OMIT_REINDEX 3343 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 3344 Index *pIndex; /* An index associated with pTab */ 3345 3346 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 3347 if( zColl==0 || collationMatch(zColl, pIndex) ){ 3348 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 3349 sqlite3BeginWriteOperation(pParse, 0, iDb); 3350 sqlite3RefillIndex(pParse, pIndex, -1); 3351 } 3352 } 3353 } 3354 #endif 3355 3356 /* 3357 ** Recompute all indices of all tables in all databases where the 3358 ** indices use the collating sequence pColl. If pColl==0 then recompute 3359 ** all indices everywhere. 3360 */ 3361 #ifndef SQLITE_OMIT_REINDEX 3362 static void reindexDatabases(Parse *pParse, char const *zColl){ 3363 Db *pDb; /* A single database */ 3364 int iDb; /* The database index number */ 3365 sqlite3 *db = pParse->db; /* The database connection */ 3366 HashElem *k; /* For looping over tables in pDb */ 3367 Table *pTab; /* A table in the database */ 3368 3369 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 3370 assert( pDb!=0 ); 3371 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 3372 pTab = (Table*)sqliteHashData(k); 3373 reindexTable(pParse, pTab, zColl); 3374 } 3375 } 3376 } 3377 #endif 3378 3379 /* 3380 ** Generate code for the REINDEX command. 3381 ** 3382 ** REINDEX -- 1 3383 ** REINDEX <collation> -- 2 3384 ** REINDEX ?<database>.?<tablename> -- 3 3385 ** REINDEX ?<database>.?<indexname> -- 4 3386 ** 3387 ** Form 1 causes all indices in all attached databases to be rebuilt. 3388 ** Form 2 rebuilds all indices in all databases that use the named 3389 ** collating function. Forms 3 and 4 rebuild the named index or all 3390 ** indices associated with the named table. 3391 */ 3392 #ifndef SQLITE_OMIT_REINDEX 3393 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 3394 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 3395 char *z; /* Name of a table or index */ 3396 const char *zDb; /* Name of the database */ 3397 Table *pTab; /* A table in the database */ 3398 Index *pIndex; /* An index associated with pTab */ 3399 int iDb; /* The database index number */ 3400 sqlite3 *db = pParse->db; /* The database connection */ 3401 Token *pObjName; /* Name of the table or index to be reindexed */ 3402 3403 /* Read the database schema. If an error occurs, leave an error message 3404 ** and code in pParse and return NULL. */ 3405 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3406 return; 3407 } 3408 3409 if( pName1==0 || pName1->z==0 ){ 3410 reindexDatabases(pParse, 0); 3411 return; 3412 }else if( pName2==0 || pName2->z==0 ){ 3413 char *zColl; 3414 assert( pName1->z ); 3415 zColl = sqlite3NameFromToken(pParse->db, pName1); 3416 if( !zColl ) return; 3417 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0); 3418 if( pColl ){ 3419 if( zColl ){ 3420 reindexDatabases(pParse, zColl); 3421 sqlite3_free(zColl); 3422 } 3423 return; 3424 } 3425 sqlite3_free(zColl); 3426 } 3427 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 3428 if( iDb<0 ) return; 3429 z = sqlite3NameFromToken(db, pObjName); 3430 if( z==0 ) return; 3431 zDb = db->aDb[iDb].zName; 3432 pTab = sqlite3FindTable(db, z, zDb); 3433 if( pTab ){ 3434 reindexTable(pParse, pTab, 0); 3435 sqlite3_free(z); 3436 return; 3437 } 3438 pIndex = sqlite3FindIndex(db, z, zDb); 3439 sqlite3_free(z); 3440 if( pIndex ){ 3441 sqlite3BeginWriteOperation(pParse, 0, iDb); 3442 sqlite3RefillIndex(pParse, pIndex, -1); 3443 return; 3444 } 3445 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 3446 } 3447 #endif 3448 3449 /* 3450 ** Return a dynamicly allocated KeyInfo structure that can be used 3451 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx. 3452 ** 3453 ** If successful, a pointer to the new structure is returned. In this case 3454 ** the caller is responsible for calling sqlite3_free() on the returned 3455 ** pointer. If an error occurs (out of memory or missing collation 3456 ** sequence), NULL is returned and the state of pParse updated to reflect 3457 ** the error. 3458 */ 3459 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ 3460 int i; 3461 int nCol = pIdx->nColumn; 3462 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol; 3463 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes); 3464 3465 if( pKey ){ 3466 pKey->db = pParse->db; 3467 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]); 3468 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) ); 3469 for(i=0; i<nCol; i++){ 3470 char *zColl = pIdx->azColl[i]; 3471 assert( zColl ); 3472 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1); 3473 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 3474 } 3475 pKey->nField = nCol; 3476 } 3477 3478 if( pParse->nErr ){ 3479 sqlite3_free(pKey); 3480 pKey = 0; 3481 } 3482 return pKey; 3483 } 3484