1.1 --- a/extensions/sqlite/sqlite-source/build.c Fri Jul 11 06:51:21 2008 +0000
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,3409 +0,0 @@
1.4 -/*
1.5 -** 2001 September 15
1.6 -**
1.7 -** The author disclaims copyright to this source code. In place of
1.8 -** a legal notice, here is a blessing:
1.9 -**
1.10 -** May you do good and not evil.
1.11 -** May you find forgiveness for yourself and forgive others.
1.12 -** May you share freely, never taking more than you give.
1.13 -**
1.14 -*************************************************************************
1.15 -** This file contains C code routines that are called by the SQLite parser
1.16 -** when syntax rules are reduced. The routines in this file handle the
1.17 -** following kinds of SQL syntax:
1.18 -**
1.19 -** CREATE TABLE
1.20 -** DROP TABLE
1.21 -** CREATE INDEX
1.22 -** DROP INDEX
1.23 -** creating ID lists
1.24 -** BEGIN TRANSACTION
1.25 -** COMMIT
1.26 -** ROLLBACK
1.27 -**
1.28 -** $Id$
1.29 -*/
1.30 -#include "sqliteInt.h"
1.31 -#include <ctype.h>
1.32 -
1.33 -/*
1.34 -** This routine is called when a new SQL statement is beginning to
1.35 -** be parsed. Initialize the pParse structure as needed.
1.36 -*/
1.37 -void sqlite3BeginParse(Parse *pParse, int explainFlag){
1.38 - pParse->explain = explainFlag;
1.39 - pParse->nVar = 0;
1.40 -}
1.41 -
1.42 -#ifndef SQLITE_OMIT_SHARED_CACHE
1.43 -/*
1.44 -** The TableLock structure is only used by the sqlite3TableLock() and
1.45 -** codeTableLocks() functions.
1.46 -*/
1.47 -struct TableLock {
1.48 - int iDb; /* The database containing the table to be locked */
1.49 - int iTab; /* The root page of the table to be locked */
1.50 - u8 isWriteLock; /* True for write lock. False for a read lock */
1.51 - const char *zName; /* Name of the table */
1.52 -};
1.53 -
1.54 -/*
1.55 -** Record the fact that we want to lock a table at run-time.
1.56 -**
1.57 -** The table to be locked has root page iTab and is found in database iDb.
1.58 -** A read or a write lock can be taken depending on isWritelock.
1.59 -**
1.60 -** This routine just records the fact that the lock is desired. The
1.61 -** code to make the lock occur is generated by a later call to
1.62 -** codeTableLocks() which occurs during sqlite3FinishCoding().
1.63 -*/
1.64 -void sqlite3TableLock(
1.65 - Parse *pParse, /* Parsing context */
1.66 - int iDb, /* Index of the database containing the table to lock */
1.67 - int iTab, /* Root page number of the table to be locked */
1.68 - u8 isWriteLock, /* True for a write lock */
1.69 - const char *zName /* Name of the table to be locked */
1.70 -){
1.71 - int i;
1.72 - int nBytes;
1.73 - TableLock *p;
1.74 -
1.75 - if( iDb<0 ){
1.76 - return;
1.77 - }
1.78 -
1.79 - for(i=0; i<pParse->nTableLock; i++){
1.80 - p = &pParse->aTableLock[i];
1.81 - if( p->iDb==iDb && p->iTab==iTab ){
1.82 - p->isWriteLock = (p->isWriteLock || isWriteLock);
1.83 - return;
1.84 - }
1.85 - }
1.86 -
1.87 - nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
1.88 - pParse->aTableLock =
1.89 - sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
1.90 - if( pParse->aTableLock ){
1.91 - p = &pParse->aTableLock[pParse->nTableLock++];
1.92 - p->iDb = iDb;
1.93 - p->iTab = iTab;
1.94 - p->isWriteLock = isWriteLock;
1.95 - p->zName = zName;
1.96 - }else{
1.97 - pParse->nTableLock = 0;
1.98 - pParse->db->mallocFailed = 1;
1.99 - }
1.100 -}
1.101 -
1.102 -/*
1.103 -** Code an OP_TableLock instruction for each table locked by the
1.104 -** statement (configured by calls to sqlite3TableLock()).
1.105 -*/
1.106 -static void codeTableLocks(Parse *pParse){
1.107 - int i;
1.108 - Vdbe *pVdbe;
1.109 -
1.110 - if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
1.111 - return;
1.112 - }
1.113 -
1.114 - for(i=0; i<pParse->nTableLock; i++){
1.115 - TableLock *p = &pParse->aTableLock[i];
1.116 - int p1 = p->iDb;
1.117 - if( p->isWriteLock ){
1.118 - p1 = -1*(p1+1);
1.119 - }
1.120 - sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
1.121 - }
1.122 -}
1.123 -#else
1.124 - #define codeTableLocks(x)
1.125 -#endif
1.126 -
1.127 -/*
1.128 -** This routine is called after a single SQL statement has been
1.129 -** parsed and a VDBE program to execute that statement has been
1.130 -** prepared. This routine puts the finishing touches on the
1.131 -** VDBE program and resets the pParse structure for the next
1.132 -** parse.
1.133 -**
1.134 -** Note that if an error occurred, it might be the case that
1.135 -** no VDBE code was generated.
1.136 -*/
1.137 -void sqlite3FinishCoding(Parse *pParse){
1.138 - sqlite3 *db;
1.139 - Vdbe *v;
1.140 -
1.141 - db = pParse->db;
1.142 - if( db->mallocFailed ) return;
1.143 - if( pParse->nested ) return;
1.144 - if( !pParse->pVdbe ){
1.145 - if( pParse->rc==SQLITE_OK && pParse->nErr ){
1.146 - pParse->rc = SQLITE_ERROR;
1.147 - return;
1.148 - }
1.149 - }
1.150 -
1.151 - /* Begin by generating some termination code at the end of the
1.152 - ** vdbe program
1.153 - */
1.154 - v = sqlite3GetVdbe(pParse);
1.155 - if( v ){
1.156 - sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
1.157 -
1.158 - /* The cookie mask contains one bit for each database file open.
1.159 - ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
1.160 - ** set for each database that is used. Generate code to start a
1.161 - ** transaction on each used database and to verify the schema cookie
1.162 - ** on each used database.
1.163 - */
1.164 - if( pParse->cookieGoto>0 ){
1.165 - u32 mask;
1.166 - int iDb;
1.167 - sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
1.168 - for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
1.169 - if( (mask & pParse->cookieMask)==0 ) continue;
1.170 - sqlite3VdbeUsesBtree(v, iDb);
1.171 - sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
1.172 - sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
1.173 - }
1.174 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.175 - if( pParse->pVirtualLock ){
1.176 - char *vtab = (char *)pParse->pVirtualLock->pVtab;
1.177 - sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB);
1.178 - }
1.179 -#endif
1.180 -
1.181 - /* Once all the cookies have been verified and transactions opened,
1.182 - ** obtain the required table-locks. This is a no-op unless the
1.183 - ** shared-cache feature is enabled.
1.184 - */
1.185 - codeTableLocks(pParse);
1.186 - sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
1.187 - }
1.188 -
1.189 -#ifndef SQLITE_OMIT_TRACE
1.190 - /* Add a No-op that contains the complete text of the compiled SQL
1.191 - ** statement as its P3 argument. This does not change the functionality
1.192 - ** of the program.
1.193 - **
1.194 - ** This is used to implement sqlite3_trace().
1.195 - */
1.196 - sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
1.197 -#endif /* SQLITE_OMIT_TRACE */
1.198 - }
1.199 -
1.200 -
1.201 - /* Get the VDBE program ready for execution
1.202 - */
1.203 - if( v && pParse->nErr==0 && !db->mallocFailed ){
1.204 -#ifdef SQLITE_DEBUG
1.205 - FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
1.206 - sqlite3VdbeTrace(v, trace);
1.207 -#endif
1.208 - sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
1.209 - pParse->nTab+3, pParse->explain);
1.210 - pParse->rc = SQLITE_DONE;
1.211 - pParse->colNamesSet = 0;
1.212 - }else if( pParse->rc==SQLITE_OK ){
1.213 - pParse->rc = SQLITE_ERROR;
1.214 - }
1.215 - pParse->nTab = 0;
1.216 - pParse->nMem = 0;
1.217 - pParse->nSet = 0;
1.218 - pParse->nVar = 0;
1.219 - pParse->cookieMask = 0;
1.220 - pParse->cookieGoto = 0;
1.221 -}
1.222 -
1.223 -/*
1.224 -** Run the parser and code generator recursively in order to generate
1.225 -** code for the SQL statement given onto the end of the pParse context
1.226 -** currently under construction. When the parser is run recursively
1.227 -** this way, the final OP_Halt is not appended and other initialization
1.228 -** and finalization steps are omitted because those are handling by the
1.229 -** outermost parser.
1.230 -**
1.231 -** Not everything is nestable. This facility is designed to permit
1.232 -** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
1.233 -** care if you decide to try to use this routine for some other purposes.
1.234 -*/
1.235 -void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
1.236 - va_list ap;
1.237 - char *zSql;
1.238 -# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
1.239 - char saveBuf[SAVE_SZ];
1.240 -
1.241 - if( pParse->nErr ) return;
1.242 - assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
1.243 - va_start(ap, zFormat);
1.244 - zSql = sqlite3VMPrintf(pParse->db, zFormat, ap);
1.245 - va_end(ap);
1.246 - if( zSql==0 ){
1.247 - pParse->db->mallocFailed = 1;
1.248 - return; /* A malloc must have failed */
1.249 - }
1.250 - pParse->nested++;
1.251 - memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
1.252 - memset(&pParse->nVar, 0, SAVE_SZ);
1.253 - sqlite3RunParser(pParse, zSql, 0);
1.254 - sqlite3_free(zSql);
1.255 - memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
1.256 - pParse->nested--;
1.257 -}
1.258 -
1.259 -/*
1.260 -** Locate the in-memory structure that describes a particular database
1.261 -** table given the name of that table and (optionally) the name of the
1.262 -** database containing the table. Return NULL if not found.
1.263 -**
1.264 -** If zDatabase is 0, all databases are searched for the table and the
1.265 -** first matching table is returned. (No checking for duplicate table
1.266 -** names is done.) The search order is TEMP first, then MAIN, then any
1.267 -** auxiliary databases added using the ATTACH command.
1.268 -**
1.269 -** See also sqlite3LocateTable().
1.270 -*/
1.271 -Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
1.272 - Table *p = 0;
1.273 - int i;
1.274 - assert( zName!=0 );
1.275 - for(i=OMIT_TEMPDB; i<db->nDb; i++){
1.276 - int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
1.277 - if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
1.278 - p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
1.279 - if( p ) break;
1.280 - }
1.281 - return p;
1.282 -}
1.283 -
1.284 -/*
1.285 -** Locate the in-memory structure that describes a particular database
1.286 -** table given the name of that table and (optionally) the name of the
1.287 -** database containing the table. Return NULL if not found. Also leave an
1.288 -** error message in pParse->zErrMsg.
1.289 -**
1.290 -** The difference between this routine and sqlite3FindTable() is that this
1.291 -** routine leaves an error message in pParse->zErrMsg where
1.292 -** sqlite3FindTable() does not.
1.293 -*/
1.294 -Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
1.295 - Table *p;
1.296 -
1.297 - /* Read the database schema. If an error occurs, leave an error message
1.298 - ** and code in pParse and return NULL. */
1.299 - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1.300 - return 0;
1.301 - }
1.302 -
1.303 - p = sqlite3FindTable(pParse->db, zName, zDbase);
1.304 - if( p==0 ){
1.305 - if( zDbase ){
1.306 - sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
1.307 - }else{
1.308 - sqlite3ErrorMsg(pParse, "no such table: %s", zName);
1.309 - }
1.310 - pParse->checkSchema = 1;
1.311 - }
1.312 - return p;
1.313 -}
1.314 -
1.315 -/*
1.316 -** Locate the in-memory structure that describes
1.317 -** a particular index given the name of that index
1.318 -** and the name of the database that contains the index.
1.319 -** Return NULL if not found.
1.320 -**
1.321 -** If zDatabase is 0, all databases are searched for the
1.322 -** table and the first matching index is returned. (No checking
1.323 -** for duplicate index names is done.) The search order is
1.324 -** TEMP first, then MAIN, then any auxiliary databases added
1.325 -** using the ATTACH command.
1.326 -*/
1.327 -Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
1.328 - Index *p = 0;
1.329 - int i;
1.330 - for(i=OMIT_TEMPDB; i<db->nDb; i++){
1.331 - int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
1.332 - Schema *pSchema = db->aDb[j].pSchema;
1.333 - if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
1.334 - assert( pSchema || (j==1 && !db->aDb[1].pBt) );
1.335 - if( pSchema ){
1.336 - p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
1.337 - }
1.338 - if( p ) break;
1.339 - }
1.340 - return p;
1.341 -}
1.342 -
1.343 -/*
1.344 -** Reclaim the memory used by an index
1.345 -*/
1.346 -static void freeIndex(Index *p){
1.347 - sqlite3_free(p->zColAff);
1.348 - sqlite3_free(p);
1.349 -}
1.350 -
1.351 -/*
1.352 -** Remove the given index from the index hash table, and free
1.353 -** its memory structures.
1.354 -**
1.355 -** The index is removed from the database hash tables but
1.356 -** it is not unlinked from the Table that it indexes.
1.357 -** Unlinking from the Table must be done by the calling function.
1.358 -*/
1.359 -static void sqliteDeleteIndex(Index *p){
1.360 - Index *pOld;
1.361 - const char *zName = p->zName;
1.362 -
1.363 - pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
1.364 - assert( pOld==0 || pOld==p );
1.365 - freeIndex(p);
1.366 -}
1.367 -
1.368 -/*
1.369 -** For the index called zIdxName which is found in the database iDb,
1.370 -** unlike that index from its Table then remove the index from
1.371 -** the index hash table and free all memory structures associated
1.372 -** with the index.
1.373 -*/
1.374 -void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
1.375 - Index *pIndex;
1.376 - int len;
1.377 - Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
1.378 -
1.379 - len = strlen(zIdxName);
1.380 - pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
1.381 - if( pIndex ){
1.382 - if( pIndex->pTable->pIndex==pIndex ){
1.383 - pIndex->pTable->pIndex = pIndex->pNext;
1.384 - }else{
1.385 - Index *p;
1.386 - for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
1.387 - if( p && p->pNext==pIndex ){
1.388 - p->pNext = pIndex->pNext;
1.389 - }
1.390 - }
1.391 - freeIndex(pIndex);
1.392 - }
1.393 - db->flags |= SQLITE_InternChanges;
1.394 -}
1.395 -
1.396 -/*
1.397 -** Erase all schema information from the in-memory hash tables of
1.398 -** a single database. This routine is called to reclaim memory
1.399 -** before the database closes. It is also called during a rollback
1.400 -** if there were schema changes during the transaction or if a
1.401 -** schema-cookie mismatch occurs.
1.402 -**
1.403 -** If iDb<=0 then reset the internal schema tables for all database
1.404 -** files. If iDb>=2 then reset the internal schema for only the
1.405 -** single file indicated.
1.406 -*/
1.407 -void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
1.408 - int i, j;
1.409 -
1.410 - assert( iDb>=0 && iDb<db->nDb );
1.411 - for(i=iDb; i<db->nDb; i++){
1.412 - Db *pDb = &db->aDb[i];
1.413 - if( pDb->pSchema ){
1.414 - sqlite3SchemaFree(pDb->pSchema);
1.415 - }
1.416 - if( iDb>0 ) return;
1.417 - }
1.418 - assert( iDb==0 );
1.419 - db->flags &= ~SQLITE_InternChanges;
1.420 -
1.421 - /* If one or more of the auxiliary database files has been closed,
1.422 - ** then remove them from the auxiliary database list. We take the
1.423 - ** opportunity to do this here since we have just deleted all of the
1.424 - ** schema hash tables and therefore do not have to make any changes
1.425 - ** to any of those tables.
1.426 - */
1.427 - for(i=0; i<db->nDb; i++){
1.428 - struct Db *pDb = &db->aDb[i];
1.429 - if( pDb->pBt==0 ){
1.430 - if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
1.431 - pDb->pAux = 0;
1.432 - }
1.433 - }
1.434 - for(i=j=2; i<db->nDb; i++){
1.435 - struct Db *pDb = &db->aDb[i];
1.436 - if( pDb->pBt==0 ){
1.437 - sqlite3_free(pDb->zName);
1.438 - pDb->zName = 0;
1.439 - continue;
1.440 - }
1.441 - if( j<i ){
1.442 - db->aDb[j] = db->aDb[i];
1.443 - }
1.444 - j++;
1.445 - }
1.446 - memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
1.447 - db->nDb = j;
1.448 - if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
1.449 - memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
1.450 - sqlite3_free(db->aDb);
1.451 - db->aDb = db->aDbStatic;
1.452 - }
1.453 -}
1.454 -
1.455 -/*
1.456 -** This routine is called when a commit occurs.
1.457 -*/
1.458 -void sqlite3CommitInternalChanges(sqlite3 *db){
1.459 - db->flags &= ~SQLITE_InternChanges;
1.460 -}
1.461 -
1.462 -/*
1.463 -** Clear the column names from a table or view.
1.464 -*/
1.465 -static void sqliteResetColumnNames(Table *pTable){
1.466 - int i;
1.467 - Column *pCol;
1.468 - assert( pTable!=0 );
1.469 - if( (pCol = pTable->aCol)!=0 ){
1.470 - for(i=0; i<pTable->nCol; i++, pCol++){
1.471 - sqlite3_free(pCol->zName);
1.472 - sqlite3ExprDelete(pCol->pDflt);
1.473 - sqlite3_free(pCol->zType);
1.474 - sqlite3_free(pCol->zColl);
1.475 - }
1.476 - sqlite3_free(pTable->aCol);
1.477 - }
1.478 - pTable->aCol = 0;
1.479 - pTable->nCol = 0;
1.480 -}
1.481 -
1.482 -/*
1.483 -** Remove the memory data structures associated with the given
1.484 -** Table. No changes are made to disk by this routine.
1.485 -**
1.486 -** This routine just deletes the data structure. It does not unlink
1.487 -** the table data structure from the hash table. Nor does it remove
1.488 -** foreign keys from the sqlite.aFKey hash table. But it does destroy
1.489 -** memory structures of the indices and foreign keys associated with
1.490 -** the table.
1.491 -*/
1.492 -void sqlite3DeleteTable(Table *pTable){
1.493 - Index *pIndex, *pNext;
1.494 - FKey *pFKey, *pNextFKey;
1.495 -
1.496 - if( pTable==0 ) return;
1.497 -
1.498 - /* Do not delete the table until the reference count reaches zero. */
1.499 - pTable->nRef--;
1.500 - if( pTable->nRef>0 ){
1.501 - return;
1.502 - }
1.503 - assert( pTable->nRef==0 );
1.504 -
1.505 - /* Delete all indices associated with this table
1.506 - */
1.507 - for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
1.508 - pNext = pIndex->pNext;
1.509 - assert( pIndex->pSchema==pTable->pSchema );
1.510 - sqliteDeleteIndex(pIndex);
1.511 - }
1.512 -
1.513 -#ifndef SQLITE_OMIT_FOREIGN_KEY
1.514 - /* Delete all foreign keys associated with this table. The keys
1.515 - ** should have already been unlinked from the pSchema->aFKey hash table
1.516 - */
1.517 - for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
1.518 - pNextFKey = pFKey->pNextFrom;
1.519 - assert( sqlite3HashFind(&pTable->pSchema->aFKey,
1.520 - pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
1.521 - sqlite3_free(pFKey);
1.522 - }
1.523 -#endif
1.524 -
1.525 - /* Delete the Table structure itself.
1.526 - */
1.527 - sqliteResetColumnNames(pTable);
1.528 - sqlite3_free(pTable->zName);
1.529 - sqlite3_free(pTable->zColAff);
1.530 - sqlite3SelectDelete(pTable->pSelect);
1.531 -#ifndef SQLITE_OMIT_CHECK
1.532 - sqlite3ExprDelete(pTable->pCheck);
1.533 -#endif
1.534 - sqlite3VtabClear(pTable);
1.535 - sqlite3_free(pTable);
1.536 -}
1.537 -
1.538 -/*
1.539 -** Unlink the given table from the hash tables and the delete the
1.540 -** table structure with all its indices and foreign keys.
1.541 -*/
1.542 -void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
1.543 - Table *p;
1.544 - FKey *pF1, *pF2;
1.545 - Db *pDb;
1.546 -
1.547 - assert( db!=0 );
1.548 - assert( iDb>=0 && iDb<db->nDb );
1.549 - assert( zTabName && zTabName[0] );
1.550 - pDb = &db->aDb[iDb];
1.551 - p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
1.552 - if( p ){
1.553 -#ifndef SQLITE_OMIT_FOREIGN_KEY
1.554 - for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
1.555 - int nTo = strlen(pF1->zTo) + 1;
1.556 - pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
1.557 - if( pF2==pF1 ){
1.558 - sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
1.559 - }else{
1.560 - while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
1.561 - if( pF2 ){
1.562 - pF2->pNextTo = pF1->pNextTo;
1.563 - }
1.564 - }
1.565 - }
1.566 -#endif
1.567 - sqlite3DeleteTable(p);
1.568 - }
1.569 - db->flags |= SQLITE_InternChanges;
1.570 -}
1.571 -
1.572 -/*
1.573 -** Given a token, return a string that consists of the text of that
1.574 -** token with any quotations removed. Space to hold the returned string
1.575 -** is obtained from sqliteMalloc() and must be freed by the calling
1.576 -** function.
1.577 -**
1.578 -** Tokens are often just pointers into the original SQL text and so
1.579 -** are not \000 terminated and are not persistent. The returned string
1.580 -** is \000 terminated and is persistent.
1.581 -*/
1.582 -char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
1.583 - char *zName;
1.584 - if( pName ){
1.585 - zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
1.586 - sqlite3Dequote(zName);
1.587 - }else{
1.588 - zName = 0;
1.589 - }
1.590 - return zName;
1.591 -}
1.592 -
1.593 -/*
1.594 -** Open the sqlite_master table stored in database number iDb for
1.595 -** writing. The table is opened using cursor 0.
1.596 -*/
1.597 -void sqlite3OpenMasterTable(Parse *p, int iDb){
1.598 - Vdbe *v = sqlite3GetVdbe(p);
1.599 - sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
1.600 - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1.601 - sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
1.602 - sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
1.603 -}
1.604 -
1.605 -/*
1.606 -** The token *pName contains the name of a database (either "main" or
1.607 -** "temp" or the name of an attached db). This routine returns the
1.608 -** index of the named database in db->aDb[], or -1 if the named db
1.609 -** does not exist.
1.610 -*/
1.611 -int sqlite3FindDb(sqlite3 *db, Token *pName){
1.612 - int i = -1; /* Database number */
1.613 - int n; /* Number of characters in the name */
1.614 - Db *pDb; /* A database whose name space is being searched */
1.615 - char *zName; /* Name we are searching for */
1.616 -
1.617 - zName = sqlite3NameFromToken(db, pName);
1.618 - if( zName ){
1.619 - n = strlen(zName);
1.620 - for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
1.621 - if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
1.622 - 0==sqlite3StrICmp(pDb->zName, zName) ){
1.623 - break;
1.624 - }
1.625 - }
1.626 - sqlite3_free(zName);
1.627 - }
1.628 - return i;
1.629 -}
1.630 -
1.631 -/* The table or view or trigger name is passed to this routine via tokens
1.632 -** pName1 and pName2. If the table name was fully qualified, for example:
1.633 -**
1.634 -** CREATE TABLE xxx.yyy (...);
1.635 -**
1.636 -** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
1.637 -** the table name is not fully qualified, i.e.:
1.638 -**
1.639 -** CREATE TABLE yyy(...);
1.640 -**
1.641 -** Then pName1 is set to "yyy" and pName2 is "".
1.642 -**
1.643 -** This routine sets the *ppUnqual pointer to point at the token (pName1 or
1.644 -** pName2) that stores the unqualified table name. The index of the
1.645 -** database "xxx" is returned.
1.646 -*/
1.647 -int sqlite3TwoPartName(
1.648 - Parse *pParse, /* Parsing and code generating context */
1.649 - Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
1.650 - Token *pName2, /* The "yyy" in the name "xxx.yyy" */
1.651 - Token **pUnqual /* Write the unqualified object name here */
1.652 -){
1.653 - int iDb; /* Database holding the object */
1.654 - sqlite3 *db = pParse->db;
1.655 -
1.656 - if( pName2 && pName2->n>0 ){
1.657 - assert( !db->init.busy );
1.658 - *pUnqual = pName2;
1.659 - iDb = sqlite3FindDb(db, pName1);
1.660 - if( iDb<0 ){
1.661 - sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
1.662 - pParse->nErr++;
1.663 - return -1;
1.664 - }
1.665 - }else{
1.666 - assert( db->init.iDb==0 || db->init.busy );
1.667 - iDb = db->init.iDb;
1.668 - *pUnqual = pName1;
1.669 - }
1.670 - return iDb;
1.671 -}
1.672 -
1.673 -/*
1.674 -** This routine is used to check if the UTF-8 string zName is a legal
1.675 -** unqualified name for a new schema object (table, index, view or
1.676 -** trigger). All names are legal except those that begin with the string
1.677 -** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
1.678 -** is reserved for internal use.
1.679 -*/
1.680 -int sqlite3CheckObjectName(Parse *pParse, const char *zName){
1.681 - if( !pParse->db->init.busy && pParse->nested==0
1.682 - && (pParse->db->flags & SQLITE_WriteSchema)==0
1.683 - && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
1.684 - sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
1.685 - return SQLITE_ERROR;
1.686 - }
1.687 - return SQLITE_OK;
1.688 -}
1.689 -
1.690 -/*
1.691 -** Begin constructing a new table representation in memory. This is
1.692 -** the first of several action routines that get called in response
1.693 -** to a CREATE TABLE statement. In particular, this routine is called
1.694 -** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
1.695 -** flag is true if the table should be stored in the auxiliary database
1.696 -** file instead of in the main database file. This is normally the case
1.697 -** when the "TEMP" or "TEMPORARY" keyword occurs in between
1.698 -** CREATE and TABLE.
1.699 -**
1.700 -** The new table record is initialized and put in pParse->pNewTable.
1.701 -** As more of the CREATE TABLE statement is parsed, additional action
1.702 -** routines will be called to add more information to this record.
1.703 -** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
1.704 -** is called to complete the construction of the new table record.
1.705 -*/
1.706 -void sqlite3StartTable(
1.707 - Parse *pParse, /* Parser context */
1.708 - Token *pName1, /* First part of the name of the table or view */
1.709 - Token *pName2, /* Second part of the name of the table or view */
1.710 - int isTemp, /* True if this is a TEMP table */
1.711 - int isView, /* True if this is a VIEW */
1.712 - int isVirtual, /* True if this is a VIRTUAL table */
1.713 - int noErr /* Do nothing if table already exists */
1.714 -){
1.715 - Table *pTable;
1.716 - char *zName = 0; /* The name of the new table */
1.717 - sqlite3 *db = pParse->db;
1.718 - Vdbe *v;
1.719 - int iDb; /* Database number to create the table in */
1.720 - Token *pName; /* Unqualified name of the table to create */
1.721 -
1.722 - /* The table or view name to create is passed to this routine via tokens
1.723 - ** pName1 and pName2. If the table name was fully qualified, for example:
1.724 - **
1.725 - ** CREATE TABLE xxx.yyy (...);
1.726 - **
1.727 - ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
1.728 - ** the table name is not fully qualified, i.e.:
1.729 - **
1.730 - ** CREATE TABLE yyy(...);
1.731 - **
1.732 - ** Then pName1 is set to "yyy" and pName2 is "".
1.733 - **
1.734 - ** The call below sets the pName pointer to point at the token (pName1 or
1.735 - ** pName2) that stores the unqualified table name. The variable iDb is
1.736 - ** set to the index of the database that the table or view is to be
1.737 - ** created in.
1.738 - */
1.739 - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1.740 - if( iDb<0 ) return;
1.741 - if( !OMIT_TEMPDB && isTemp && iDb>1 ){
1.742 - /* If creating a temp table, the name may not be qualified */
1.743 - sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
1.744 - return;
1.745 - }
1.746 - if( !OMIT_TEMPDB && isTemp ) iDb = 1;
1.747 -
1.748 - pParse->sNameToken = *pName;
1.749 - zName = sqlite3NameFromToken(db, pName);
1.750 - if( zName==0 ) return;
1.751 - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
1.752 - goto begin_table_error;
1.753 - }
1.754 - if( db->init.iDb==1 ) isTemp = 1;
1.755 -#ifndef SQLITE_OMIT_AUTHORIZATION
1.756 - assert( (isTemp & 1)==isTemp );
1.757 - {
1.758 - int code;
1.759 - char *zDb = db->aDb[iDb].zName;
1.760 - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1.761 - goto begin_table_error;
1.762 - }
1.763 - if( isView ){
1.764 - if( !OMIT_TEMPDB && isTemp ){
1.765 - code = SQLITE_CREATE_TEMP_VIEW;
1.766 - }else{
1.767 - code = SQLITE_CREATE_VIEW;
1.768 - }
1.769 - }else{
1.770 - if( !OMIT_TEMPDB && isTemp ){
1.771 - code = SQLITE_CREATE_TEMP_TABLE;
1.772 - }else{
1.773 - code = SQLITE_CREATE_TABLE;
1.774 - }
1.775 - }
1.776 - if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
1.777 - goto begin_table_error;
1.778 - }
1.779 - }
1.780 -#endif
1.781 -
1.782 - /* Make sure the new table name does not collide with an existing
1.783 - ** index or table name in the same database. Issue an error message if
1.784 - ** it does. The exception is if the statement being parsed was passed
1.785 - ** to an sqlite3_declare_vtab() call. In that case only the column names
1.786 - ** and types will be used, so there is no need to test for namespace
1.787 - ** collisions.
1.788 - */
1.789 - if( !IN_DECLARE_VTAB ){
1.790 - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1.791 - goto begin_table_error;
1.792 - }
1.793 - pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
1.794 - if( pTable ){
1.795 - if( !noErr ){
1.796 - sqlite3ErrorMsg(pParse, "table %T already exists", pName);
1.797 - }
1.798 - goto begin_table_error;
1.799 - }
1.800 - if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
1.801 - sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
1.802 - goto begin_table_error;
1.803 - }
1.804 - }
1.805 -
1.806 - pTable = sqlite3DbMallocZero(db, sizeof(Table));
1.807 - if( pTable==0 ){
1.808 - db->mallocFailed = 1;
1.809 - pParse->rc = SQLITE_NOMEM;
1.810 - pParse->nErr++;
1.811 - goto begin_table_error;
1.812 - }
1.813 - pTable->zName = zName;
1.814 - pTable->iPKey = -1;
1.815 - pTable->pSchema = db->aDb[iDb].pSchema;
1.816 - pTable->nRef = 1;
1.817 - if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
1.818 - pParse->pNewTable = pTable;
1.819 -
1.820 - /* If this is the magic sqlite_sequence table used by autoincrement,
1.821 - ** then record a pointer to this table in the main database structure
1.822 - ** so that INSERT can find the table easily.
1.823 - */
1.824 -#ifndef SQLITE_OMIT_AUTOINCREMENT
1.825 - if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
1.826 - pTable->pSchema->pSeqTab = pTable;
1.827 - }
1.828 -#endif
1.829 -
1.830 - /* Begin generating the code that will insert the table record into
1.831 - ** the SQLITE_MASTER table. Note in particular that we must go ahead
1.832 - ** and allocate the record number for the table entry now. Before any
1.833 - ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
1.834 - ** indices to be created and the table record must come before the
1.835 - ** indices. Hence, the record number for the table must be allocated
1.836 - ** now.
1.837 - */
1.838 - if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1.839 - int lbl;
1.840 - int fileFormat;
1.841 - sqlite3BeginWriteOperation(pParse, 0, iDb);
1.842 -
1.843 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.844 - if( isVirtual ){
1.845 - sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
1.846 - }
1.847 -#endif
1.848 -
1.849 - /* If the file format and encoding in the database have not been set,
1.850 - ** set them now.
1.851 - */
1.852 - sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
1.853 - sqlite3VdbeUsesBtree(v, iDb);
1.854 - lbl = sqlite3VdbeMakeLabel(v);
1.855 - sqlite3VdbeAddOp(v, OP_If, 0, lbl);
1.856 - fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1.857 - 1 : SQLITE_MAX_FILE_FORMAT;
1.858 - sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
1.859 - sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
1.860 - sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
1.861 - sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
1.862 - sqlite3VdbeResolveLabel(v, lbl);
1.863 -
1.864 - /* This just creates a place-holder record in the sqlite_master table.
1.865 - ** The record created does not contain anything yet. It will be replaced
1.866 - ** by the real entry in code generated at sqlite3EndTable().
1.867 - **
1.868 - ** The rowid for the new entry is left on the top of the stack.
1.869 - ** The rowid value is needed by the code that sqlite3EndTable will
1.870 - ** generate.
1.871 - */
1.872 -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1.873 - if( isView || isVirtual ){
1.874 - sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
1.875 - }else
1.876 -#endif
1.877 - {
1.878 - sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
1.879 - }
1.880 - sqlite3OpenMasterTable(pParse, iDb);
1.881 - sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
1.882 - sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1.883 - sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1.884 - sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND);
1.885 - sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1.886 - sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1.887 - }
1.888 -
1.889 - /* Normal (non-error) return. */
1.890 - return;
1.891 -
1.892 - /* If an error occurs, we jump here */
1.893 -begin_table_error:
1.894 - sqlite3_free(zName);
1.895 - return;
1.896 -}
1.897 -
1.898 -/*
1.899 -** This macro is used to compare two strings in a case-insensitive manner.
1.900 -** It is slightly faster than calling sqlite3StrICmp() directly, but
1.901 -** produces larger code.
1.902 -**
1.903 -** WARNING: This macro is not compatible with the strcmp() family. It
1.904 -** returns true if the two strings are equal, otherwise false.
1.905 -*/
1.906 -#define STRICMP(x, y) (\
1.907 -sqlite3UpperToLower[*(unsigned char *)(x)]== \
1.908 -sqlite3UpperToLower[*(unsigned char *)(y)] \
1.909 -&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1.910 -
1.911 -/*
1.912 -** Add a new column to the table currently being constructed.
1.913 -**
1.914 -** The parser calls this routine once for each column declaration
1.915 -** in a CREATE TABLE statement. sqlite3StartTable() gets called
1.916 -** first to get things going. Then this routine is called for each
1.917 -** column.
1.918 -*/
1.919 -void sqlite3AddColumn(Parse *pParse, Token *pName){
1.920 - Table *p;
1.921 - int i;
1.922 - char *z;
1.923 - Column *pCol;
1.924 - if( (p = pParse->pNewTable)==0 ) return;
1.925 - if( p->nCol+1>SQLITE_MAX_COLUMN ){
1.926 - sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1.927 - return;
1.928 - }
1.929 - z = sqlite3NameFromToken(pParse->db, pName);
1.930 - if( z==0 ) return;
1.931 - for(i=0; i<p->nCol; i++){
1.932 - if( STRICMP(z, p->aCol[i].zName) ){
1.933 - sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1.934 - sqlite3_free(z);
1.935 - return;
1.936 - }
1.937 - }
1.938 - if( (p->nCol & 0x7)==0 ){
1.939 - Column *aNew;
1.940 - aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
1.941 - if( aNew==0 ){
1.942 - sqlite3_free(z);
1.943 - return;
1.944 - }
1.945 - p->aCol = aNew;
1.946 - }
1.947 - pCol = &p->aCol[p->nCol];
1.948 - memset(pCol, 0, sizeof(p->aCol[0]));
1.949 - pCol->zName = z;
1.950 -
1.951 - /* If there is no type specified, columns have the default affinity
1.952 - ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1.953 - ** be called next to set pCol->affinity correctly.
1.954 - */
1.955 - pCol->affinity = SQLITE_AFF_NONE;
1.956 - p->nCol++;
1.957 -}
1.958 -
1.959 -/*
1.960 -** This routine is called by the parser while in the middle of
1.961 -** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1.962 -** been seen on a column. This routine sets the notNull flag on
1.963 -** the column currently under construction.
1.964 -*/
1.965 -void sqlite3AddNotNull(Parse *pParse, int onError){
1.966 - Table *p;
1.967 - int i;
1.968 - if( (p = pParse->pNewTable)==0 ) return;
1.969 - i = p->nCol-1;
1.970 - if( i>=0 ) p->aCol[i].notNull = onError;
1.971 -}
1.972 -
1.973 -/*
1.974 -** Scan the column type name zType (length nType) and return the
1.975 -** associated affinity type.
1.976 -**
1.977 -** This routine does a case-independent search of zType for the
1.978 -** substrings in the following table. If one of the substrings is
1.979 -** found, the corresponding affinity is returned. If zType contains
1.980 -** more than one of the substrings, entries toward the top of
1.981 -** the table take priority. For example, if zType is 'BLOBINT',
1.982 -** SQLITE_AFF_INTEGER is returned.
1.983 -**
1.984 -** Substring | Affinity
1.985 -** --------------------------------
1.986 -** 'INT' | SQLITE_AFF_INTEGER
1.987 -** 'CHAR' | SQLITE_AFF_TEXT
1.988 -** 'CLOB' | SQLITE_AFF_TEXT
1.989 -** 'TEXT' | SQLITE_AFF_TEXT
1.990 -** 'BLOB' | SQLITE_AFF_NONE
1.991 -** 'REAL' | SQLITE_AFF_REAL
1.992 -** 'FLOA' | SQLITE_AFF_REAL
1.993 -** 'DOUB' | SQLITE_AFF_REAL
1.994 -**
1.995 -** If none of the substrings in the above table are found,
1.996 -** SQLITE_AFF_NUMERIC is returned.
1.997 -*/
1.998 -char sqlite3AffinityType(const Token *pType){
1.999 - u32 h = 0;
1.1000 - char aff = SQLITE_AFF_NUMERIC;
1.1001 - const unsigned char *zIn = pType->z;
1.1002 - const unsigned char *zEnd = &pType->z[pType->n];
1.1003 -
1.1004 - while( zIn!=zEnd ){
1.1005 - h = (h<<8) + sqlite3UpperToLower[*zIn];
1.1006 - zIn++;
1.1007 - if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1.1008 - aff = SQLITE_AFF_TEXT;
1.1009 - }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1.1010 - aff = SQLITE_AFF_TEXT;
1.1011 - }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1.1012 - aff = SQLITE_AFF_TEXT;
1.1013 - }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1.1014 - && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1.1015 - aff = SQLITE_AFF_NONE;
1.1016 -#ifndef SQLITE_OMIT_FLOATING_POINT
1.1017 - }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1.1018 - && aff==SQLITE_AFF_NUMERIC ){
1.1019 - aff = SQLITE_AFF_REAL;
1.1020 - }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1.1021 - && aff==SQLITE_AFF_NUMERIC ){
1.1022 - aff = SQLITE_AFF_REAL;
1.1023 - }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1.1024 - && aff==SQLITE_AFF_NUMERIC ){
1.1025 - aff = SQLITE_AFF_REAL;
1.1026 -#endif
1.1027 - }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1.1028 - aff = SQLITE_AFF_INTEGER;
1.1029 - break;
1.1030 - }
1.1031 - }
1.1032 -
1.1033 - return aff;
1.1034 -}
1.1035 -
1.1036 -/*
1.1037 -** This routine is called by the parser while in the middle of
1.1038 -** parsing a CREATE TABLE statement. The pFirst token is the first
1.1039 -** token in the sequence of tokens that describe the type of the
1.1040 -** column currently under construction. pLast is the last token
1.1041 -** in the sequence. Use this information to construct a string
1.1042 -** that contains the typename of the column and store that string
1.1043 -** in zType.
1.1044 -*/
1.1045 -void sqlite3AddColumnType(Parse *pParse, Token *pType){
1.1046 - Table *p;
1.1047 - int i;
1.1048 - Column *pCol;
1.1049 -
1.1050 - if( (p = pParse->pNewTable)==0 ) return;
1.1051 - i = p->nCol-1;
1.1052 - if( i<0 ) return;
1.1053 - pCol = &p->aCol[i];
1.1054 - sqlite3_free(pCol->zType);
1.1055 - pCol->zType = sqlite3NameFromToken(pParse->db, pType);
1.1056 - pCol->affinity = sqlite3AffinityType(pType);
1.1057 -}
1.1058 -
1.1059 -/*
1.1060 -** The expression is the default value for the most recently added column
1.1061 -** of the table currently under construction.
1.1062 -**
1.1063 -** Default value expressions must be constant. Raise an exception if this
1.1064 -** is not the case.
1.1065 -**
1.1066 -** This routine is called by the parser while in the middle of
1.1067 -** parsing a CREATE TABLE statement.
1.1068 -*/
1.1069 -void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
1.1070 - Table *p;
1.1071 - Column *pCol;
1.1072 - if( (p = pParse->pNewTable)!=0 ){
1.1073 - pCol = &(p->aCol[p->nCol-1]);
1.1074 - if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1.1075 - sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1.1076 - pCol->zName);
1.1077 - }else{
1.1078 - Expr *pCopy;
1.1079 - sqlite3 *db = pParse->db;
1.1080 - sqlite3ExprDelete(pCol->pDflt);
1.1081 - pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
1.1082 - if( pCopy ){
1.1083 - sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
1.1084 - }
1.1085 - }
1.1086 - }
1.1087 - sqlite3ExprDelete(pExpr);
1.1088 -}
1.1089 -
1.1090 -/*
1.1091 -** Designate the PRIMARY KEY for the table. pList is a list of names
1.1092 -** of columns that form the primary key. If pList is NULL, then the
1.1093 -** most recently added column of the table is the primary key.
1.1094 -**
1.1095 -** A table can have at most one primary key. If the table already has
1.1096 -** a primary key (and this is the second primary key) then create an
1.1097 -** error.
1.1098 -**
1.1099 -** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1.1100 -** then we will try to use that column as the rowid. Set the Table.iPKey
1.1101 -** field of the table under construction to be the index of the
1.1102 -** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1.1103 -** no INTEGER PRIMARY KEY.
1.1104 -**
1.1105 -** If the key is not an INTEGER PRIMARY KEY, then create a unique
1.1106 -** index for the key. No index is created for INTEGER PRIMARY KEYs.
1.1107 -*/
1.1108 -void sqlite3AddPrimaryKey(
1.1109 - Parse *pParse, /* Parsing context */
1.1110 - ExprList *pList, /* List of field names to be indexed */
1.1111 - int onError, /* What to do with a uniqueness conflict */
1.1112 - int autoInc, /* True if the AUTOINCREMENT keyword is present */
1.1113 - int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1.1114 -){
1.1115 - Table *pTab = pParse->pNewTable;
1.1116 - char *zType = 0;
1.1117 - int iCol = -1, i;
1.1118 - if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
1.1119 - if( pTab->hasPrimKey ){
1.1120 - sqlite3ErrorMsg(pParse,
1.1121 - "table \"%s\" has more than one primary key", pTab->zName);
1.1122 - goto primary_key_exit;
1.1123 - }
1.1124 - pTab->hasPrimKey = 1;
1.1125 - if( pList==0 ){
1.1126 - iCol = pTab->nCol - 1;
1.1127 - pTab->aCol[iCol].isPrimKey = 1;
1.1128 - }else{
1.1129 - for(i=0; i<pList->nExpr; i++){
1.1130 - for(iCol=0; iCol<pTab->nCol; iCol++){
1.1131 - if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1.1132 - break;
1.1133 - }
1.1134 - }
1.1135 - if( iCol<pTab->nCol ){
1.1136 - pTab->aCol[iCol].isPrimKey = 1;
1.1137 - }
1.1138 - }
1.1139 - if( pList->nExpr>1 ) iCol = -1;
1.1140 - }
1.1141 - if( iCol>=0 && iCol<pTab->nCol ){
1.1142 - zType = pTab->aCol[iCol].zType;
1.1143 - }
1.1144 - if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1.1145 - && sortOrder==SQLITE_SO_ASC ){
1.1146 - pTab->iPKey = iCol;
1.1147 - pTab->keyConf = onError;
1.1148 - pTab->autoInc = autoInc;
1.1149 - }else if( autoInc ){
1.1150 -#ifndef SQLITE_OMIT_AUTOINCREMENT
1.1151 - sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1.1152 - "INTEGER PRIMARY KEY");
1.1153 -#endif
1.1154 - }else{
1.1155 - sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1.1156 - pList = 0;
1.1157 - }
1.1158 -
1.1159 -primary_key_exit:
1.1160 - sqlite3ExprListDelete(pList);
1.1161 - return;
1.1162 -}
1.1163 -
1.1164 -/*
1.1165 -** Add a new CHECK constraint to the table currently under construction.
1.1166 -*/
1.1167 -void sqlite3AddCheckConstraint(
1.1168 - Parse *pParse, /* Parsing context */
1.1169 - Expr *pCheckExpr /* The check expression */
1.1170 -){
1.1171 -#ifndef SQLITE_OMIT_CHECK
1.1172 - Table *pTab = pParse->pNewTable;
1.1173 - sqlite3 *db = pParse->db;
1.1174 - if( pTab && !IN_DECLARE_VTAB ){
1.1175 - /* The CHECK expression must be duplicated so that tokens refer
1.1176 - ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1.1177 - ** statement */
1.1178 - pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
1.1179 - sqlite3ExprDup(db, pCheckExpr));
1.1180 - }
1.1181 -#endif
1.1182 - sqlite3ExprDelete(pCheckExpr);
1.1183 -}
1.1184 -
1.1185 -/*
1.1186 -** Set the collation function of the most recently parsed table column
1.1187 -** to the CollSeq given.
1.1188 -*/
1.1189 -void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
1.1190 - Table *p;
1.1191 - int i;
1.1192 -
1.1193 - if( (p = pParse->pNewTable)==0 ) return;
1.1194 - i = p->nCol-1;
1.1195 -
1.1196 - if( sqlite3LocateCollSeq(pParse, zType, nType) ){
1.1197 - Index *pIdx;
1.1198 - p->aCol[i].zColl = sqlite3DbStrNDup(pParse->db, zType, nType);
1.1199 -
1.1200 - /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1.1201 - ** then an index may have been created on this column before the
1.1202 - ** collation type was added. Correct this if it is the case.
1.1203 - */
1.1204 - for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1.1205 - assert( pIdx->nColumn==1 );
1.1206 - if( pIdx->aiColumn[0]==i ){
1.1207 - pIdx->azColl[0] = p->aCol[i].zColl;
1.1208 - }
1.1209 - }
1.1210 - }
1.1211 -}
1.1212 -
1.1213 -/*
1.1214 -** This function returns the collation sequence for database native text
1.1215 -** encoding identified by the string zName, length nName.
1.1216 -**
1.1217 -** If the requested collation sequence is not available, or not available
1.1218 -** in the database native encoding, the collation factory is invoked to
1.1219 -** request it. If the collation factory does not supply such a sequence,
1.1220 -** and the sequence is available in another text encoding, then that is
1.1221 -** returned instead.
1.1222 -**
1.1223 -** If no versions of the requested collations sequence are available, or
1.1224 -** another error occurs, NULL is returned and an error message written into
1.1225 -** pParse.
1.1226 -**
1.1227 -** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1.1228 -** invokes the collation factory if the named collation cannot be found
1.1229 -** and generates an error message.
1.1230 -*/
1.1231 -CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
1.1232 - sqlite3 *db = pParse->db;
1.1233 - u8 enc = ENC(db);
1.1234 - u8 initbusy = db->init.busy;
1.1235 - CollSeq *pColl;
1.1236 -
1.1237 - pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
1.1238 - if( !initbusy && (!pColl || !pColl->xCmp) ){
1.1239 - pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1.1240 - if( !pColl ){
1.1241 - if( nName<0 ){
1.1242 - nName = strlen(zName);
1.1243 - }
1.1244 - sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1.1245 - pColl = 0;
1.1246 - }
1.1247 - }
1.1248 -
1.1249 - return pColl;
1.1250 -}
1.1251 -
1.1252 -
1.1253 -/*
1.1254 -** Generate code that will increment the schema cookie.
1.1255 -**
1.1256 -** The schema cookie is used to determine when the schema for the
1.1257 -** database changes. After each schema change, the cookie value
1.1258 -** changes. When a process first reads the schema it records the
1.1259 -** cookie. Thereafter, whenever it goes to access the database,
1.1260 -** it checks the cookie to make sure the schema has not changed
1.1261 -** since it was last read.
1.1262 -**
1.1263 -** This plan is not completely bullet-proof. It is possible for
1.1264 -** the schema to change multiple times and for the cookie to be
1.1265 -** set back to prior value. But schema changes are infrequent
1.1266 -** and the probability of hitting the same cookie value is only
1.1267 -** 1 chance in 2^32. So we're safe enough.
1.1268 -*/
1.1269 -void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
1.1270 - sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
1.1271 - sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
1.1272 -}
1.1273 -
1.1274 -/*
1.1275 -** Measure the number of characters needed to output the given
1.1276 -** identifier. The number returned includes any quotes used
1.1277 -** but does not include the null terminator.
1.1278 -**
1.1279 -** The estimate is conservative. It might be larger that what is
1.1280 -** really needed.
1.1281 -*/
1.1282 -static int identLength(const char *z){
1.1283 - int n;
1.1284 - for(n=0; *z; n++, z++){
1.1285 - if( *z=='"' ){ n++; }
1.1286 - }
1.1287 - return n + 2;
1.1288 -}
1.1289 -
1.1290 -/*
1.1291 -** Write an identifier onto the end of the given string. Add
1.1292 -** quote characters as needed.
1.1293 -*/
1.1294 -static void identPut(char *z, int *pIdx, char *zSignedIdent){
1.1295 - unsigned char *zIdent = (unsigned char*)zSignedIdent;
1.1296 - int i, j, needQuote;
1.1297 - i = *pIdx;
1.1298 - for(j=0; zIdent[j]; j++){
1.1299 - if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1.1300 - }
1.1301 - needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
1.1302 - || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1.1303 - if( needQuote ) z[i++] = '"';
1.1304 - for(j=0; zIdent[j]; j++){
1.1305 - z[i++] = zIdent[j];
1.1306 - if( zIdent[j]=='"' ) z[i++] = '"';
1.1307 - }
1.1308 - if( needQuote ) z[i++] = '"';
1.1309 - z[i] = 0;
1.1310 - *pIdx = i;
1.1311 -}
1.1312 -
1.1313 -/*
1.1314 -** Generate a CREATE TABLE statement appropriate for the given
1.1315 -** table. Memory to hold the text of the statement is obtained
1.1316 -** from sqliteMalloc() and must be freed by the calling function.
1.1317 -*/
1.1318 -static char *createTableStmt(Table *p, int isTemp){
1.1319 - int i, k, n;
1.1320 - char *zStmt;
1.1321 - char *zSep, *zSep2, *zEnd, *z;
1.1322 - Column *pCol;
1.1323 - n = 0;
1.1324 - for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1.1325 - n += identLength(pCol->zName);
1.1326 - z = pCol->zType;
1.1327 - if( z ){
1.1328 - n += (strlen(z) + 1);
1.1329 - }
1.1330 - }
1.1331 - n += identLength(p->zName);
1.1332 - if( n<50 ){
1.1333 - zSep = "";
1.1334 - zSep2 = ",";
1.1335 - zEnd = ")";
1.1336 - }else{
1.1337 - zSep = "\n ";
1.1338 - zSep2 = ",\n ";
1.1339 - zEnd = "\n)";
1.1340 - }
1.1341 - n += 35 + 6*p->nCol;
1.1342 - zStmt = sqlite3_malloc( n );
1.1343 - if( zStmt==0 ) return 0;
1.1344 - sqlite3_snprintf(n, zStmt,
1.1345 - !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
1.1346 - k = strlen(zStmt);
1.1347 - identPut(zStmt, &k, p->zName);
1.1348 - zStmt[k++] = '(';
1.1349 - for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1.1350 - sqlite3_snprintf(n-k, &zStmt[k], zSep);
1.1351 - k += strlen(&zStmt[k]);
1.1352 - zSep = zSep2;
1.1353 - identPut(zStmt, &k, pCol->zName);
1.1354 - if( (z = pCol->zType)!=0 ){
1.1355 - zStmt[k++] = ' ';
1.1356 - assert( strlen(z)+k+1<=n );
1.1357 - sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
1.1358 - k += strlen(z);
1.1359 - }
1.1360 - }
1.1361 - sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1.1362 - return zStmt;
1.1363 -}
1.1364 -
1.1365 -/*
1.1366 -** This routine is called to report the final ")" that terminates
1.1367 -** a CREATE TABLE statement.
1.1368 -**
1.1369 -** The table structure that other action routines have been building
1.1370 -** is added to the internal hash tables, assuming no errors have
1.1371 -** occurred.
1.1372 -**
1.1373 -** An entry for the table is made in the master table on disk, unless
1.1374 -** this is a temporary table or db->init.busy==1. When db->init.busy==1
1.1375 -** it means we are reading the sqlite_master table because we just
1.1376 -** connected to the database or because the sqlite_master table has
1.1377 -** recently changed, so the entry for this table already exists in
1.1378 -** the sqlite_master table. We do not want to create it again.
1.1379 -**
1.1380 -** If the pSelect argument is not NULL, it means that this routine
1.1381 -** was called to create a table generated from a
1.1382 -** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1.1383 -** the new table will match the result set of the SELECT.
1.1384 -*/
1.1385 -void sqlite3EndTable(
1.1386 - Parse *pParse, /* Parse context */
1.1387 - Token *pCons, /* The ',' token after the last column defn. */
1.1388 - Token *pEnd, /* The final ')' token in the CREATE TABLE */
1.1389 - Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1.1390 -){
1.1391 - Table *p;
1.1392 - sqlite3 *db = pParse->db;
1.1393 - int iDb;
1.1394 -
1.1395 - if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
1.1396 - return;
1.1397 - }
1.1398 - p = pParse->pNewTable;
1.1399 - if( p==0 ) return;
1.1400 -
1.1401 - assert( !db->init.busy || !pSelect );
1.1402 -
1.1403 - iDb = sqlite3SchemaToIndex(db, p->pSchema);
1.1404 -
1.1405 -#ifndef SQLITE_OMIT_CHECK
1.1406 - /* Resolve names in all CHECK constraint expressions.
1.1407 - */
1.1408 - if( p->pCheck ){
1.1409 - SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1.1410 - NameContext sNC; /* Name context for pParse->pNewTable */
1.1411 -
1.1412 - memset(&sNC, 0, sizeof(sNC));
1.1413 - memset(&sSrc, 0, sizeof(sSrc));
1.1414 - sSrc.nSrc = 1;
1.1415 - sSrc.a[0].zName = p->zName;
1.1416 - sSrc.a[0].pTab = p;
1.1417 - sSrc.a[0].iCursor = -1;
1.1418 - sNC.pParse = pParse;
1.1419 - sNC.pSrcList = &sSrc;
1.1420 - sNC.isCheck = 1;
1.1421 - if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
1.1422 - return;
1.1423 - }
1.1424 - }
1.1425 -#endif /* !defined(SQLITE_OMIT_CHECK) */
1.1426 -
1.1427 - /* If the db->init.busy is 1 it means we are reading the SQL off the
1.1428 - ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1.1429 - ** So do not write to the disk again. Extract the root page number
1.1430 - ** for the table from the db->init.newTnum field. (The page number
1.1431 - ** should have been put there by the sqliteOpenCb routine.)
1.1432 - */
1.1433 - if( db->init.busy ){
1.1434 - p->tnum = db->init.newTnum;
1.1435 - }
1.1436 -
1.1437 - /* If not initializing, then create a record for the new table
1.1438 - ** in the SQLITE_MASTER table of the database. The record number
1.1439 - ** for the new table entry should already be on the stack.
1.1440 - **
1.1441 - ** If this is a TEMPORARY table, write the entry into the auxiliary
1.1442 - ** file instead of into the main database file.
1.1443 - */
1.1444 - if( !db->init.busy ){
1.1445 - int n;
1.1446 - Vdbe *v;
1.1447 - char *zType; /* "view" or "table" */
1.1448 - char *zType2; /* "VIEW" or "TABLE" */
1.1449 - char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
1.1450 -
1.1451 - v = sqlite3GetVdbe(pParse);
1.1452 - if( v==0 ) return;
1.1453 -
1.1454 - sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1.1455 -
1.1456 - /* Create the rootpage for the new table and push it onto the stack.
1.1457 - ** A view has no rootpage, so just push a zero onto the stack for
1.1458 - ** views. Initialize zType at the same time.
1.1459 - */
1.1460 - if( p->pSelect==0 ){
1.1461 - /* A regular table */
1.1462 - zType = "table";
1.1463 - zType2 = "TABLE";
1.1464 -#ifndef SQLITE_OMIT_VIEW
1.1465 - }else{
1.1466 - /* A view */
1.1467 - zType = "view";
1.1468 - zType2 = "VIEW";
1.1469 -#endif
1.1470 - }
1.1471 -
1.1472 - /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1.1473 - ** statement to populate the new table. The root-page number for the
1.1474 - ** new table is on the top of the vdbe stack.
1.1475 - **
1.1476 - ** Once the SELECT has been coded by sqlite3Select(), it is in a
1.1477 - ** suitable state to query for the column names and types to be used
1.1478 - ** by the new table.
1.1479 - **
1.1480 - ** A shared-cache write-lock is not required to write to the new table,
1.1481 - ** as a schema-lock must have already been obtained to create it. Since
1.1482 - ** a schema-lock excludes all other database users, the write-lock would
1.1483 - ** be redundant.
1.1484 - */
1.1485 - if( pSelect ){
1.1486 - Table *pSelTab;
1.1487 - sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1.1488 - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1.1489 - sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1.1490 - pParse->nTab = 2;
1.1491 - sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
1.1492 - sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1.1493 - if( pParse->nErr==0 ){
1.1494 - pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1.1495 - if( pSelTab==0 ) return;
1.1496 - assert( p->aCol==0 );
1.1497 - p->nCol = pSelTab->nCol;
1.1498 - p->aCol = pSelTab->aCol;
1.1499 - pSelTab->nCol = 0;
1.1500 - pSelTab->aCol = 0;
1.1501 - sqlite3DeleteTable(pSelTab);
1.1502 - }
1.1503 - }
1.1504 -
1.1505 - /* Compute the complete text of the CREATE statement */
1.1506 - if( pSelect ){
1.1507 - zStmt = createTableStmt(p, p->pSchema==db->aDb[1].pSchema);
1.1508 - }else{
1.1509 - n = pEnd->z - pParse->sNameToken.z + 1;
1.1510 - zStmt = sqlite3MPrintf(db,
1.1511 - "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1.1512 - );
1.1513 - }
1.1514 -
1.1515 - /* A slot for the record has already been allocated in the
1.1516 - ** SQLITE_MASTER table. We just need to update that slot with all
1.1517 - ** the information we've collected. The rowid for the preallocated
1.1518 - ** slot is the 2nd item on the stack. The top of the stack is the
1.1519 - ** root page for the new table (or a 0 if this is a view).
1.1520 - */
1.1521 - sqlite3NestedParse(pParse,
1.1522 - "UPDATE %Q.%s "
1.1523 - "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1.1524 - "WHERE rowid=#1",
1.1525 - db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1.1526 - zType,
1.1527 - p->zName,
1.1528 - p->zName,
1.1529 - zStmt
1.1530 - );
1.1531 - sqlite3_free(zStmt);
1.1532 - sqlite3ChangeCookie(db, v, iDb);
1.1533 -
1.1534 -#ifndef SQLITE_OMIT_AUTOINCREMENT
1.1535 - /* Check to see if we need to create an sqlite_sequence table for
1.1536 - ** keeping track of autoincrement keys.
1.1537 - */
1.1538 - if( p->autoInc ){
1.1539 - Db *pDb = &db->aDb[iDb];
1.1540 - if( pDb->pSchema->pSeqTab==0 ){
1.1541 - sqlite3NestedParse(pParse,
1.1542 - "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1.1543 - pDb->zName
1.1544 - );
1.1545 - }
1.1546 - }
1.1547 -#endif
1.1548 -
1.1549 - /* Reparse everything to update our internal data structures */
1.1550 - sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
1.1551 - sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P3_DYNAMIC);
1.1552 - }
1.1553 -
1.1554 -
1.1555 - /* Add the table to the in-memory representation of the database.
1.1556 - */
1.1557 - if( db->init.busy && pParse->nErr==0 ){
1.1558 - Table *pOld;
1.1559 - FKey *pFKey;
1.1560 - Schema *pSchema = p->pSchema;
1.1561 - pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
1.1562 - if( pOld ){
1.1563 - assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1.1564 - db->mallocFailed = 1;
1.1565 - return;
1.1566 - }
1.1567 -#ifndef SQLITE_OMIT_FOREIGN_KEY
1.1568 - for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1.1569 - void *data;
1.1570 - int nTo = strlen(pFKey->zTo) + 1;
1.1571 - pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
1.1572 - data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
1.1573 - if( data==(void *)pFKey ){
1.1574 - db->mallocFailed = 1;
1.1575 - }
1.1576 - }
1.1577 -#endif
1.1578 - pParse->pNewTable = 0;
1.1579 - db->nTable++;
1.1580 - db->flags |= SQLITE_InternChanges;
1.1581 -
1.1582 -#ifndef SQLITE_OMIT_ALTERTABLE
1.1583 - if( !p->pSelect ){
1.1584 - const char *zName = (const char *)pParse->sNameToken.z;
1.1585 - int nName;
1.1586 - assert( !pSelect && pCons && pEnd );
1.1587 - if( pCons->z==0 ){
1.1588 - pCons = pEnd;
1.1589 - }
1.1590 - nName = (const char *)pCons->z - zName;
1.1591 - p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
1.1592 - }
1.1593 -#endif
1.1594 - }
1.1595 -}
1.1596 -
1.1597 -#ifndef SQLITE_OMIT_VIEW
1.1598 -/*
1.1599 -** The parser calls this routine in order to create a new VIEW
1.1600 -*/
1.1601 -void sqlite3CreateView(
1.1602 - Parse *pParse, /* The parsing context */
1.1603 - Token *pBegin, /* The CREATE token that begins the statement */
1.1604 - Token *pName1, /* The token that holds the name of the view */
1.1605 - Token *pName2, /* The token that holds the name of the view */
1.1606 - Select *pSelect, /* A SELECT statement that will become the new view */
1.1607 - int isTemp, /* TRUE for a TEMPORARY view */
1.1608 - int noErr /* Suppress error messages if VIEW already exists */
1.1609 -){
1.1610 - Table *p;
1.1611 - int n;
1.1612 - const unsigned char *z;
1.1613 - Token sEnd;
1.1614 - DbFixer sFix;
1.1615 - Token *pName;
1.1616 - int iDb;
1.1617 - sqlite3 *db = pParse->db;
1.1618 -
1.1619 - if( pParse->nVar>0 ){
1.1620 - sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1.1621 - sqlite3SelectDelete(pSelect);
1.1622 - return;
1.1623 - }
1.1624 - sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
1.1625 - p = pParse->pNewTable;
1.1626 - if( p==0 || pParse->nErr ){
1.1627 - sqlite3SelectDelete(pSelect);
1.1628 - return;
1.1629 - }
1.1630 - sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1.1631 - iDb = sqlite3SchemaToIndex(db, p->pSchema);
1.1632 - if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
1.1633 - && sqlite3FixSelect(&sFix, pSelect)
1.1634 - ){
1.1635 - sqlite3SelectDelete(pSelect);
1.1636 - return;
1.1637 - }
1.1638 -
1.1639 - /* Make a copy of the entire SELECT statement that defines the view.
1.1640 - ** This will force all the Expr.token.z values to be dynamically
1.1641 - ** allocated rather than point to the input string - which means that
1.1642 - ** they will persist after the current sqlite3_exec() call returns.
1.1643 - */
1.1644 - p->pSelect = sqlite3SelectDup(db, pSelect);
1.1645 - sqlite3SelectDelete(pSelect);
1.1646 - if( db->mallocFailed ){
1.1647 - return;
1.1648 - }
1.1649 - if( !db->init.busy ){
1.1650 - sqlite3ViewGetColumnNames(pParse, p);
1.1651 - }
1.1652 -
1.1653 - /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1.1654 - ** the end.
1.1655 - */
1.1656 - sEnd = pParse->sLastToken;
1.1657 - if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1.1658 - sEnd.z += sEnd.n;
1.1659 - }
1.1660 - sEnd.n = 0;
1.1661 - n = sEnd.z - pBegin->z;
1.1662 - z = (const unsigned char*)pBegin->z;
1.1663 - while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1.1664 - sEnd.z = &z[n-1];
1.1665 - sEnd.n = 1;
1.1666 -
1.1667 - /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1.1668 - sqlite3EndTable(pParse, 0, &sEnd, 0);
1.1669 - return;
1.1670 -}
1.1671 -#endif /* SQLITE_OMIT_VIEW */
1.1672 -
1.1673 -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1.1674 -/*
1.1675 -** The Table structure pTable is really a VIEW. Fill in the names of
1.1676 -** the columns of the view in the pTable structure. Return the number
1.1677 -** of errors. If an error is seen leave an error message in pParse->zErrMsg.
1.1678 -*/
1.1679 -int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1.1680 - Table *pSelTab; /* A fake table from which we get the result set */
1.1681 - Select *pSel; /* Copy of the SELECT that implements the view */
1.1682 - int nErr = 0; /* Number of errors encountered */
1.1683 - int n; /* Temporarily holds the number of cursors assigned */
1.1684 - sqlite3 *db = pParse->db; /* Database connection for malloc errors */
1.1685 -
1.1686 - assert( pTable );
1.1687 -
1.1688 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.1689 - if( sqlite3VtabCallConnect(pParse, pTable) ){
1.1690 - return SQLITE_ERROR;
1.1691 - }
1.1692 - if( IsVirtual(pTable) ) return 0;
1.1693 -#endif
1.1694 -
1.1695 -#ifndef SQLITE_OMIT_VIEW
1.1696 - /* A positive nCol means the columns names for this view are
1.1697 - ** already known.
1.1698 - */
1.1699 - if( pTable->nCol>0 ) return 0;
1.1700 -
1.1701 - /* A negative nCol is a special marker meaning that we are currently
1.1702 - ** trying to compute the column names. If we enter this routine with
1.1703 - ** a negative nCol, it means two or more views form a loop, like this:
1.1704 - **
1.1705 - ** CREATE VIEW one AS SELECT * FROM two;
1.1706 - ** CREATE VIEW two AS SELECT * FROM one;
1.1707 - **
1.1708 - ** Actually, this error is caught previously and so the following test
1.1709 - ** should always fail. But we will leave it in place just to be safe.
1.1710 - */
1.1711 - if( pTable->nCol<0 ){
1.1712 - sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1.1713 - return 1;
1.1714 - }
1.1715 - assert( pTable->nCol>=0 );
1.1716 -
1.1717 - /* If we get this far, it means we need to compute the table names.
1.1718 - ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1.1719 - ** "*" elements in the results set of the view and will assign cursors
1.1720 - ** to the elements of the FROM clause. But we do not want these changes
1.1721 - ** to be permanent. So the computation is done on a copy of the SELECT
1.1722 - ** statement that defines the view.
1.1723 - */
1.1724 - assert( pTable->pSelect );
1.1725 - pSel = sqlite3SelectDup(db, pTable->pSelect);
1.1726 - if( pSel ){
1.1727 - n = pParse->nTab;
1.1728 - sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1.1729 - pTable->nCol = -1;
1.1730 - pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1.1731 - pParse->nTab = n;
1.1732 - if( pSelTab ){
1.1733 - assert( pTable->aCol==0 );
1.1734 - pTable->nCol = pSelTab->nCol;
1.1735 - pTable->aCol = pSelTab->aCol;
1.1736 - pSelTab->nCol = 0;
1.1737 - pSelTab->aCol = 0;
1.1738 - sqlite3DeleteTable(pSelTab);
1.1739 - pTable->pSchema->flags |= DB_UnresetViews;
1.1740 - }else{
1.1741 - pTable->nCol = 0;
1.1742 - nErr++;
1.1743 - }
1.1744 - sqlite3SelectDelete(pSel);
1.1745 - } else {
1.1746 - nErr++;
1.1747 - }
1.1748 -#endif /* SQLITE_OMIT_VIEW */
1.1749 - return nErr;
1.1750 -}
1.1751 -#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
1.1752 -
1.1753 -#ifndef SQLITE_OMIT_VIEW
1.1754 -/*
1.1755 -** Clear the column names from every VIEW in database idx.
1.1756 -*/
1.1757 -static void sqliteViewResetAll(sqlite3 *db, int idx){
1.1758 - HashElem *i;
1.1759 - if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1.1760 - for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
1.1761 - Table *pTab = sqliteHashData(i);
1.1762 - if( pTab->pSelect ){
1.1763 - sqliteResetColumnNames(pTab);
1.1764 - }
1.1765 - }
1.1766 - DbClearProperty(db, idx, DB_UnresetViews);
1.1767 -}
1.1768 -#else
1.1769 -# define sqliteViewResetAll(A,B)
1.1770 -#endif /* SQLITE_OMIT_VIEW */
1.1771 -
1.1772 -/*
1.1773 -** This function is called by the VDBE to adjust the internal schema
1.1774 -** used by SQLite when the btree layer moves a table root page. The
1.1775 -** root-page of a table or index in database iDb has changed from iFrom
1.1776 -** to iTo.
1.1777 -**
1.1778 -** Ticket #1728: The symbol table might still contain information
1.1779 -** on tables and/or indices that are the process of being deleted.
1.1780 -** If you are unlucky, one of those deleted indices or tables might
1.1781 -** have the same rootpage number as the real table or index that is
1.1782 -** being moved. So we cannot stop searching after the first match
1.1783 -** because the first match might be for one of the deleted indices
1.1784 -** or tables and not the table/index that is actually being moved.
1.1785 -** We must continue looping until all tables and indices with
1.1786 -** rootpage==iFrom have been converted to have a rootpage of iTo
1.1787 -** in order to be certain that we got the right one.
1.1788 -*/
1.1789 -#ifndef SQLITE_OMIT_AUTOVACUUM
1.1790 -void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1.1791 - HashElem *pElem;
1.1792 - Hash *pHash;
1.1793 -
1.1794 - pHash = &pDb->pSchema->tblHash;
1.1795 - for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1.1796 - Table *pTab = sqliteHashData(pElem);
1.1797 - if( pTab->tnum==iFrom ){
1.1798 - pTab->tnum = iTo;
1.1799 - }
1.1800 - }
1.1801 - pHash = &pDb->pSchema->idxHash;
1.1802 - for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1.1803 - Index *pIdx = sqliteHashData(pElem);
1.1804 - if( pIdx->tnum==iFrom ){
1.1805 - pIdx->tnum = iTo;
1.1806 - }
1.1807 - }
1.1808 -}
1.1809 -#endif
1.1810 -
1.1811 -/*
1.1812 -** Write code to erase the table with root-page iTable from database iDb.
1.1813 -** Also write code to modify the sqlite_master table and internal schema
1.1814 -** if a root-page of another table is moved by the btree-layer whilst
1.1815 -** erasing iTable (this can happen with an auto-vacuum database).
1.1816 -*/
1.1817 -static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1.1818 - Vdbe *v = sqlite3GetVdbe(pParse);
1.1819 - sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1.1820 -#ifndef SQLITE_OMIT_AUTOVACUUM
1.1821 - /* OP_Destroy pushes an integer onto the stack. If this integer
1.1822 - ** is non-zero, then it is the root page number of a table moved to
1.1823 - ** location iTable. The following code modifies the sqlite_master table to
1.1824 - ** reflect this.
1.1825 - **
1.1826 - ** The "#0" in the SQL is a special constant that means whatever value
1.1827 - ** is on the top of the stack. See sqlite3RegisterExpr().
1.1828 - */
1.1829 - sqlite3NestedParse(pParse,
1.1830 - "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
1.1831 - pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
1.1832 -#endif
1.1833 -}
1.1834 -
1.1835 -/*
1.1836 -** Write VDBE code to erase table pTab and all associated indices on disk.
1.1837 -** Code to update the sqlite_master tables and internal schema definitions
1.1838 -** in case a root-page belonging to another table is moved by the btree layer
1.1839 -** is also added (this can happen with an auto-vacuum database).
1.1840 -*/
1.1841 -static void destroyTable(Parse *pParse, Table *pTab){
1.1842 -#ifdef SQLITE_OMIT_AUTOVACUUM
1.1843 - Index *pIdx;
1.1844 - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.1845 - destroyRootPage(pParse, pTab->tnum, iDb);
1.1846 - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.1847 - destroyRootPage(pParse, pIdx->tnum, iDb);
1.1848 - }
1.1849 -#else
1.1850 - /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1.1851 - ** is not defined), then it is important to call OP_Destroy on the
1.1852 - ** table and index root-pages in order, starting with the numerically
1.1853 - ** largest root-page number. This guarantees that none of the root-pages
1.1854 - ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1.1855 - ** following were coded:
1.1856 - **
1.1857 - ** OP_Destroy 4 0
1.1858 - ** ...
1.1859 - ** OP_Destroy 5 0
1.1860 - **
1.1861 - ** and root page 5 happened to be the largest root-page number in the
1.1862 - ** database, then root page 5 would be moved to page 4 by the
1.1863 - ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1.1864 - ** a free-list page.
1.1865 - */
1.1866 - int iTab = pTab->tnum;
1.1867 - int iDestroyed = 0;
1.1868 -
1.1869 - while( 1 ){
1.1870 - Index *pIdx;
1.1871 - int iLargest = 0;
1.1872 -
1.1873 - if( iDestroyed==0 || iTab<iDestroyed ){
1.1874 - iLargest = iTab;
1.1875 - }
1.1876 - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.1877 - int iIdx = pIdx->tnum;
1.1878 - assert( pIdx->pSchema==pTab->pSchema );
1.1879 - if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1.1880 - iLargest = iIdx;
1.1881 - }
1.1882 - }
1.1883 - if( iLargest==0 ){
1.1884 - return;
1.1885 - }else{
1.1886 - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.1887 - destroyRootPage(pParse, iLargest, iDb);
1.1888 - iDestroyed = iLargest;
1.1889 - }
1.1890 - }
1.1891 -#endif
1.1892 -}
1.1893 -
1.1894 -/*
1.1895 -** This routine is called to do the work of a DROP TABLE statement.
1.1896 -** pName is the name of the table to be dropped.
1.1897 -*/
1.1898 -void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
1.1899 - Table *pTab;
1.1900 - Vdbe *v;
1.1901 - sqlite3 *db = pParse->db;
1.1902 - int iDb;
1.1903 -
1.1904 - if( pParse->nErr || db->mallocFailed ){
1.1905 - goto exit_drop_table;
1.1906 - }
1.1907 - assert( pName->nSrc==1 );
1.1908 - pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1.1909 -
1.1910 - if( pTab==0 ){
1.1911 - if( noErr ){
1.1912 - sqlite3ErrorClear(pParse);
1.1913 - }
1.1914 - goto exit_drop_table;
1.1915 - }
1.1916 - iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.1917 - assert( iDb>=0 && iDb<db->nDb );
1.1918 -#ifndef SQLITE_OMIT_AUTHORIZATION
1.1919 - {
1.1920 - int code;
1.1921 - const char *zTab = SCHEMA_TABLE(iDb);
1.1922 - const char *zDb = db->aDb[iDb].zName;
1.1923 - const char *zArg2 = 0;
1.1924 - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
1.1925 - goto exit_drop_table;
1.1926 - }
1.1927 - if( isView ){
1.1928 - if( !OMIT_TEMPDB && iDb==1 ){
1.1929 - code = SQLITE_DROP_TEMP_VIEW;
1.1930 - }else{
1.1931 - code = SQLITE_DROP_VIEW;
1.1932 - }
1.1933 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.1934 - }else if( IsVirtual(pTab) ){
1.1935 - if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1.1936 - goto exit_drop_table;
1.1937 - }
1.1938 - code = SQLITE_DROP_VTABLE;
1.1939 - zArg2 = pTab->pMod->zName;
1.1940 -#endif
1.1941 - }else{
1.1942 - if( !OMIT_TEMPDB && iDb==1 ){
1.1943 - code = SQLITE_DROP_TEMP_TABLE;
1.1944 - }else{
1.1945 - code = SQLITE_DROP_TABLE;
1.1946 - }
1.1947 - }
1.1948 - if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
1.1949 - goto exit_drop_table;
1.1950 - }
1.1951 - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1.1952 - goto exit_drop_table;
1.1953 - }
1.1954 - }
1.1955 -#endif
1.1956 - if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
1.1957 - sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
1.1958 - goto exit_drop_table;
1.1959 - }
1.1960 -
1.1961 -#ifndef SQLITE_OMIT_VIEW
1.1962 - /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1.1963 - ** on a table.
1.1964 - */
1.1965 - if( isView && pTab->pSelect==0 ){
1.1966 - sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1.1967 - goto exit_drop_table;
1.1968 - }
1.1969 - if( !isView && pTab->pSelect ){
1.1970 - sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1.1971 - goto exit_drop_table;
1.1972 - }
1.1973 -#endif
1.1974 -
1.1975 - /* Generate code to remove the table from the master table
1.1976 - ** on disk.
1.1977 - */
1.1978 - v = sqlite3GetVdbe(pParse);
1.1979 - if( v ){
1.1980 - Trigger *pTrigger;
1.1981 - Db *pDb = &db->aDb[iDb];
1.1982 - sqlite3BeginWriteOperation(pParse, 0, iDb);
1.1983 -
1.1984 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.1985 - if( IsVirtual(pTab) ){
1.1986 - Vdbe *v = sqlite3GetVdbe(pParse);
1.1987 - if( v ){
1.1988 - sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
1.1989 - }
1.1990 - }
1.1991 -#endif
1.1992 -
1.1993 - /* Drop all triggers associated with the table being dropped. Code
1.1994 - ** is generated to remove entries from sqlite_master and/or
1.1995 - ** sqlite_temp_master if required.
1.1996 - */
1.1997 - pTrigger = pTab->pTrigger;
1.1998 - while( pTrigger ){
1.1999 - assert( pTrigger->pSchema==pTab->pSchema ||
1.2000 - pTrigger->pSchema==db->aDb[1].pSchema );
1.2001 - sqlite3DropTriggerPtr(pParse, pTrigger);
1.2002 - pTrigger = pTrigger->pNext;
1.2003 - }
1.2004 -
1.2005 -#ifndef SQLITE_OMIT_AUTOINCREMENT
1.2006 - /* Remove any entries of the sqlite_sequence table associated with
1.2007 - ** the table being dropped. This is done before the table is dropped
1.2008 - ** at the btree level, in case the sqlite_sequence table needs to
1.2009 - ** move as a result of the drop (can happen in auto-vacuum mode).
1.2010 - */
1.2011 - if( pTab->autoInc ){
1.2012 - sqlite3NestedParse(pParse,
1.2013 - "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1.2014 - pDb->zName, pTab->zName
1.2015 - );
1.2016 - }
1.2017 -#endif
1.2018 -
1.2019 - /* Drop all SQLITE_MASTER table and index entries that refer to the
1.2020 - ** table. The program name loops through the master table and deletes
1.2021 - ** every row that refers to a table of the same name as the one being
1.2022 - ** dropped. Triggers are handled seperately because a trigger can be
1.2023 - ** created in the temp database that refers to a table in another
1.2024 - ** database.
1.2025 - */
1.2026 - sqlite3NestedParse(pParse,
1.2027 - "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
1.2028 - pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
1.2029 - if( !isView && !IsVirtual(pTab) ){
1.2030 - destroyTable(pParse, pTab);
1.2031 - }
1.2032 -
1.2033 - /* Remove the table entry from SQLite's internal schema and modify
1.2034 - ** the schema cookie.
1.2035 - */
1.2036 - if( IsVirtual(pTab) ){
1.2037 - sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0);
1.2038 - }
1.2039 - sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
1.2040 - sqlite3ChangeCookie(db, v, iDb);
1.2041 - }
1.2042 - sqliteViewResetAll(db, iDb);
1.2043 -
1.2044 -exit_drop_table:
1.2045 - sqlite3SrcListDelete(pName);
1.2046 -}
1.2047 -
1.2048 -/*
1.2049 -** This routine is called to create a new foreign key on the table
1.2050 -** currently under construction. pFromCol determines which columns
1.2051 -** in the current table point to the foreign key. If pFromCol==0 then
1.2052 -** connect the key to the last column inserted. pTo is the name of
1.2053 -** the table referred to. pToCol is a list of tables in the other
1.2054 -** pTo table that the foreign key points to. flags contains all
1.2055 -** information about the conflict resolution algorithms specified
1.2056 -** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1.2057 -**
1.2058 -** An FKey structure is created and added to the table currently
1.2059 -** under construction in the pParse->pNewTable field. The new FKey
1.2060 -** is not linked into db->aFKey at this point - that does not happen
1.2061 -** until sqlite3EndTable().
1.2062 -**
1.2063 -** The foreign key is set for IMMEDIATE processing. A subsequent call
1.2064 -** to sqlite3DeferForeignKey() might change this to DEFERRED.
1.2065 -*/
1.2066 -void sqlite3CreateForeignKey(
1.2067 - Parse *pParse, /* Parsing context */
1.2068 - ExprList *pFromCol, /* Columns in this table that point to other table */
1.2069 - Token *pTo, /* Name of the other table */
1.2070 - ExprList *pToCol, /* Columns in the other table */
1.2071 - int flags /* Conflict resolution algorithms. */
1.2072 -){
1.2073 -#ifndef SQLITE_OMIT_FOREIGN_KEY
1.2074 - FKey *pFKey = 0;
1.2075 - Table *p = pParse->pNewTable;
1.2076 - int nByte;
1.2077 - int i;
1.2078 - int nCol;
1.2079 - char *z;
1.2080 -
1.2081 - assert( pTo!=0 );
1.2082 - if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
1.2083 - if( pFromCol==0 ){
1.2084 - int iCol = p->nCol-1;
1.2085 - if( iCol<0 ) goto fk_end;
1.2086 - if( pToCol && pToCol->nExpr!=1 ){
1.2087 - sqlite3ErrorMsg(pParse, "foreign key on %s"
1.2088 - " should reference only one column of table %T",
1.2089 - p->aCol[iCol].zName, pTo);
1.2090 - goto fk_end;
1.2091 - }
1.2092 - nCol = 1;
1.2093 - }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
1.2094 - sqlite3ErrorMsg(pParse,
1.2095 - "number of columns in foreign key does not match the number of "
1.2096 - "columns in the referenced table");
1.2097 - goto fk_end;
1.2098 - }else{
1.2099 - nCol = pFromCol->nExpr;
1.2100 - }
1.2101 - nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1.2102 - if( pToCol ){
1.2103 - for(i=0; i<pToCol->nExpr; i++){
1.2104 - nByte += strlen(pToCol->a[i].zName) + 1;
1.2105 - }
1.2106 - }
1.2107 - pFKey = sqlite3DbMallocZero(pParse->db, nByte );
1.2108 - if( pFKey==0 ){
1.2109 - goto fk_end;
1.2110 - }
1.2111 - pFKey->pFrom = p;
1.2112 - pFKey->pNextFrom = p->pFKey;
1.2113 - z = (char*)&pFKey[1];
1.2114 - pFKey->aCol = (struct sColMap*)z;
1.2115 - z += sizeof(struct sColMap)*nCol;
1.2116 - pFKey->zTo = z;
1.2117 - memcpy(z, pTo->z, pTo->n);
1.2118 - z[pTo->n] = 0;
1.2119 - z += pTo->n+1;
1.2120 - pFKey->pNextTo = 0;
1.2121 - pFKey->nCol = nCol;
1.2122 - if( pFromCol==0 ){
1.2123 - pFKey->aCol[0].iFrom = p->nCol-1;
1.2124 - }else{
1.2125 - for(i=0; i<nCol; i++){
1.2126 - int j;
1.2127 - for(j=0; j<p->nCol; j++){
1.2128 - if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
1.2129 - pFKey->aCol[i].iFrom = j;
1.2130 - break;
1.2131 - }
1.2132 - }
1.2133 - if( j>=p->nCol ){
1.2134 - sqlite3ErrorMsg(pParse,
1.2135 - "unknown column \"%s\" in foreign key definition",
1.2136 - pFromCol->a[i].zName);
1.2137 - goto fk_end;
1.2138 - }
1.2139 - }
1.2140 - }
1.2141 - if( pToCol ){
1.2142 - for(i=0; i<nCol; i++){
1.2143 - int n = strlen(pToCol->a[i].zName);
1.2144 - pFKey->aCol[i].zCol = z;
1.2145 - memcpy(z, pToCol->a[i].zName, n);
1.2146 - z[n] = 0;
1.2147 - z += n+1;
1.2148 - }
1.2149 - }
1.2150 - pFKey->isDeferred = 0;
1.2151 - pFKey->deleteConf = flags & 0xff;
1.2152 - pFKey->updateConf = (flags >> 8 ) & 0xff;
1.2153 - pFKey->insertConf = (flags >> 16 ) & 0xff;
1.2154 -
1.2155 - /* Link the foreign key to the table as the last step.
1.2156 - */
1.2157 - p->pFKey = pFKey;
1.2158 - pFKey = 0;
1.2159 -
1.2160 -fk_end:
1.2161 - sqlite3_free(pFKey);
1.2162 -#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
1.2163 - sqlite3ExprListDelete(pFromCol);
1.2164 - sqlite3ExprListDelete(pToCol);
1.2165 -}
1.2166 -
1.2167 -/*
1.2168 -** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
1.2169 -** clause is seen as part of a foreign key definition. The isDeferred
1.2170 -** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
1.2171 -** The behavior of the most recently created foreign key is adjusted
1.2172 -** accordingly.
1.2173 -*/
1.2174 -void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
1.2175 -#ifndef SQLITE_OMIT_FOREIGN_KEY
1.2176 - Table *pTab;
1.2177 - FKey *pFKey;
1.2178 - if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
1.2179 - pFKey->isDeferred = isDeferred;
1.2180 -#endif
1.2181 -}
1.2182 -
1.2183 -/*
1.2184 -** Generate code that will erase and refill index *pIdx. This is
1.2185 -** used to initialize a newly created index or to recompute the
1.2186 -** content of an index in response to a REINDEX command.
1.2187 -**
1.2188 -** if memRootPage is not negative, it means that the index is newly
1.2189 -** created. The memory cell specified by memRootPage contains the
1.2190 -** root page number of the index. If memRootPage is negative, then
1.2191 -** the index already exists and must be cleared before being refilled and
1.2192 -** the root page number of the index is taken from pIndex->tnum.
1.2193 -*/
1.2194 -static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
1.2195 - Table *pTab = pIndex->pTable; /* The table that is indexed */
1.2196 - int iTab = pParse->nTab; /* Btree cursor used for pTab */
1.2197 - int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
1.2198 - int addr1; /* Address of top of loop */
1.2199 - int tnum; /* Root page of index */
1.2200 - Vdbe *v; /* Generate code into this virtual machine */
1.2201 - KeyInfo *pKey; /* KeyInfo for index */
1.2202 - sqlite3 *db = pParse->db; /* The database connection */
1.2203 - int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
1.2204 -
1.2205 -#ifndef SQLITE_OMIT_AUTHORIZATION
1.2206 - if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
1.2207 - db->aDb[iDb].zName ) ){
1.2208 - return;
1.2209 - }
1.2210 -#endif
1.2211 -
1.2212 - /* Require a write-lock on the table to perform this operation */
1.2213 - sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
1.2214 -
1.2215 - v = sqlite3GetVdbe(pParse);
1.2216 - if( v==0 ) return;
1.2217 - if( memRootPage>=0 ){
1.2218 - sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
1.2219 - tnum = 0;
1.2220 - }else{
1.2221 - tnum = pIndex->tnum;
1.2222 - sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
1.2223 - }
1.2224 - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
1.2225 - pKey = sqlite3IndexKeyinfo(pParse, pIndex);
1.2226 - sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
1.2227 - sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1.2228 - addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
1.2229 - sqlite3GenerateIndexKey(v, pIndex, iTab);
1.2230 - if( pIndex->onError!=OE_None ){
1.2231 - int curaddr = sqlite3VdbeCurrentAddr(v);
1.2232 - int addr2 = curaddr+4;
1.2233 - sqlite3VdbeChangeP2(v, curaddr-1, addr2);
1.2234 - sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
1.2235 - sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
1.2236 - sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
1.2237 - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
1.2238 - "indexed columns are not unique", P3_STATIC);
1.2239 - assert( db->mallocFailed || addr2==sqlite3VdbeCurrentAddr(v) );
1.2240 - }
1.2241 - sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
1.2242 - sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
1.2243 - sqlite3VdbeJumpHere(v, addr1);
1.2244 - sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
1.2245 - sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
1.2246 -}
1.2247 -
1.2248 -/*
1.2249 -** Create a new index for an SQL table. pName1.pName2 is the name of the index
1.2250 -** and pTblList is the name of the table that is to be indexed. Both will
1.2251 -** be NULL for a primary key or an index that is created to satisfy a
1.2252 -** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
1.2253 -** as the table to be indexed. pParse->pNewTable is a table that is
1.2254 -** currently being constructed by a CREATE TABLE statement.
1.2255 -**
1.2256 -** pList is a list of columns to be indexed. pList will be NULL if this
1.2257 -** is a primary key or unique-constraint on the most recent column added
1.2258 -** to the table currently under construction.
1.2259 -*/
1.2260 -void sqlite3CreateIndex(
1.2261 - Parse *pParse, /* All information about this parse */
1.2262 - Token *pName1, /* First part of index name. May be NULL */
1.2263 - Token *pName2, /* Second part of index name. May be NULL */
1.2264 - SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
1.2265 - ExprList *pList, /* A list of columns to be indexed */
1.2266 - int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1.2267 - Token *pStart, /* The CREATE token that begins this statement */
1.2268 - Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
1.2269 - int sortOrder, /* Sort order of primary key when pList==NULL */
1.2270 - int ifNotExist /* Omit error if index already exists */
1.2271 -){
1.2272 - Table *pTab = 0; /* Table to be indexed */
1.2273 - Index *pIndex = 0; /* The index to be created */
1.2274 - char *zName = 0; /* Name of the index */
1.2275 - int nName; /* Number of characters in zName */
1.2276 - int i, j;
1.2277 - Token nullId; /* Fake token for an empty ID list */
1.2278 - DbFixer sFix; /* For assigning database names to pTable */
1.2279 - int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
1.2280 - sqlite3 *db = pParse->db;
1.2281 - Db *pDb; /* The specific table containing the indexed database */
1.2282 - int iDb; /* Index of the database that is being written */
1.2283 - Token *pName = 0; /* Unqualified name of the index to create */
1.2284 - struct ExprList_item *pListItem; /* For looping over pList */
1.2285 - int nCol;
1.2286 - int nExtra = 0;
1.2287 - char *zExtra;
1.2288 -
1.2289 - if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
1.2290 - goto exit_create_index;
1.2291 - }
1.2292 -
1.2293 - /*
1.2294 - ** Find the table that is to be indexed. Return early if not found.
1.2295 - */
1.2296 - if( pTblName!=0 ){
1.2297 -
1.2298 - /* Use the two-part index name to determine the database
1.2299 - ** to search for the table. 'Fix' the table name to this db
1.2300 - ** before looking up the table.
1.2301 - */
1.2302 - assert( pName1 && pName2 );
1.2303 - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1.2304 - if( iDb<0 ) goto exit_create_index;
1.2305 -
1.2306 -#ifndef SQLITE_OMIT_TEMPDB
1.2307 - /* If the index name was unqualified, check if the the table
1.2308 - ** is a temp table. If so, set the database to 1.
1.2309 - */
1.2310 - pTab = sqlite3SrcListLookup(pParse, pTblName);
1.2311 - if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
1.2312 - iDb = 1;
1.2313 - }
1.2314 -#endif
1.2315 -
1.2316 - if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
1.2317 - sqlite3FixSrcList(&sFix, pTblName)
1.2318 - ){
1.2319 - /* Because the parser constructs pTblName from a single identifier,
1.2320 - ** sqlite3FixSrcList can never fail. */
1.2321 - assert(0);
1.2322 - }
1.2323 - pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
1.2324 - pTblName->a[0].zDatabase);
1.2325 - if( !pTab ) goto exit_create_index;
1.2326 - assert( db->aDb[iDb].pSchema==pTab->pSchema );
1.2327 - }else{
1.2328 - assert( pName==0 );
1.2329 - pTab = pParse->pNewTable;
1.2330 - if( !pTab ) goto exit_create_index;
1.2331 - iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.2332 - }
1.2333 - pDb = &db->aDb[iDb];
1.2334 -
1.2335 - if( pTab==0 || pParse->nErr ) goto exit_create_index;
1.2336 - if( pTab->readOnly ){
1.2337 - sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
1.2338 - goto exit_create_index;
1.2339 - }
1.2340 -#ifndef SQLITE_OMIT_VIEW
1.2341 - if( pTab->pSelect ){
1.2342 - sqlite3ErrorMsg(pParse, "views may not be indexed");
1.2343 - goto exit_create_index;
1.2344 - }
1.2345 -#endif
1.2346 -#ifndef SQLITE_OMIT_VIRTUALTABLE
1.2347 - if( IsVirtual(pTab) ){
1.2348 - sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
1.2349 - goto exit_create_index;
1.2350 - }
1.2351 -#endif
1.2352 -
1.2353 - /*
1.2354 - ** Find the name of the index. Make sure there is not already another
1.2355 - ** index or table with the same name.
1.2356 - **
1.2357 - ** Exception: If we are reading the names of permanent indices from the
1.2358 - ** sqlite_master table (because some other process changed the schema) and
1.2359 - ** one of the index names collides with the name of a temporary table or
1.2360 - ** index, then we will continue to process this index.
1.2361 - **
1.2362 - ** If pName==0 it means that we are
1.2363 - ** dealing with a primary key or UNIQUE constraint. We have to invent our
1.2364 - ** own name.
1.2365 - */
1.2366 - if( pName ){
1.2367 - zName = sqlite3NameFromToken(db, pName);
1.2368 - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
1.2369 - if( zName==0 ) goto exit_create_index;
1.2370 - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
1.2371 - goto exit_create_index;
1.2372 - }
1.2373 - if( !db->init.busy ){
1.2374 - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
1.2375 - if( sqlite3FindTable(db, zName, 0)!=0 ){
1.2376 - sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
1.2377 - goto exit_create_index;
1.2378 - }
1.2379 - }
1.2380 - if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
1.2381 - if( !ifNotExist ){
1.2382 - sqlite3ErrorMsg(pParse, "index %s already exists", zName);
1.2383 - }
1.2384 - goto exit_create_index;
1.2385 - }
1.2386 - }else{
1.2387 - char zBuf[30];
1.2388 - int n;
1.2389 - Index *pLoop;
1.2390 - for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
1.2391 - sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
1.2392 - zName = 0;
1.2393 - sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
1.2394 - if( zName==0 ){
1.2395 - db->mallocFailed = 1;
1.2396 - goto exit_create_index;
1.2397 - }
1.2398 - }
1.2399 -
1.2400 - /* Check for authorization to create an index.
1.2401 - */
1.2402 -#ifndef SQLITE_OMIT_AUTHORIZATION
1.2403 - {
1.2404 - const char *zDb = pDb->zName;
1.2405 - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
1.2406 - goto exit_create_index;
1.2407 - }
1.2408 - i = SQLITE_CREATE_INDEX;
1.2409 - if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
1.2410 - if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
1.2411 - goto exit_create_index;
1.2412 - }
1.2413 - }
1.2414 -#endif
1.2415 -
1.2416 - /* If pList==0, it means this routine was called to make a primary
1.2417 - ** key out of the last column added to the table under construction.
1.2418 - ** So create a fake list to simulate this.
1.2419 - */
1.2420 - if( pList==0 ){
1.2421 - nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
1.2422 - nullId.n = strlen((char*)nullId.z);
1.2423 - pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
1.2424 - if( pList==0 ) goto exit_create_index;
1.2425 - pList->a[0].sortOrder = sortOrder;
1.2426 - }
1.2427 -
1.2428 - /* Figure out how many bytes of space are required to store explicitly
1.2429 - ** specified collation sequence names.
1.2430 - */
1.2431 - for(i=0; i<pList->nExpr; i++){
1.2432 - Expr *pExpr = pList->a[i].pExpr;
1.2433 - if( pExpr ){
1.2434 - nExtra += (1 + strlen(pExpr->pColl->zName));
1.2435 - }
1.2436 - }
1.2437 -
1.2438 - /*
1.2439 - ** Allocate the index structure.
1.2440 - */
1.2441 - nName = strlen(zName);
1.2442 - nCol = pList->nExpr;
1.2443 - pIndex = sqlite3DbMallocZero(db,
1.2444 - sizeof(Index) + /* Index structure */
1.2445 - sizeof(int)*nCol + /* Index.aiColumn */
1.2446 - sizeof(int)*(nCol+1) + /* Index.aiRowEst */
1.2447 - sizeof(char *)*nCol + /* Index.azColl */
1.2448 - sizeof(u8)*nCol + /* Index.aSortOrder */
1.2449 - nName + 1 + /* Index.zName */
1.2450 - nExtra /* Collation sequence names */
1.2451 - );
1.2452 - if( db->mallocFailed ){
1.2453 - goto exit_create_index;
1.2454 - }
1.2455 - pIndex->azColl = (char**)(&pIndex[1]);
1.2456 - pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
1.2457 - pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
1.2458 - pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
1.2459 - pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
1.2460 - zExtra = (char *)(&pIndex->zName[nName+1]);
1.2461 - memcpy(pIndex->zName, zName, nName+1);
1.2462 - pIndex->pTable = pTab;
1.2463 - pIndex->nColumn = pList->nExpr;
1.2464 - pIndex->onError = onError;
1.2465 - pIndex->autoIndex = pName==0;
1.2466 - pIndex->pSchema = db->aDb[iDb].pSchema;
1.2467 -
1.2468 - /* Check to see if we should honor DESC requests on index columns
1.2469 - */
1.2470 - if( pDb->pSchema->file_format>=4 ){
1.2471 - sortOrderMask = -1; /* Honor DESC */
1.2472 - }else{
1.2473 - sortOrderMask = 0; /* Ignore DESC */
1.2474 - }
1.2475 -
1.2476 - /* Scan the names of the columns of the table to be indexed and
1.2477 - ** load the column indices into the Index structure. Report an error
1.2478 - ** if any column is not found.
1.2479 - */
1.2480 - for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
1.2481 - const char *zColName = pListItem->zName;
1.2482 - Column *pTabCol;
1.2483 - int requestedSortOrder;
1.2484 - char *zColl; /* Collation sequence name */
1.2485 -
1.2486 - for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
1.2487 - if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
1.2488 - }
1.2489 - if( j>=pTab->nCol ){
1.2490 - sqlite3ErrorMsg(pParse, "table %s has no column named %s",
1.2491 - pTab->zName, zColName);
1.2492 - goto exit_create_index;
1.2493 - }
1.2494 - /* TODO: Add a test to make sure that the same column is not named
1.2495 - ** more than once within the same index. Only the first instance of
1.2496 - ** the column will ever be used by the optimizer. Note that using the
1.2497 - ** same column more than once cannot be an error because that would
1.2498 - ** break backwards compatibility - it needs to be a warning.
1.2499 - */
1.2500 - pIndex->aiColumn[i] = j;
1.2501 - if( pListItem->pExpr ){
1.2502 - assert( pListItem->pExpr->pColl );
1.2503 - zColl = zExtra;
1.2504 - sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
1.2505 - zExtra += (strlen(zColl) + 1);
1.2506 - }else{
1.2507 - zColl = pTab->aCol[j].zColl;
1.2508 - if( !zColl ){
1.2509 - zColl = db->pDfltColl->zName;
1.2510 - }
1.2511 - }
1.2512 - if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
1.2513 - goto exit_create_index;
1.2514 - }
1.2515 - pIndex->azColl[i] = zColl;
1.2516 - requestedSortOrder = pListItem->sortOrder & sortOrderMask;
1.2517 - pIndex->aSortOrder[i] = requestedSortOrder;
1.2518 - }
1.2519 - sqlite3DefaultRowEst(pIndex);
1.2520 -
1.2521 - if( pTab==pParse->pNewTable ){
1.2522 - /* This routine has been called to create an automatic index as a
1.2523 - ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
1.2524 - ** a PRIMARY KEY or UNIQUE clause following the column definitions.
1.2525 - ** i.e. one of:
1.2526 - **
1.2527 - ** CREATE TABLE t(x PRIMARY KEY, y);
1.2528 - ** CREATE TABLE t(x, y, UNIQUE(x, y));
1.2529 - **
1.2530 - ** Either way, check to see if the table already has such an index. If
1.2531 - ** so, don't bother creating this one. This only applies to
1.2532 - ** automatically created indices. Users can do as they wish with
1.2533 - ** explicit indices.
1.2534 - */
1.2535 - Index *pIdx;
1.2536 - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1.2537 - int k;
1.2538 - assert( pIdx->onError!=OE_None );
1.2539 - assert( pIdx->autoIndex );
1.2540 - assert( pIndex->onError!=OE_None );
1.2541 -
1.2542 - if( pIdx->nColumn!=pIndex->nColumn ) continue;
1.2543 - for(k=0; k<pIdx->nColumn; k++){
1.2544 - const char *z1 = pIdx->azColl[k];
1.2545 - const char *z2 = pIndex->azColl[k];
1.2546 - if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
1.2547 - if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
1.2548 - if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
1.2549 - }
1.2550 - if( k==pIdx->nColumn ){
1.2551 - if( pIdx->onError!=pIndex->onError ){
1.2552 - /* This constraint creates the same index as a previous
1.2553 - ** constraint specified somewhere in the CREATE TABLE statement.
1.2554 - ** However the ON CONFLICT clauses are different. If both this
1.2555 - ** constraint and the previous equivalent constraint have explicit
1.2556 - ** ON CONFLICT clauses this is an error. Otherwise, use the
1.2557 - ** explicitly specified behaviour for the index.
1.2558 - */
1.2559 - if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
1.2560 - sqlite3ErrorMsg(pParse,
1.2561 - "conflicting ON CONFLICT clauses specified", 0);
1.2562 - }
1.2563 - if( pIdx->onError==OE_Default ){
1.2564 - pIdx->onError = pIndex->onError;
1.2565 - }
1.2566 - }
1.2567 - goto exit_create_index;
1.2568 - }
1.2569 - }
1.2570 - }
1.2571 -
1.2572 - /* Link the new Index structure to its table and to the other
1.2573 - ** in-memory database structures.
1.2574 - */
1.2575 - if( db->init.busy ){
1.2576 - Index *p;
1.2577 - p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
1.2578 - pIndex->zName, strlen(pIndex->zName)+1, pIndex);
1.2579 - if( p ){
1.2580 - assert( p==pIndex ); /* Malloc must have failed */
1.2581 - db->mallocFailed = 1;
1.2582 - goto exit_create_index;
1.2583 - }
1.2584 - db->flags |= SQLITE_InternChanges;
1.2585 - if( pTblName!=0 ){
1.2586 - pIndex->tnum = db->init.newTnum;
1.2587 - }
1.2588 - }
1.2589 -
1.2590 - /* If the db->init.busy is 0 then create the index on disk. This
1.2591 - ** involves writing the index into the master table and filling in the
1.2592 - ** index with the current table contents.
1.2593 - **
1.2594 - ** The db->init.busy is 0 when the user first enters a CREATE INDEX
1.2595 - ** command. db->init.busy is 1 when a database is opened and
1.2596 - ** CREATE INDEX statements are read out of the master table. In
1.2597 - ** the latter case the index already exists on disk, which is why
1.2598 - ** we don't want to recreate it.
1.2599 - **
1.2600 - ** If pTblName==0 it means this index is generated as a primary key
1.2601 - ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
1.2602 - ** has just been created, it contains no data and the index initialization
1.2603 - ** step can be skipped.
1.2604 - */
1.2605 - else if( db->init.busy==0 ){
1.2606 - Vdbe *v;
1.2607 - char *zStmt;
1.2608 - int iMem = pParse->nMem++;
1.2609 -
1.2610 - v = sqlite3GetVdbe(pParse);
1.2611 - if( v==0 ) goto exit_create_index;
1.2612 -
1.2613 -
1.2614 - /* Create the rootpage for the index
1.2615 - */
1.2616 - sqlite3BeginWriteOperation(pParse, 1, iDb);
1.2617 - sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
1.2618 - sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
1.2619 -
1.2620 - /* Gather the complete text of the CREATE INDEX statement into
1.2621 - ** the zStmt variable
1.2622 - */
1.2623 - if( pStart && pEnd ){
1.2624 - /* A named index with an explicit CREATE INDEX statement */
1.2625 - zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
1.2626 - onError==OE_None ? "" : " UNIQUE",
1.2627 - pEnd->z - pName->z + 1,
1.2628 - pName->z);
1.2629 - }else{
1.2630 - /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
1.2631 - /* zStmt = sqlite3MPrintf(""); */
1.2632 - zStmt = 0;
1.2633 - }
1.2634 -
1.2635 - /* Add an entry in sqlite_master for this index
1.2636 - */
1.2637 - sqlite3NestedParse(pParse,
1.2638 - "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
1.2639 - db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1.2640 - pIndex->zName,
1.2641 - pTab->zName,
1.2642 - zStmt
1.2643 - );
1.2644 - sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
1.2645 - sqlite3_free(zStmt);
1.2646 -
1.2647 - /* Fill the index with data and reparse the schema. Code an OP_Expire
1.2648 - ** to invalidate all pre-compiled statements.
1.2649 - */
1.2650 - if( pTblName ){
1.2651 - sqlite3RefillIndex(pParse, pIndex, iMem);
1.2652 - sqlite3ChangeCookie(db, v, iDb);
1.2653 - sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
1.2654 - sqlite3MPrintf(db, "name='%q'", pIndex->zName), P3_DYNAMIC);
1.2655 - sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
1.2656 - }
1.2657 - }
1.2658 -
1.2659 - /* When adding an index to the list of indices for a table, make
1.2660 - ** sure all indices labeled OE_Replace come after all those labeled
1.2661 - ** OE_Ignore. This is necessary for the correct operation of UPDATE
1.2662 - ** and INSERT.
1.2663 - */
1.2664 - if( db->init.busy || pTblName==0 ){
1.2665 - if( onError!=OE_Replace || pTab->pIndex==0
1.2666 - || pTab->pIndex->onError==OE_Replace){
1.2667 - pIndex->pNext = pTab->pIndex;
1.2668 - pTab->pIndex = pIndex;
1.2669 - }else{
1.2670 - Index *pOther = pTab->pIndex;
1.2671 - while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
1.2672 - pOther = pOther->pNext;
1.2673 - }
1.2674 - pIndex->pNext = pOther->pNext;
1.2675 - pOther->pNext = pIndex;
1.2676 - }
1.2677 - pIndex = 0;
1.2678 - }
1.2679 -
1.2680 - /* Clean up before exiting */
1.2681 -exit_create_index:
1.2682 - if( pIndex ){
1.2683 - freeIndex(pIndex);
1.2684 - }
1.2685 - sqlite3ExprListDelete(pList);
1.2686 - sqlite3SrcListDelete(pTblName);
1.2687 - sqlite3_free(zName);
1.2688 - return;
1.2689 -}
1.2690 -
1.2691 -/*
1.2692 -** Generate code to make sure the file format number is at least minFormat.
1.2693 -** The generated code will increase the file format number if necessary.
1.2694 -*/
1.2695 -void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
1.2696 - Vdbe *v;
1.2697 - v = sqlite3GetVdbe(pParse);
1.2698 - if( v ){
1.2699 - sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
1.2700 - sqlite3VdbeUsesBtree(v, iDb);
1.2701 - sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
1.2702 - sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
1.2703 - sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
1.2704 - sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
1.2705 - }
1.2706 -}
1.2707 -
1.2708 -/*
1.2709 -** Fill the Index.aiRowEst[] array with default information - information
1.2710 -** to be used when we have not run the ANALYZE command.
1.2711 -**
1.2712 -** aiRowEst[0] is suppose to contain the number of elements in the index.
1.2713 -** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
1.2714 -** number of rows in the table that match any particular value of the
1.2715 -** first column of the index. aiRowEst[2] is an estimate of the number
1.2716 -** of rows that match any particular combiniation of the first 2 columns
1.2717 -** of the index. And so forth. It must always be the case that
1.2718 -*
1.2719 -** aiRowEst[N]<=aiRowEst[N-1]
1.2720 -** aiRowEst[N]>=1
1.2721 -**
1.2722 -** Apart from that, we have little to go on besides intuition as to
1.2723 -** how aiRowEst[] should be initialized. The numbers generated here
1.2724 -** are based on typical values found in actual indices.
1.2725 -*/
1.2726 -void sqlite3DefaultRowEst(Index *pIdx){
1.2727 - unsigned *a = pIdx->aiRowEst;
1.2728 - int i;
1.2729 - assert( a!=0 );
1.2730 - a[0] = 1000000;
1.2731 - for(i=pIdx->nColumn; i>=5; i--){
1.2732 - a[i] = 5;
1.2733 - }
1.2734 - while( i>=1 ){
1.2735 - a[i] = 11 - i;
1.2736 - i--;
1.2737 - }
1.2738 - if( pIdx->onError!=OE_None ){
1.2739 - a[pIdx->nColumn] = 1;
1.2740 - }
1.2741 -}
1.2742 -
1.2743 -/*
1.2744 -** This routine will drop an existing named index. This routine
1.2745 -** implements the DROP INDEX statement.
1.2746 -*/
1.2747 -void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
1.2748 - Index *pIndex;
1.2749 - Vdbe *v;
1.2750 - sqlite3 *db = pParse->db;
1.2751 - int iDb;
1.2752 -
1.2753 - if( pParse->nErr || db->mallocFailed ){
1.2754 - goto exit_drop_index;
1.2755 - }
1.2756 - assert( pName->nSrc==1 );
1.2757 - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1.2758 - goto exit_drop_index;
1.2759 - }
1.2760 - pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
1.2761 - if( pIndex==0 ){
1.2762 - if( !ifExists ){
1.2763 - sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
1.2764 - }
1.2765 - pParse->checkSchema = 1;
1.2766 - goto exit_drop_index;
1.2767 - }
1.2768 - if( pIndex->autoIndex ){
1.2769 - sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
1.2770 - "or PRIMARY KEY constraint cannot be dropped", 0);
1.2771 - goto exit_drop_index;
1.2772 - }
1.2773 - iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
1.2774 -#ifndef SQLITE_OMIT_AUTHORIZATION
1.2775 - {
1.2776 - int code = SQLITE_DROP_INDEX;
1.2777 - Table *pTab = pIndex->pTable;
1.2778 - const char *zDb = db->aDb[iDb].zName;
1.2779 - const char *zTab = SCHEMA_TABLE(iDb);
1.2780 - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
1.2781 - goto exit_drop_index;
1.2782 - }
1.2783 - if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
1.2784 - if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
1.2785 - goto exit_drop_index;
1.2786 - }
1.2787 - }
1.2788 -#endif
1.2789 -
1.2790 - /* Generate code to remove the index and from the master table */
1.2791 - v = sqlite3GetVdbe(pParse);
1.2792 - if( v ){
1.2793 - sqlite3NestedParse(pParse,
1.2794 - "DELETE FROM %Q.%s WHERE name=%Q",
1.2795 - db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1.2796 - pIndex->zName
1.2797 - );
1.2798 - sqlite3ChangeCookie(db, v, iDb);
1.2799 - destroyRootPage(pParse, pIndex->tnum, iDb);
1.2800 - sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
1.2801 - }
1.2802 -
1.2803 -exit_drop_index:
1.2804 - sqlite3SrcListDelete(pName);
1.2805 -}
1.2806 -
1.2807 -/*
1.2808 -** pArray is a pointer to an array of objects. Each object in the
1.2809 -** array is szEntry bytes in size. This routine allocates a new
1.2810 -** object on the end of the array.
1.2811 -**
1.2812 -** *pnEntry is the number of entries already in use. *pnAlloc is
1.2813 -** the previously allocated size of the array. initSize is the
1.2814 -** suggested initial array size allocation.
1.2815 -**
1.2816 -** The index of the new entry is returned in *pIdx.
1.2817 -**
1.2818 -** This routine returns a pointer to the array of objects. This
1.2819 -** might be the same as the pArray parameter or it might be a different
1.2820 -** pointer if the array was resized.
1.2821 -*/
1.2822 -void *sqlite3ArrayAllocate(
1.2823 - sqlite3 *db, /* Connection to notify of malloc failures */
1.2824 - void *pArray, /* Array of objects. Might be reallocated */
1.2825 - int szEntry, /* Size of each object in the array */
1.2826 - int initSize, /* Suggested initial allocation, in elements */
1.2827 - int *pnEntry, /* Number of objects currently in use */
1.2828 - int *pnAlloc, /* Current size of the allocation, in elements */
1.2829 - int *pIdx /* Write the index of a new slot here */
1.2830 -){
1.2831 - char *z;
1.2832 - if( *pnEntry >= *pnAlloc ){
1.2833 - void *pNew;
1.2834 - int newSize;
1.2835 - newSize = (*pnAlloc)*2 + initSize;
1.2836 - pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
1.2837 - if( pNew==0 ){
1.2838 - *pIdx = -1;
1.2839 - return pArray;
1.2840 - }
1.2841 - *pnAlloc = newSize;
1.2842 - pArray = pNew;
1.2843 - }
1.2844 - z = (char*)pArray;
1.2845 - memset(&z[*pnEntry * szEntry], 0, szEntry);
1.2846 - *pIdx = *pnEntry;
1.2847 - ++*pnEntry;
1.2848 - return pArray;
1.2849 -}
1.2850 -
1.2851 -/*
1.2852 -** Append a new element to the given IdList. Create a new IdList if
1.2853 -** need be.
1.2854 -**
1.2855 -** A new IdList is returned, or NULL if malloc() fails.
1.2856 -*/
1.2857 -IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
1.2858 - int i;
1.2859 - if( pList==0 ){
1.2860 - pList = sqlite3DbMallocZero(db, sizeof(IdList) );
1.2861 - if( pList==0 ) return 0;
1.2862 - pList->nAlloc = 0;
1.2863 - }
1.2864 - pList->a = sqlite3ArrayAllocate(
1.2865 - db,
1.2866 - pList->a,
1.2867 - sizeof(pList->a[0]),
1.2868 - 5,
1.2869 - &pList->nId,
1.2870 - &pList->nAlloc,
1.2871 - &i
1.2872 - );
1.2873 - if( i<0 ){
1.2874 - sqlite3IdListDelete(pList);
1.2875 - return 0;
1.2876 - }
1.2877 - pList->a[i].zName = sqlite3NameFromToken(db, pToken);
1.2878 - return pList;
1.2879 -}
1.2880 -
1.2881 -/*
1.2882 -** Delete an IdList.
1.2883 -*/
1.2884 -void sqlite3IdListDelete(IdList *pList){
1.2885 - int i;
1.2886 - if( pList==0 ) return;
1.2887 - for(i=0; i<pList->nId; i++){
1.2888 - sqlite3_free(pList->a[i].zName);
1.2889 - }
1.2890 - sqlite3_free(pList->a);
1.2891 - sqlite3_free(pList);
1.2892 -}
1.2893 -
1.2894 -/*
1.2895 -** Return the index in pList of the identifier named zId. Return -1
1.2896 -** if not found.
1.2897 -*/
1.2898 -int sqlite3IdListIndex(IdList *pList, const char *zName){
1.2899 - int i;
1.2900 - if( pList==0 ) return -1;
1.2901 - for(i=0; i<pList->nId; i++){
1.2902 - if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
1.2903 - }
1.2904 - return -1;
1.2905 -}
1.2906 -
1.2907 -/*
1.2908 -** Append a new table name to the given SrcList. Create a new SrcList if
1.2909 -** need be. A new entry is created in the SrcList even if pToken is NULL.
1.2910 -**
1.2911 -** A new SrcList is returned, or NULL if malloc() fails.
1.2912 -**
1.2913 -** If pDatabase is not null, it means that the table has an optional
1.2914 -** database name prefix. Like this: "database.table". The pDatabase
1.2915 -** points to the table name and the pTable points to the database name.
1.2916 -** The SrcList.a[].zName field is filled with the table name which might
1.2917 -** come from pTable (if pDatabase is NULL) or from pDatabase.
1.2918 -** SrcList.a[].zDatabase is filled with the database name from pTable,
1.2919 -** or with NULL if no database is specified.
1.2920 -**
1.2921 -** In other words, if call like this:
1.2922 -**
1.2923 -** sqlite3SrcListAppend(D,A,B,0);
1.2924 -**
1.2925 -** Then B is a table name and the database name is unspecified. If called
1.2926 -** like this:
1.2927 -**
1.2928 -** sqlite3SrcListAppend(D,A,B,C);
1.2929 -**
1.2930 -** Then C is the table name and B is the database name.
1.2931 -*/
1.2932 -SrcList *sqlite3SrcListAppend(
1.2933 - sqlite3 *db, /* Connection to notify of malloc failures */
1.2934 - SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
1.2935 - Token *pTable, /* Table to append */
1.2936 - Token *pDatabase /* Database of the table */
1.2937 -){
1.2938 - struct SrcList_item *pItem;
1.2939 - if( pList==0 ){
1.2940 - pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
1.2941 - if( pList==0 ) return 0;
1.2942 - pList->nAlloc = 1;
1.2943 - }
1.2944 - if( pList->nSrc>=pList->nAlloc ){
1.2945 - SrcList *pNew;
1.2946 - pList->nAlloc *= 2;
1.2947 - pNew = sqlite3DbRealloc(db, pList,
1.2948 - sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
1.2949 - if( pNew==0 ){
1.2950 - sqlite3SrcListDelete(pList);
1.2951 - return 0;
1.2952 - }
1.2953 - pList = pNew;
1.2954 - }
1.2955 - pItem = &pList->a[pList->nSrc];
1.2956 - memset(pItem, 0, sizeof(pList->a[0]));
1.2957 - if( pDatabase && pDatabase->z==0 ){
1.2958 - pDatabase = 0;
1.2959 - }
1.2960 - if( pDatabase && pTable ){
1.2961 - Token *pTemp = pDatabase;
1.2962 - pDatabase = pTable;
1.2963 - pTable = pTemp;
1.2964 - }
1.2965 - pItem->zName = sqlite3NameFromToken(db, pTable);
1.2966 - pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
1.2967 - pItem->iCursor = -1;
1.2968 - pItem->isPopulated = 0;
1.2969 - pList->nSrc++;
1.2970 - return pList;
1.2971 -}
1.2972 -
1.2973 -/*
1.2974 -** Assign cursors to all tables in a SrcList
1.2975 -*/
1.2976 -void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
1.2977 - int i;
1.2978 - struct SrcList_item *pItem;
1.2979 - assert(pList || pParse->db->mallocFailed );
1.2980 - if( pList ){
1.2981 - for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
1.2982 - if( pItem->iCursor>=0 ) break;
1.2983 - pItem->iCursor = pParse->nTab++;
1.2984 - if( pItem->pSelect ){
1.2985 - sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
1.2986 - }
1.2987 - }
1.2988 - }
1.2989 -}
1.2990 -
1.2991 -/*
1.2992 -** Delete an entire SrcList including all its substructure.
1.2993 -*/
1.2994 -void sqlite3SrcListDelete(SrcList *pList){
1.2995 - int i;
1.2996 - struct SrcList_item *pItem;
1.2997 - if( pList==0 ) return;
1.2998 - for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
1.2999 - sqlite3_free(pItem->zDatabase);
1.3000 - sqlite3_free(pItem->zName);
1.3001 - sqlite3_free(pItem->zAlias);
1.3002 - sqlite3DeleteTable(pItem->pTab);
1.3003 - sqlite3SelectDelete(pItem->pSelect);
1.3004 - sqlite3ExprDelete(pItem->pOn);
1.3005 - sqlite3IdListDelete(pItem->pUsing);
1.3006 - }
1.3007 - sqlite3_free(pList);
1.3008 -}
1.3009 -
1.3010 -/*
1.3011 -** This routine is called by the parser to add a new term to the
1.3012 -** end of a growing FROM clause. The "p" parameter is the part of
1.3013 -** the FROM clause that has already been constructed. "p" is NULL
1.3014 -** if this is the first term of the FROM clause. pTable and pDatabase
1.3015 -** are the name of the table and database named in the FROM clause term.
1.3016 -** pDatabase is NULL if the database name qualifier is missing - the
1.3017 -** usual case. If the term has a alias, then pAlias points to the
1.3018 -** alias token. If the term is a subquery, then pSubquery is the
1.3019 -** SELECT statement that the subquery encodes. The pTable and
1.3020 -** pDatabase parameters are NULL for subqueries. The pOn and pUsing
1.3021 -** parameters are the content of the ON and USING clauses.
1.3022 -**
1.3023 -** Return a new SrcList which encodes is the FROM with the new
1.3024 -** term added.
1.3025 -*/
1.3026 -SrcList *sqlite3SrcListAppendFromTerm(
1.3027 - Parse *pParse, /* Parsing context */
1.3028 - SrcList *p, /* The left part of the FROM clause already seen */
1.3029 - Token *pTable, /* Name of the table to add to the FROM clause */
1.3030 - Token *pDatabase, /* Name of the database containing pTable */
1.3031 - Token *pAlias, /* The right-hand side of the AS subexpression */
1.3032 - Select *pSubquery, /* A subquery used in place of a table name */
1.3033 - Expr *pOn, /* The ON clause of a join */
1.3034 - IdList *pUsing /* The USING clause of a join */
1.3035 -){
1.3036 - struct SrcList_item *pItem;
1.3037 - sqlite3 *db = pParse->db;
1.3038 - p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
1.3039 - if( p==0 || p->nSrc==0 ){
1.3040 - sqlite3ExprDelete(pOn);
1.3041 - sqlite3IdListDelete(pUsing);
1.3042 - sqlite3SelectDelete(pSubquery);
1.3043 - return p;
1.3044 - }
1.3045 - pItem = &p->a[p->nSrc-1];
1.3046 - if( pAlias && pAlias->n ){
1.3047 - pItem->zAlias = sqlite3NameFromToken(db, pAlias);
1.3048 - }
1.3049 - pItem->pSelect = pSubquery;
1.3050 - pItem->pOn = pOn;
1.3051 - pItem->pUsing = pUsing;
1.3052 - return p;
1.3053 -}
1.3054 -
1.3055 -/*
1.3056 -** When building up a FROM clause in the parser, the join operator
1.3057 -** is initially attached to the left operand. But the code generator
1.3058 -** expects the join operator to be on the right operand. This routine
1.3059 -** Shifts all join operators from left to right for an entire FROM
1.3060 -** clause.
1.3061 -**
1.3062 -** Example: Suppose the join is like this:
1.3063 -**
1.3064 -** A natural cross join B
1.3065 -**
1.3066 -** The operator is "natural cross join". The A and B operands are stored
1.3067 -** in p->a[0] and p->a[1], respectively. The parser initially stores the
1.3068 -** operator with A. This routine shifts that operator over to B.
1.3069 -*/
1.3070 -void sqlite3SrcListShiftJoinType(SrcList *p){
1.3071 - if( p && p->a ){
1.3072 - int i;
1.3073 - for(i=p->nSrc-1; i>0; i--){
1.3074 - p->a[i].jointype = p->a[i-1].jointype;
1.3075 - }
1.3076 - p->a[0].jointype = 0;
1.3077 - }
1.3078 -}
1.3079 -
1.3080 -/*
1.3081 -** Begin a transaction
1.3082 -*/
1.3083 -void sqlite3BeginTransaction(Parse *pParse, int type){
1.3084 - sqlite3 *db;
1.3085 - Vdbe *v;
1.3086 - int i;
1.3087 -
1.3088 - if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
1.3089 - if( pParse->nErr || db->mallocFailed ) return;
1.3090 - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
1.3091 -
1.3092 - v = sqlite3GetVdbe(pParse);
1.3093 - if( !v ) return;
1.3094 - if( type!=TK_DEFERRED ){
1.3095 - for(i=0; i<db->nDb; i++){
1.3096 - sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
1.3097 - sqlite3VdbeUsesBtree(v, i);
1.3098 - }
1.3099 - }
1.3100 - sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
1.3101 -}
1.3102 -
1.3103 -/*
1.3104 -** Commit a transaction
1.3105 -*/
1.3106 -void sqlite3CommitTransaction(Parse *pParse){
1.3107 - sqlite3 *db;
1.3108 - Vdbe *v;
1.3109 -
1.3110 - if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
1.3111 - if( pParse->nErr || db->mallocFailed ) return;
1.3112 - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
1.3113 -
1.3114 - v = sqlite3GetVdbe(pParse);
1.3115 - if( v ){
1.3116 - sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
1.3117 - }
1.3118 -}
1.3119 -
1.3120 -/*
1.3121 -** Rollback a transaction
1.3122 -*/
1.3123 -void sqlite3RollbackTransaction(Parse *pParse){
1.3124 - sqlite3 *db;
1.3125 - Vdbe *v;
1.3126 -
1.3127 - if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
1.3128 - if( pParse->nErr || db->mallocFailed ) return;
1.3129 - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
1.3130 -
1.3131 - v = sqlite3GetVdbe(pParse);
1.3132 - if( v ){
1.3133 - sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
1.3134 - }
1.3135 -}
1.3136 -
1.3137 -/*
1.3138 -** Make sure the TEMP database is open and available for use. Return
1.3139 -** the number of errors. Leave any error messages in the pParse structure.
1.3140 -*/
1.3141 -int sqlite3OpenTempDatabase(Parse *pParse){
1.3142 - sqlite3 *db = pParse->db;
1.3143 - if( db->aDb[1].pBt==0 && !pParse->explain ){
1.3144 - int rc;
1.3145 - static const int flags =
1.3146 - SQLITE_OPEN_READWRITE |
1.3147 - SQLITE_OPEN_CREATE |
1.3148 - SQLITE_OPEN_EXCLUSIVE |
1.3149 - SQLITE_OPEN_DELETEONCLOSE |
1.3150 - SQLITE_OPEN_TEMP_DB;
1.3151 -
1.3152 - rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
1.3153 - &db->aDb[1].pBt);
1.3154 - if( rc!=SQLITE_OK ){
1.3155 - sqlite3ErrorMsg(pParse, "unable to open a temporary database "
1.3156 - "file for storing temporary tables");
1.3157 - pParse->rc = rc;
1.3158 - return 1;
1.3159 - }
1.3160 - if( db->flags & !db->autoCommit ){
1.3161 - rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
1.3162 - if( rc!=SQLITE_OK ){
1.3163 - sqlite3ErrorMsg(pParse, "unable to get a write lock on "
1.3164 - "the temporary database file");
1.3165 - pParse->rc = rc;
1.3166 - return 1;
1.3167 - }
1.3168 - }
1.3169 - assert( db->aDb[1].pSchema );
1.3170 - }
1.3171 - return 0;
1.3172 -}
1.3173 -
1.3174 -/*
1.3175 -** Generate VDBE code that will verify the schema cookie and start
1.3176 -** a read-transaction for all named database files.
1.3177 -**
1.3178 -** It is important that all schema cookies be verified and all
1.3179 -** read transactions be started before anything else happens in
1.3180 -** the VDBE program. But this routine can be called after much other
1.3181 -** code has been generated. So here is what we do:
1.3182 -**
1.3183 -** The first time this routine is called, we code an OP_Goto that
1.3184 -** will jump to a subroutine at the end of the program. Then we
1.3185 -** record every database that needs its schema verified in the
1.3186 -** pParse->cookieMask field. Later, after all other code has been
1.3187 -** generated, the subroutine that does the cookie verifications and
1.3188 -** starts the transactions will be coded and the OP_Goto P2 value
1.3189 -** will be made to point to that subroutine. The generation of the
1.3190 -** cookie verification subroutine code happens in sqlite3FinishCoding().
1.3191 -**
1.3192 -** If iDb<0 then code the OP_Goto only - don't set flag to verify the
1.3193 -** schema on any databases. This can be used to position the OP_Goto
1.3194 -** early in the code, before we know if any database tables will be used.
1.3195 -*/
1.3196 -void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
1.3197 - sqlite3 *db;
1.3198 - Vdbe *v;
1.3199 - int mask;
1.3200 -
1.3201 - v = sqlite3GetVdbe(pParse);
1.3202 - if( v==0 ) return; /* This only happens if there was a prior error */
1.3203 - db = pParse->db;
1.3204 - if( pParse->cookieGoto==0 ){
1.3205 - pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
1.3206 - }
1.3207 - if( iDb>=0 ){
1.3208 - assert( iDb<db->nDb );
1.3209 - assert( db->aDb[iDb].pBt!=0 || iDb==1 );
1.3210 - assert( iDb<SQLITE_MAX_ATTACHED+2 );
1.3211 - mask = 1<<iDb;
1.3212 - if( (pParse->cookieMask & mask)==0 ){
1.3213 - pParse->cookieMask |= mask;
1.3214 - pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
1.3215 - if( !OMIT_TEMPDB && iDb==1 ){
1.3216 - sqlite3OpenTempDatabase(pParse);
1.3217 - }
1.3218 - }
1.3219 - }
1.3220 -}
1.3221 -
1.3222 -/*
1.3223 -** Generate VDBE code that prepares for doing an operation that
1.3224 -** might change the database.
1.3225 -**
1.3226 -** This routine starts a new transaction if we are not already within
1.3227 -** a transaction. If we are already within a transaction, then a checkpoint
1.3228 -** is set if the setStatement parameter is true. A checkpoint should
1.3229 -** be set for operations that might fail (due to a constraint) part of
1.3230 -** the way through and which will need to undo some writes without having to
1.3231 -** rollback the whole transaction. For operations where all constraints
1.3232 -** can be checked before any changes are made to the database, it is never
1.3233 -** necessary to undo a write and the checkpoint should not be set.
1.3234 -**
1.3235 -** Only database iDb and the temp database are made writable by this call.
1.3236 -** If iDb==0, then the main and temp databases are made writable. If
1.3237 -** iDb==1 then only the temp database is made writable. If iDb>1 then the
1.3238 -** specified auxiliary database and the temp database are made writable.
1.3239 -*/
1.3240 -void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
1.3241 - Vdbe *v = sqlite3GetVdbe(pParse);
1.3242 - if( v==0 ) return;
1.3243 - sqlite3CodeVerifySchema(pParse, iDb);
1.3244 - pParse->writeMask |= 1<<iDb;
1.3245 - if( setStatement && pParse->nested==0 ){
1.3246 - sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
1.3247 - }
1.3248 - if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
1.3249 - sqlite3BeginWriteOperation(pParse, setStatement, 1);
1.3250 - }
1.3251 -}
1.3252 -
1.3253 -/*
1.3254 -** Check to see if pIndex uses the collating sequence pColl. Return
1.3255 -** true if it does and false if it does not.
1.3256 -*/
1.3257 -#ifndef SQLITE_OMIT_REINDEX
1.3258 -static int collationMatch(const char *zColl, Index *pIndex){
1.3259 - int i;
1.3260 - for(i=0; i<pIndex->nColumn; i++){
1.3261 - const char *z = pIndex->azColl[i];
1.3262 - if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
1.3263 - return 1;
1.3264 - }
1.3265 - }
1.3266 - return 0;
1.3267 -}
1.3268 -#endif
1.3269 -
1.3270 -/*
1.3271 -** Recompute all indices of pTab that use the collating sequence pColl.
1.3272 -** If pColl==0 then recompute all indices of pTab.
1.3273 -*/
1.3274 -#ifndef SQLITE_OMIT_REINDEX
1.3275 -static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
1.3276 - Index *pIndex; /* An index associated with pTab */
1.3277 -
1.3278 - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
1.3279 - if( zColl==0 || collationMatch(zColl, pIndex) ){
1.3280 - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1.3281 - sqlite3BeginWriteOperation(pParse, 0, iDb);
1.3282 - sqlite3RefillIndex(pParse, pIndex, -1);
1.3283 - }
1.3284 - }
1.3285 -}
1.3286 -#endif
1.3287 -
1.3288 -/*
1.3289 -** Recompute all indices of all tables in all databases where the
1.3290 -** indices use the collating sequence pColl. If pColl==0 then recompute
1.3291 -** all indices everywhere.
1.3292 -*/
1.3293 -#ifndef SQLITE_OMIT_REINDEX
1.3294 -static void reindexDatabases(Parse *pParse, char const *zColl){
1.3295 - Db *pDb; /* A single database */
1.3296 - int iDb; /* The database index number */
1.3297 - sqlite3 *db = pParse->db; /* The database connection */
1.3298 - HashElem *k; /* For looping over tables in pDb */
1.3299 - Table *pTab; /* A table in the database */
1.3300 -
1.3301 - for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
1.3302 - assert( pDb!=0 );
1.3303 - for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
1.3304 - pTab = (Table*)sqliteHashData(k);
1.3305 - reindexTable(pParse, pTab, zColl);
1.3306 - }
1.3307 - }
1.3308 -}
1.3309 -#endif
1.3310 -
1.3311 -/*
1.3312 -** Generate code for the REINDEX command.
1.3313 -**
1.3314 -** REINDEX -- 1
1.3315 -** REINDEX <collation> -- 2
1.3316 -** REINDEX ?<database>.?<tablename> -- 3
1.3317 -** REINDEX ?<database>.?<indexname> -- 4
1.3318 -**
1.3319 -** Form 1 causes all indices in all attached databases to be rebuilt.
1.3320 -** Form 2 rebuilds all indices in all databases that use the named
1.3321 -** collating function. Forms 3 and 4 rebuild the named index or all
1.3322 -** indices associated with the named table.
1.3323 -*/
1.3324 -#ifndef SQLITE_OMIT_REINDEX
1.3325 -void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
1.3326 - CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
1.3327 - char *z; /* Name of a table or index */
1.3328 - const char *zDb; /* Name of the database */
1.3329 - Table *pTab; /* A table in the database */
1.3330 - Index *pIndex; /* An index associated with pTab */
1.3331 - int iDb; /* The database index number */
1.3332 - sqlite3 *db = pParse->db; /* The database connection */
1.3333 - Token *pObjName; /* Name of the table or index to be reindexed */
1.3334 -
1.3335 - /* Read the database schema. If an error occurs, leave an error message
1.3336 - ** and code in pParse and return NULL. */
1.3337 - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1.3338 - return;
1.3339 - }
1.3340 -
1.3341 - if( pName1==0 || pName1->z==0 ){
1.3342 - reindexDatabases(pParse, 0);
1.3343 - return;
1.3344 - }else if( pName2==0 || pName2->z==0 ){
1.3345 - assert( pName1->z );
1.3346 - pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
1.3347 - if( pColl ){
1.3348 - char *zColl = sqlite3DbStrNDup(db, (const char *)pName1->z, pName1->n);
1.3349 - if( zColl ){
1.3350 - reindexDatabases(pParse, zColl);
1.3351 - sqlite3_free(zColl);
1.3352 - }
1.3353 - return;
1.3354 - }
1.3355 - }
1.3356 - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
1.3357 - if( iDb<0 ) return;
1.3358 - z = sqlite3NameFromToken(db, pObjName);
1.3359 - if( z==0 ) return;
1.3360 - zDb = db->aDb[iDb].zName;
1.3361 - pTab = sqlite3FindTable(db, z, zDb);
1.3362 - if( pTab ){
1.3363 - reindexTable(pParse, pTab, 0);
1.3364 - sqlite3_free(z);
1.3365 - return;
1.3366 - }
1.3367 - pIndex = sqlite3FindIndex(db, z, zDb);
1.3368 - sqlite3_free(z);
1.3369 - if( pIndex ){
1.3370 - sqlite3BeginWriteOperation(pParse, 0, iDb);
1.3371 - sqlite3RefillIndex(pParse, pIndex, -1);
1.3372 - return;
1.3373 - }
1.3374 - sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
1.3375 -}
1.3376 -#endif
1.3377 -
1.3378 -/*
1.3379 -** Return a dynamicly allocated KeyInfo structure that can be used
1.3380 -** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
1.3381 -**
1.3382 -** If successful, a pointer to the new structure is returned. In this case
1.3383 -** the caller is responsible for calling sqlite3_free() on the returned
1.3384 -** pointer. If an error occurs (out of memory or missing collation
1.3385 -** sequence), NULL is returned and the state of pParse updated to reflect
1.3386 -** the error.
1.3387 -*/
1.3388 -KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
1.3389 - int i;
1.3390 - int nCol = pIdx->nColumn;
1.3391 - int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
1.3392 - KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes);
1.3393 -
1.3394 - if( pKey ){
1.3395 - pKey->db = pParse->db;
1.3396 - pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
1.3397 - assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
1.3398 - for(i=0; i<nCol; i++){
1.3399 - char *zColl = pIdx->azColl[i];
1.3400 - assert( zColl );
1.3401 - pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
1.3402 - pKey->aSortOrder[i] = pIdx->aSortOrder[i];
1.3403 - }
1.3404 - pKey->nField = nCol;
1.3405 - }
1.3406 -
1.3407 - if( pParse->nErr ){
1.3408 - sqlite3_free(pKey);
1.3409 - pKey = 0;
1.3410 - }
1.3411 - return pKey;
1.3412 -}