Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(61)

Side by Side Diff: third_party/sqlite/sqlite-src-3080704/src/build.c

Issue 883353008: [sql] Import reference version of SQLite 3.8.7.4. (Closed) Base URL: http://chromium.googlesource.com/chromium/src.git@master
Patch Set: Hold back encoding change which is messing up patch. Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 ** 2001 September 15 2 ** 2001 September 15
3 ** 3 **
4 ** The author disclaims copyright to this source code. In place of 4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing: 5 ** a legal notice, here is a blessing:
6 ** 6 **
7 ** May you do good and not evil. 7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others. 8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give. 9 ** May you share freely, never taking more than you give.
10 ** 10 **
(...skipping 96 matching lines...) Expand 10 before | Expand all | Expand 10 after
107 int p1 = p->iDb; 107 int p1 = p->iDb;
108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
109 p->zName, P4_STATIC); 109 p->zName, P4_STATIC);
110 } 110 }
111 } 111 }
112 #else 112 #else
113 #define codeTableLocks(x) 113 #define codeTableLocks(x)
114 #endif 114 #endif
115 115
116 /* 116 /*
117 ** Return TRUE if the given yDbMask object is empty - if it contains no
118 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
119 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
120 */
121 #if SQLITE_MAX_ATTACHED>30
122 int sqlite3DbMaskAllZero(yDbMask m){
123 int i;
124 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
125 return 1;
126 }
127 #endif
128
129 /*
117 ** This routine is called after a single SQL statement has been 130 ** This routine is called after a single SQL statement has been
118 ** parsed and a VDBE program to execute that statement has been 131 ** parsed and a VDBE program to execute that statement has been
119 ** prepared. This routine puts the finishing touches on the 132 ** prepared. This routine puts the finishing touches on the
120 ** VDBE program and resets the pParse structure for the next 133 ** VDBE program and resets the pParse structure for the next
121 ** parse. 134 ** parse.
122 ** 135 **
123 ** Note that if an error occurred, it might be the case that 136 ** Note that if an error occurred, it might be the case that
124 ** no VDBE code was generated. 137 ** no VDBE code was generated.
125 */ 138 */
126 void sqlite3FinishCoding(Parse *pParse){ 139 void sqlite3FinishCoding(Parse *pParse){
127 sqlite3 *db; 140 sqlite3 *db;
128 Vdbe *v; 141 Vdbe *v;
129 142
143 assert( pParse->pToplevel==0 );
130 db = pParse->db; 144 db = pParse->db;
131 if( db->mallocFailed ) return; 145 if( db->mallocFailed ) return;
132 if( pParse->nested ) return; 146 if( pParse->nested ) return;
133 if( pParse->nErr ) return; 147 if( pParse->nErr ) return;
134 148
135 /* Begin by generating some termination code at the end of the 149 /* Begin by generating some termination code at the end of the
136 ** vdbe program 150 ** vdbe program
137 */ 151 */
138 v = sqlite3GetVdbe(pParse); 152 v = sqlite3GetVdbe(pParse);
139 assert( !pParse->isMultiWrite 153 assert( !pParse->isMultiWrite
140 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); 154 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
141 if( v ){ 155 if( v ){
156 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
142 sqlite3VdbeAddOp0(v, OP_Halt); 157 sqlite3VdbeAddOp0(v, OP_Halt);
143 158
159 #if SQLITE_USER_AUTHENTICATION
160 if( pParse->nTableLock>0 && db->init.busy==0 ){
161 sqlite3UserAuthInit(db);
162 if( db->auth.authLevel<UAUTH_User ){
163 pParse->rc = SQLITE_AUTH_USER;
164 sqlite3ErrorMsg(pParse, "user not authenticated");
165 return;
166 }
167 }
168 #endif
169
144 /* The cookie mask contains one bit for each database file open. 170 /* The cookie mask contains one bit for each database file open.
145 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 171 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
146 ** set for each database that is used. Generate code to start a 172 ** set for each database that is used. Generate code to start a
147 ** transaction on each used database and to verify the schema cookie 173 ** transaction on each used database and to verify the schema cookie
148 ** on each used database. 174 ** on each used database.
149 */ 175 */
150 if( pParse->cookieGoto>0 ){ 176 if( db->mallocFailed==0
151 yDbMask mask; 177 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
152 int iDb; 178 ){
153 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); 179 int iDb, i;
154 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){ 180 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
155 if( (mask & pParse->cookieMask)==0 ) continue; 181 sqlite3VdbeJumpHere(v, 0);
182 for(iDb=0; iDb<db->nDb; iDb++){
183 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
156 sqlite3VdbeUsesBtree(v, iDb); 184 sqlite3VdbeUsesBtree(v, iDb);
157 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); 185 sqlite3VdbeAddOp4Int(v,
158 if( db->init.busy==0 ){ 186 OP_Transaction, /* Opcode */
159 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 187 iDb, /* P1 */
160 sqlite3VdbeAddOp3(v, OP_VerifyCookie, 188 DbMaskTest(pParse->writeMask,iDb), /* P2 */
161 iDb, pParse->cookieValue[iDb], 189 pParse->cookieValue[iDb], /* P3 */
162 db->aDb[iDb].pSchema->iGeneration); 190 db->aDb[iDb].pSchema->iGeneration /* P4 */
163 } 191 );
192 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
164 } 193 }
165 #ifndef SQLITE_OMIT_VIRTUALTABLE 194 #ifndef SQLITE_OMIT_VIRTUALTABLE
166 { 195 for(i=0; i<pParse->nVtabLock; i++){
167 int i; 196 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
168 for(i=0; i<pParse->nVtabLock; i++){ 197 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
169 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
170 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
171 }
172 pParse->nVtabLock = 0;
173 } 198 }
199 pParse->nVtabLock = 0;
174 #endif 200 #endif
175 201
176 /* Once all the cookies have been verified and transactions opened, 202 /* Once all the cookies have been verified and transactions opened,
177 ** obtain the required table-locks. This is a no-op unless the 203 ** obtain the required table-locks. This is a no-op unless the
178 ** shared-cache feature is enabled. 204 ** shared-cache feature is enabled.
179 */ 205 */
180 codeTableLocks(pParse); 206 codeTableLocks(pParse);
181 207
182 /* Initialize any AUTOINCREMENT data structures required. 208 /* Initialize any AUTOINCREMENT data structures required.
183 */ 209 */
184 sqlite3AutoincrementBegin(pParse); 210 sqlite3AutoincrementBegin(pParse);
185 211
212 /* Code constant expressions that where factored out of inner loops */
213 if( pParse->pConstExpr ){
214 ExprList *pEL = pParse->pConstExpr;
215 pParse->okConstFactor = 0;
216 for(i=0; i<pEL->nExpr; i++){
217 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
218 }
219 }
220
186 /* Finally, jump back to the beginning of the executable code. */ 221 /* Finally, jump back to the beginning of the executable code. */
187 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); 222 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
188 } 223 }
189 } 224 }
190 225
191 226
192 /* Get the VDBE program ready for execution 227 /* Get the VDBE program ready for execution
193 */ 228 */
194 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){ 229 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
195 #ifdef SQLITE_DEBUG
196 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
197 sqlite3VdbeTrace(v, trace);
198 #endif
199 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ 230 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
200 /* A minimum of one cursor is required if autoincrement is used 231 /* A minimum of one cursor is required if autoincrement is used
201 * See ticket [a696379c1f08866] */ 232 * See ticket [a696379c1f08866] */
202 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; 233 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
203 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem, 234 sqlite3VdbeMakeReady(v, pParse);
204 pParse->nTab, pParse->nMaxArg, pParse->explain,
205 pParse->isMultiWrite && pParse->mayAbort);
206 pParse->rc = SQLITE_DONE; 235 pParse->rc = SQLITE_DONE;
207 pParse->colNamesSet = 0; 236 pParse->colNamesSet = 0;
208 }else{ 237 }else{
209 pParse->rc = SQLITE_ERROR; 238 pParse->rc = SQLITE_ERROR;
210 } 239 }
211 pParse->nTab = 0; 240 pParse->nTab = 0;
212 pParse->nMem = 0; 241 pParse->nMem = 0;
213 pParse->nSet = 0; 242 pParse->nSet = 0;
214 pParse->nVar = 0; 243 pParse->nVar = 0;
215 pParse->cookieMask = 0; 244 DbMaskZero(pParse->cookieMask);
216 pParse->cookieGoto = 0;
217 } 245 }
218 246
219 /* 247 /*
220 ** Run the parser and code generator recursively in order to generate 248 ** Run the parser and code generator recursively in order to generate
221 ** code for the SQL statement given onto the end of the pParse context 249 ** code for the SQL statement given onto the end of the pParse context
222 ** currently under construction. When the parser is run recursively 250 ** currently under construction. When the parser is run recursively
223 ** this way, the final OP_Halt is not appended and other initialization 251 ** this way, the final OP_Halt is not appended and other initialization
224 ** and finalization steps are omitted because those are handling by the 252 ** and finalization steps are omitted because those are handling by the
225 ** outermost parser. 253 ** outermost parser.
226 ** 254 **
(...skipping 20 matching lines...) Expand all
247 pParse->nested++; 275 pParse->nested++;
248 memcpy(saveBuf, &pParse->nVar, SAVE_SZ); 276 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
249 memset(&pParse->nVar, 0, SAVE_SZ); 277 memset(&pParse->nVar, 0, SAVE_SZ);
250 sqlite3RunParser(pParse, zSql, &zErrMsg); 278 sqlite3RunParser(pParse, zSql, &zErrMsg);
251 sqlite3DbFree(db, zErrMsg); 279 sqlite3DbFree(db, zErrMsg);
252 sqlite3DbFree(db, zSql); 280 sqlite3DbFree(db, zSql);
253 memcpy(&pParse->nVar, saveBuf, SAVE_SZ); 281 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
254 pParse->nested--; 282 pParse->nested--;
255 } 283 }
256 284
285 #if SQLITE_USER_AUTHENTICATION
286 /*
287 ** Return TRUE if zTable is the name of the system table that stores the
288 ** list of users and their access credentials.
289 */
290 int sqlite3UserAuthTable(const char *zTable){
291 return sqlite3_stricmp(zTable, "sqlite_user")==0;
292 }
293 #endif
294
257 /* 295 /*
258 ** Locate the in-memory structure that describes a particular database 296 ** Locate the in-memory structure that describes a particular database
259 ** table given the name of that table and (optionally) the name of the 297 ** table given the name of that table and (optionally) the name of the
260 ** database containing the table. Return NULL if not found. 298 ** database containing the table. Return NULL if not found.
261 ** 299 **
262 ** If zDatabase is 0, all databases are searched for the table and the 300 ** If zDatabase is 0, all databases are searched for the table and the
263 ** first matching table is returned. (No checking for duplicate table 301 ** first matching table is returned. (No checking for duplicate table
264 ** names is done.) The search order is TEMP first, then MAIN, then any 302 ** names is done.) The search order is TEMP first, then MAIN, then any
265 ** auxiliary databases added using the ATTACH command. 303 ** auxiliary databases added using the ATTACH command.
266 ** 304 **
267 ** See also sqlite3LocateTable(). 305 ** See also sqlite3LocateTable().
268 */ 306 */
269 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 307 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
270 Table *p = 0; 308 Table *p = 0;
271 int i; 309 int i;
272 int nName;
273 assert( zName!=0 ); 310 assert( zName!=0 );
274 nName = sqlite3Strlen30(zName);
275 /* All mutexes are required for schema access. Make sure we hold them. */ 311 /* All mutexes are required for schema access. Make sure we hold them. */
276 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 312 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
313 #if SQLITE_USER_AUTHENTICATION
314 /* Only the admin user is allowed to know that the sqlite_user table
315 ** exists */
316 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
317 return 0;
318 }
319 #endif
277 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 320 for(i=OMIT_TEMPDB; i<db->nDb; i++){
278 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 321 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
279 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; 322 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
280 assert( sqlite3SchemaMutexHeld(db, j, 0) ); 323 assert( sqlite3SchemaMutexHeld(db, j, 0) );
281 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName); 324 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
282 if( p ) break; 325 if( p ) break;
283 } 326 }
284 return p; 327 return p;
285 } 328 }
286 329
287 /* 330 /*
288 ** Locate the in-memory structure that describes a particular database 331 ** Locate the in-memory structure that describes a particular database
289 ** table given the name of that table and (optionally) the name of the 332 ** table given the name of that table and (optionally) the name of the
290 ** database containing the table. Return NULL if not found. Also leave an 333 ** database containing the table. Return NULL if not found. Also leave an
291 ** error message in pParse->zErrMsg. 334 ** error message in pParse->zErrMsg.
(...skipping 19 matching lines...) Expand all
311 p = sqlite3FindTable(pParse->db, zName, zDbase); 354 p = sqlite3FindTable(pParse->db, zName, zDbase);
312 if( p==0 ){ 355 if( p==0 ){
313 const char *zMsg = isView ? "no such view" : "no such table"; 356 const char *zMsg = isView ? "no such view" : "no such table";
314 if( zDbase ){ 357 if( zDbase ){
315 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 358 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
316 }else{ 359 }else{
317 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 360 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
318 } 361 }
319 pParse->checkSchema = 1; 362 pParse->checkSchema = 1;
320 } 363 }
364 #if SQLITE_USER_AUTHENICATION
365 else if( pParse->db->auth.authLevel<UAUTH_User ){
366 sqlite3ErrorMsg(pParse, "user not authenticated");
367 p = 0;
368 }
369 #endif
321 return p; 370 return p;
322 } 371 }
323 372
324 /* 373 /*
374 ** Locate the table identified by *p.
375 **
376 ** This is a wrapper around sqlite3LocateTable(). The difference between
377 ** sqlite3LocateTable() and this function is that this function restricts
378 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
379 ** non-NULL if it is part of a view or trigger program definition. See
380 ** sqlite3FixSrcList() for details.
381 */
382 Table *sqlite3LocateTableItem(
383 Parse *pParse,
384 int isView,
385 struct SrcList_item *p
386 ){
387 const char *zDb;
388 assert( p->pSchema==0 || p->zDatabase==0 );
389 if( p->pSchema ){
390 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
391 zDb = pParse->db->aDb[iDb].zName;
392 }else{
393 zDb = p->zDatabase;
394 }
395 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
396 }
397
398 /*
325 ** Locate the in-memory structure that describes 399 ** Locate the in-memory structure that describes
326 ** a particular index given the name of that index 400 ** a particular index given the name of that index
327 ** and the name of the database that contains the index. 401 ** and the name of the database that contains the index.
328 ** Return NULL if not found. 402 ** Return NULL if not found.
329 ** 403 **
330 ** If zDatabase is 0, all databases are searched for the 404 ** If zDatabase is 0, all databases are searched for the
331 ** table and the first matching index is returned. (No checking 405 ** table and the first matching index is returned. (No checking
332 ** for duplicate index names is done.) The search order is 406 ** for duplicate index names is done.) The search order is
333 ** TEMP first, then MAIN, then any auxiliary databases added 407 ** TEMP first, then MAIN, then any auxiliary databases added
334 ** using the ATTACH command. 408 ** using the ATTACH command.
335 */ 409 */
336 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 410 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
337 Index *p = 0; 411 Index *p = 0;
338 int i; 412 int i;
339 int nName = sqlite3Strlen30(zName);
340 /* All mutexes are required for schema access. Make sure we hold them. */ 413 /* All mutexes are required for schema access. Make sure we hold them. */
341 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); 414 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
342 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 415 for(i=OMIT_TEMPDB; i<db->nDb; i++){
343 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 416 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
344 Schema *pSchema = db->aDb[j].pSchema; 417 Schema *pSchema = db->aDb[j].pSchema;
345 assert( pSchema ); 418 assert( pSchema );
346 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; 419 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
347 assert( sqlite3SchemaMutexHeld(db, j, 0) ); 420 assert( sqlite3SchemaMutexHeld(db, j, 0) );
348 p = sqlite3HashFind(&pSchema->idxHash, zName, nName); 421 p = sqlite3HashFind(&pSchema->idxHash, zName);
349 if( p ) break; 422 if( p ) break;
350 } 423 }
351 return p; 424 return p;
352 } 425 }
353 426
354 /* 427 /*
355 ** Reclaim the memory used by an index 428 ** Reclaim the memory used by an index
356 */ 429 */
357 static void freeIndex(sqlite3 *db, Index *p){ 430 static void freeIndex(sqlite3 *db, Index *p){
358 #ifndef SQLITE_OMIT_ANALYZE 431 #ifndef SQLITE_OMIT_ANALYZE
359 sqlite3DeleteIndexSamples(db, p); 432 sqlite3DeleteIndexSamples(db, p);
360 #endif 433 #endif
434 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
435 sqlite3ExprDelete(db, p->pPartIdxWhere);
361 sqlite3DbFree(db, p->zColAff); 436 sqlite3DbFree(db, p->zColAff);
437 if( p->isResized ) sqlite3DbFree(db, p->azColl);
438 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
439 sqlite3_free(p->aiRowEst);
440 #endif
362 sqlite3DbFree(db, p); 441 sqlite3DbFree(db, p);
363 } 442 }
364 443
365 /* 444 /*
366 ** For the index called zIdxName which is found in the database iDb, 445 ** For the index called zIdxName which is found in the database iDb,
367 ** unlike that index from its Table then remove the index from 446 ** unlike that index from its Table then remove the index from
368 ** the index hash table and free all memory structures associated 447 ** the index hash table and free all memory structures associated
369 ** with the index. 448 ** with the index.
370 */ 449 */
371 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 450 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
372 Index *pIndex; 451 Index *pIndex;
373 int len;
374 Hash *pHash; 452 Hash *pHash;
375 453
376 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 454 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
377 pHash = &db->aDb[iDb].pSchema->idxHash; 455 pHash = &db->aDb[iDb].pSchema->idxHash;
378 len = sqlite3Strlen30(zIdxName); 456 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
379 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
380 if( ALWAYS(pIndex) ){ 457 if( ALWAYS(pIndex) ){
381 if( pIndex->pTable->pIndex==pIndex ){ 458 if( pIndex->pTable->pIndex==pIndex ){
382 pIndex->pTable->pIndex = pIndex->pNext; 459 pIndex->pTable->pIndex = pIndex->pNext;
383 }else{ 460 }else{
384 Index *p; 461 Index *p;
385 /* Justification of ALWAYS(); The index must be on the list of 462 /* Justification of ALWAYS(); The index must be on the list of
386 ** indices. */ 463 ** indices. */
387 p = pIndex->pTable->pIndex; 464 p = pIndex->pTable->pIndex;
388 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } 465 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
389 if( ALWAYS(p && p->pNext==pIndex) ){ 466 if( ALWAYS(p && p->pNext==pIndex) ){
390 p->pNext = pIndex->pNext; 467 p->pNext = pIndex->pNext;
391 } 468 }
392 } 469 }
393 freeIndex(db, pIndex); 470 freeIndex(db, pIndex);
394 } 471 }
395 db->flags |= SQLITE_InternChanges; 472 db->flags |= SQLITE_InternChanges;
396 } 473 }
397 474
398 /* 475 /*
399 ** Erase all schema information from the in-memory hash tables of 476 ** Look through the list of open database files in db->aDb[] and if
400 ** a single database. This routine is called to reclaim memory 477 ** any have been closed, remove them from the list. Reallocate the
401 ** before the database closes. It is also called during a rollback 478 ** db->aDb[] structure to a smaller size, if possible.
402 ** if there were schema changes during the transaction or if a
403 ** schema-cookie mismatch occurs.
404 ** 479 **
405 ** If iDb<0 then reset the internal schema tables for all database 480 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
406 ** files. If iDb>=0 then reset the internal schema for only the 481 ** are never candidates for being collapsed.
407 ** single file indicated.
408 */ 482 */
409 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ 483 void sqlite3CollapseDatabaseArray(sqlite3 *db){
410 int i, j; 484 int i, j;
411 assert( iDb<db->nDb );
412
413 if( iDb>=0 ){
414 /* Case 1: Reset the single schema identified by iDb */
415 Db *pDb = &db->aDb[iDb];
416 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
417 assert( pDb->pSchema!=0 );
418 sqlite3SchemaClear(pDb->pSchema);
419
420 /* If any database other than TEMP is reset, then also reset TEMP
421 ** since TEMP might be holding triggers that reference tables in the
422 ** other database.
423 */
424 if( iDb!=1 ){
425 pDb = &db->aDb[1];
426 assert( pDb->pSchema!=0 );
427 sqlite3SchemaClear(pDb->pSchema);
428 }
429 return;
430 }
431 /* Case 2 (from here to the end): Reset all schemas for all attached
432 ** databases. */
433 assert( iDb<0 );
434 sqlite3BtreeEnterAll(db);
435 for(i=0; i<db->nDb; i++){
436 Db *pDb = &db->aDb[i];
437 if( pDb->pSchema ){
438 sqlite3SchemaClear(pDb->pSchema);
439 }
440 }
441 db->flags &= ~SQLITE_InternChanges;
442 sqlite3VtabUnlockList(db);
443 sqlite3BtreeLeaveAll(db);
444
445 /* If one or more of the auxiliary database files has been closed,
446 ** then remove them from the auxiliary database list. We take the
447 ** opportunity to do this here since we have just deleted all of the
448 ** schema hash tables and therefore do not have to make any changes
449 ** to any of those tables.
450 */
451 for(i=j=2; i<db->nDb; i++){ 485 for(i=j=2; i<db->nDb; i++){
452 struct Db *pDb = &db->aDb[i]; 486 struct Db *pDb = &db->aDb[i];
453 if( pDb->pBt==0 ){ 487 if( pDb->pBt==0 ){
454 sqlite3DbFree(db, pDb->zName); 488 sqlite3DbFree(db, pDb->zName);
455 pDb->zName = 0; 489 pDb->zName = 0;
456 continue; 490 continue;
457 } 491 }
458 if( j<i ){ 492 if( j<i ){
459 db->aDb[j] = db->aDb[i]; 493 db->aDb[j] = db->aDb[i];
460 } 494 }
461 j++; 495 j++;
462 } 496 }
463 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); 497 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
464 db->nDb = j; 498 db->nDb = j;
465 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 499 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
466 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 500 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
467 sqlite3DbFree(db, db->aDb); 501 sqlite3DbFree(db, db->aDb);
468 db->aDb = db->aDbStatic; 502 db->aDb = db->aDbStatic;
469 } 503 }
470 } 504 }
471 505
472 /* 506 /*
507 ** Reset the schema for the database at index iDb. Also reset the
508 ** TEMP schema.
509 */
510 void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
511 Db *pDb;
512 assert( iDb<db->nDb );
513
514 /* Case 1: Reset the single schema identified by iDb */
515 pDb = &db->aDb[iDb];
516 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
517 assert( pDb->pSchema!=0 );
518 sqlite3SchemaClear(pDb->pSchema);
519
520 /* If any database other than TEMP is reset, then also reset TEMP
521 ** since TEMP might be holding triggers that reference tables in the
522 ** other database.
523 */
524 if( iDb!=1 ){
525 pDb = &db->aDb[1];
526 assert( pDb->pSchema!=0 );
527 sqlite3SchemaClear(pDb->pSchema);
528 }
529 return;
530 }
531
532 /*
533 ** Erase all schema information from all attached databases (including
534 ** "main" and "temp") for a single database connection.
535 */
536 void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
537 int i;
538 sqlite3BtreeEnterAll(db);
539 for(i=0; i<db->nDb; i++){
540 Db *pDb = &db->aDb[i];
541 if( pDb->pSchema ){
542 sqlite3SchemaClear(pDb->pSchema);
543 }
544 }
545 db->flags &= ~SQLITE_InternChanges;
546 sqlite3VtabUnlockList(db);
547 sqlite3BtreeLeaveAll(db);
548 sqlite3CollapseDatabaseArray(db);
549 }
550
551 /*
473 ** This routine is called when a commit occurs. 552 ** This routine is called when a commit occurs.
474 */ 553 */
475 void sqlite3CommitInternalChanges(sqlite3 *db){ 554 void sqlite3CommitInternalChanges(sqlite3 *db){
476 db->flags &= ~SQLITE_InternChanges; 555 db->flags &= ~SQLITE_InternChanges;
477 } 556 }
478 557
479 /* 558 /*
480 ** Delete memory allocated for the column names of a table or view (the 559 ** Delete memory allocated for the column names of a table or view (the
481 ** Table.aCol[] array). 560 ** Table.aCol[] array).
482 */ 561 */
(...skipping 14 matching lines...) Expand all
497 } 576 }
498 577
499 /* 578 /*
500 ** Remove the memory data structures associated with the given 579 ** Remove the memory data structures associated with the given
501 ** Table. No changes are made to disk by this routine. 580 ** Table. No changes are made to disk by this routine.
502 ** 581 **
503 ** This routine just deletes the data structure. It does not unlink 582 ** This routine just deletes the data structure. It does not unlink
504 ** the table data structure from the hash table. But it does destroy 583 ** the table data structure from the hash table. But it does destroy
505 ** memory structures of the indices and foreign keys associated with 584 ** memory structures of the indices and foreign keys associated with
506 ** the table. 585 ** the table.
586 **
587 ** The db parameter is optional. It is needed if the Table object
588 ** contains lookaside memory. (Table objects in the schema do not use
589 ** lookaside memory, but some ephemeral Table objects do.) Or the
590 ** db parameter can be used with db->pnBytesFreed to measure the memory
591 ** used by the Table object.
507 */ 592 */
508 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ 593 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
509 Index *pIndex, *pNext; 594 Index *pIndex, *pNext;
595 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
510 596
511 assert( !pTable || pTable->nRef>0 ); 597 assert( !pTable || pTable->nRef>0 );
512 598
513 /* Do not delete the table until the reference count reaches zero. */ 599 /* Do not delete the table until the reference count reaches zero. */
514 if( !pTable ) return; 600 if( !pTable ) return;
515 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; 601 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
516 602
603 /* Record the number of outstanding lookaside allocations in schema Tables
604 ** prior to doing any free() operations. Since schema Tables do not use
605 ** lookaside, this number should not change. */
606 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
607 db->lookaside.nOut : 0 );
608
517 /* Delete all indices associated with this table. */ 609 /* Delete all indices associated with this table. */
518 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 610 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
519 pNext = pIndex->pNext; 611 pNext = pIndex->pNext;
520 assert( pIndex->pSchema==pTable->pSchema ); 612 assert( pIndex->pSchema==pTable->pSchema );
521 if( !db || db->pnBytesFreed==0 ){ 613 if( !db || db->pnBytesFreed==0 ){
522 char *zName = pIndex->zName; 614 char *zName = pIndex->zName;
523 TESTONLY ( Index *pOld = ) sqlite3HashInsert( 615 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
524 » &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0 616 &pIndex->pSchema->idxHash, zName, 0
525 ); 617 );
526 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 618 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
527 assert( pOld==pIndex || pOld==0 ); 619 assert( pOld==pIndex || pOld==0 );
528 } 620 }
529 freeIndex(db, pIndex); 621 freeIndex(db, pIndex);
530 } 622 }
531 623
532 /* Delete any foreign keys attached to this table. */ 624 /* Delete any foreign keys attached to this table. */
533 sqlite3FkDelete(db, pTable); 625 sqlite3FkDelete(db, pTable);
534 626
535 /* Delete the Table structure itself. 627 /* Delete the Table structure itself.
536 */ 628 */
537 sqliteDeleteColumnNames(db, pTable); 629 sqliteDeleteColumnNames(db, pTable);
538 sqlite3DbFree(db, pTable->zName); 630 sqlite3DbFree(db, pTable->zName);
539 sqlite3DbFree(db, pTable->zColAff); 631 sqlite3DbFree(db, pTable->zColAff);
540 sqlite3SelectDelete(db, pTable->pSelect); 632 sqlite3SelectDelete(db, pTable->pSelect);
541 #ifndef SQLITE_OMIT_CHECK 633 #ifndef SQLITE_OMIT_CHECK
542 sqlite3ExprDelete(db, pTable->pCheck); 634 sqlite3ExprListDelete(db, pTable->pCheck);
543 #endif 635 #endif
544 #ifndef SQLITE_OMIT_VIRTUALTABLE 636 #ifndef SQLITE_OMIT_VIRTUALTABLE
545 sqlite3VtabClear(db, pTable); 637 sqlite3VtabClear(db, pTable);
546 #endif 638 #endif
547 sqlite3DbFree(db, pTable); 639 sqlite3DbFree(db, pTable);
640
641 /* Verify that no lookaside memory was used by schema tables */
642 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
548 } 643 }
549 644
550 /* 645 /*
551 ** Unlink the given table from the hash tables and the delete the 646 ** Unlink the given table from the hash tables and the delete the
552 ** table structure with all its indices and foreign keys. 647 ** table structure with all its indices and foreign keys.
553 */ 648 */
554 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 649 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
555 Table *p; 650 Table *p;
556 Db *pDb; 651 Db *pDb;
557 652
558 assert( db!=0 ); 653 assert( db!=0 );
559 assert( iDb>=0 && iDb<db->nDb ); 654 assert( iDb>=0 && iDb<db->nDb );
560 assert( zTabName ); 655 assert( zTabName );
561 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 656 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
562 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ 657 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
563 pDb = &db->aDb[iDb]; 658 pDb = &db->aDb[iDb];
564 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 659 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
565 sqlite3Strlen30(zTabName),0);
566 sqlite3DeleteTable(db, p); 660 sqlite3DeleteTable(db, p);
567 db->flags |= SQLITE_InternChanges; 661 db->flags |= SQLITE_InternChanges;
568 } 662 }
569 663
570 /* 664 /*
571 ** Given a token, return a string that consists of the text of that 665 ** Given a token, return a string that consists of the text of that
572 ** token. Space to hold the returned string 666 ** token. Space to hold the returned string
573 ** is obtained from sqliteMalloc() and must be freed by the calling 667 ** is obtained from sqliteMalloc() and must be freed by the calling
574 ** function. 668 ** function.
575 ** 669 **
(...skipping 15 matching lines...) Expand all
591 return zName; 685 return zName;
592 } 686 }
593 687
594 /* 688 /*
595 ** Open the sqlite_master table stored in database number iDb for 689 ** Open the sqlite_master table stored in database number iDb for
596 ** writing. The table is opened using cursor 0. 690 ** writing. The table is opened using cursor 0.
597 */ 691 */
598 void sqlite3OpenMasterTable(Parse *p, int iDb){ 692 void sqlite3OpenMasterTable(Parse *p, int iDb){
599 Vdbe *v = sqlite3GetVdbe(p); 693 Vdbe *v = sqlite3GetVdbe(p);
600 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); 694 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
601 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); 695 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
602 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
603 if( p->nTab==0 ){ 696 if( p->nTab==0 ){
604 p->nTab = 1; 697 p->nTab = 1;
605 } 698 }
606 } 699 }
607 700
608 /* 701 /*
609 ** Parameter zName points to a nul-terminated buffer containing the name 702 ** Parameter zName points to a nul-terminated buffer containing the name
610 ** of a database ("main", "temp" or the name of an attached db). This 703 ** of a database ("main", "temp" or the name of an attached db). This
611 ** function returns the index of the named database in db->aDb[], or 704 ** function returns the index of the named database in db->aDb[], or
612 ** -1 if the named db cannot be found. 705 ** -1 if the named db cannot be found.
(...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after
698 if( !pParse->db->init.busy && pParse->nested==0 791 if( !pParse->db->init.busy && pParse->nested==0
699 && (pParse->db->flags & SQLITE_WriteSchema)==0 792 && (pParse->db->flags & SQLITE_WriteSchema)==0
700 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 793 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
701 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 794 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
702 return SQLITE_ERROR; 795 return SQLITE_ERROR;
703 } 796 }
704 return SQLITE_OK; 797 return SQLITE_OK;
705 } 798 }
706 799
707 /* 800 /*
801 ** Return the PRIMARY KEY index of a table
802 */
803 Index *sqlite3PrimaryKeyIndex(Table *pTab){
804 Index *p;
805 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
806 return p;
807 }
808
809 /*
810 ** Return the column of index pIdx that corresponds to table
811 ** column iCol. Return -1 if not found.
812 */
813 i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
814 int i;
815 for(i=0; i<pIdx->nColumn; i++){
816 if( iCol==pIdx->aiColumn[i] ) return i;
817 }
818 return -1;
819 }
820
821 /*
708 ** Begin constructing a new table representation in memory. This is 822 ** Begin constructing a new table representation in memory. This is
709 ** the first of several action routines that get called in response 823 ** the first of several action routines that get called in response
710 ** to a CREATE TABLE statement. In particular, this routine is called 824 ** to a CREATE TABLE statement. In particular, this routine is called
711 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 825 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
712 ** flag is true if the table should be stored in the auxiliary database 826 ** flag is true if the table should be stored in the auxiliary database
713 ** file instead of in the main database file. This is normally the case 827 ** file instead of in the main database file. This is normally the case
714 ** when the "TEMP" or "TEMPORARY" keyword occurs in between 828 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
715 ** CREATE and TABLE. 829 ** CREATE and TABLE.
716 ** 830 **
717 ** The new table record is initialized and put in pParse->pNewTable. 831 ** The new table record is initialized and put in pParse->pNewTable.
(...skipping 111 matching lines...) Expand 10 before | Expand all | Expand 10 after
829 if( pTable==0 ){ 943 if( pTable==0 ){
830 db->mallocFailed = 1; 944 db->mallocFailed = 1;
831 pParse->rc = SQLITE_NOMEM; 945 pParse->rc = SQLITE_NOMEM;
832 pParse->nErr++; 946 pParse->nErr++;
833 goto begin_table_error; 947 goto begin_table_error;
834 } 948 }
835 pTable->zName = zName; 949 pTable->zName = zName;
836 pTable->iPKey = -1; 950 pTable->iPKey = -1;
837 pTable->pSchema = db->aDb[iDb].pSchema; 951 pTable->pSchema = db->aDb[iDb].pSchema;
838 pTable->nRef = 1; 952 pTable->nRef = 1;
839 pTable->nRowEst = 1000000; 953 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
840 assert( pParse->pNewTable==0 ); 954 assert( pParse->pNewTable==0 );
841 pParse->pNewTable = pTable; 955 pParse->pNewTable = pTable;
842 956
843 /* If this is the magic sqlite_sequence table used by autoincrement, 957 /* If this is the magic sqlite_sequence table used by autoincrement,
844 ** then record a pointer to this table in the main database structure 958 ** then record a pointer to this table in the main database structure
845 ** so that INSERT can find the table easily. 959 ** so that INSERT can find the table easily.
846 */ 960 */
847 #ifndef SQLITE_OMIT_AUTOINCREMENT 961 #ifndef SQLITE_OMIT_AUTOINCREMENT
848 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 962 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
849 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 963 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
(...skipping 22 matching lines...) Expand all
872 #endif 986 #endif
873 987
874 /* If the file format and encoding in the database have not been set, 988 /* If the file format and encoding in the database have not been set,
875 ** set them now. 989 ** set them now.
876 */ 990 */
877 reg1 = pParse->regRowid = ++pParse->nMem; 991 reg1 = pParse->regRowid = ++pParse->nMem;
878 reg2 = pParse->regRoot = ++pParse->nMem; 992 reg2 = pParse->regRoot = ++pParse->nMem;
879 reg3 = ++pParse->nMem; 993 reg3 = ++pParse->nMem;
880 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); 994 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
881 sqlite3VdbeUsesBtree(v, iDb); 995 sqlite3VdbeUsesBtree(v, iDb);
882 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); 996 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
883 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 997 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
884 1 : SQLITE_MAX_FILE_FORMAT; 998 1 : SQLITE_MAX_FILE_FORMAT;
885 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); 999 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
886 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3); 1000 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
887 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); 1001 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
888 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3); 1002 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
889 sqlite3VdbeJumpHere(v, j1); 1003 sqlite3VdbeJumpHere(v, j1);
890 1004
891 /* This just creates a place-holder record in the sqlite_master table. 1005 /* This just creates a place-holder record in the sqlite_master table.
892 ** The record created does not contain anything yet. It will be replaced 1006 ** The record created does not contain anything yet. It will be replaced
893 ** by the real entry in code generated at sqlite3EndTable(). 1007 ** by the real entry in code generated at sqlite3EndTable().
894 ** 1008 **
895 ** The rowid for the new entry is left in register pParse->regRowid. 1009 ** The rowid for the new entry is left in register pParse->regRowid.
896 ** The root page number of the new table is left in reg pParse->regRoot. 1010 ** The root page number of the new table is left in reg pParse->regRoot.
897 ** The rowid and root page number values are needed by the code that 1011 ** The rowid and root page number values are needed by the code that
898 ** sqlite3EndTable will generate. 1012 ** sqlite3EndTable will generate.
899 */ 1013 */
900 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 1014 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
901 if( isView || isVirtual ){ 1015 if( isView || isVirtual ){
902 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 1016 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
903 }else 1017 }else
904 #endif 1018 #endif
905 { 1019 {
906 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); 1020 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
907 } 1021 }
908 sqlite3OpenMasterTable(pParse, iDb); 1022 sqlite3OpenMasterTable(pParse, iDb);
909 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 1023 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
910 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); 1024 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
911 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 1025 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
912 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1026 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
913 sqlite3VdbeAddOp0(v, OP_Close); 1027 sqlite3VdbeAddOp0(v, OP_Close);
914 } 1028 }
915 1029
916 /* Normal (non-error) return. */ 1030 /* Normal (non-error) return. */
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
976 } 1090 }
977 pCol = &p->aCol[p->nCol]; 1091 pCol = &p->aCol[p->nCol];
978 memset(pCol, 0, sizeof(p->aCol[0])); 1092 memset(pCol, 0, sizeof(p->aCol[0]));
979 pCol->zName = z; 1093 pCol->zName = z;
980 1094
981 /* If there is no type specified, columns have the default affinity 1095 /* If there is no type specified, columns have the default affinity
982 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will 1096 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
983 ** be called next to set pCol->affinity correctly. 1097 ** be called next to set pCol->affinity correctly.
984 */ 1098 */
985 pCol->affinity = SQLITE_AFF_NONE; 1099 pCol->affinity = SQLITE_AFF_NONE;
1100 pCol->szEst = 1;
986 p->nCol++; 1101 p->nCol++;
987 } 1102 }
988 1103
989 /* 1104 /*
990 ** This routine is called by the parser while in the middle of 1105 ** This routine is called by the parser while in the middle of
991 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 1106 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
992 ** been seen on a column. This routine sets the notNull flag on 1107 ** been seen on a column. This routine sets the notNull flag on
993 ** the column currently under construction. 1108 ** the column currently under construction.
994 */ 1109 */
995 void sqlite3AddNotNull(Parse *pParse, int onError){ 1110 void sqlite3AddNotNull(Parse *pParse, int onError){
(...skipping 21 matching lines...) Expand all
1017 ** 'CLOB' | SQLITE_AFF_TEXT 1132 ** 'CLOB' | SQLITE_AFF_TEXT
1018 ** 'TEXT' | SQLITE_AFF_TEXT 1133 ** 'TEXT' | SQLITE_AFF_TEXT
1019 ** 'BLOB' | SQLITE_AFF_NONE 1134 ** 'BLOB' | SQLITE_AFF_NONE
1020 ** 'REAL' | SQLITE_AFF_REAL 1135 ** 'REAL' | SQLITE_AFF_REAL
1021 ** 'FLOA' | SQLITE_AFF_REAL 1136 ** 'FLOA' | SQLITE_AFF_REAL
1022 ** 'DOUB' | SQLITE_AFF_REAL 1137 ** 'DOUB' | SQLITE_AFF_REAL
1023 ** 1138 **
1024 ** If none of the substrings in the above table are found, 1139 ** If none of the substrings in the above table are found,
1025 ** SQLITE_AFF_NUMERIC is returned. 1140 ** SQLITE_AFF_NUMERIC is returned.
1026 */ 1141 */
1027 char sqlite3AffinityType(const char *zIn){ 1142 char sqlite3AffinityType(const char *zIn, u8 *pszEst){
1028 u32 h = 0; 1143 u32 h = 0;
1029 char aff = SQLITE_AFF_NUMERIC; 1144 char aff = SQLITE_AFF_NUMERIC;
1145 const char *zChar = 0;
1030 1146
1031 if( zIn ) while( zIn[0] ){ 1147 if( zIn==0 ) return aff;
1148 while( zIn[0] ){
1032 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; 1149 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1033 zIn++; 1150 zIn++;
1034 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 1151 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1035 aff = SQLITE_AFF_TEXT; 1152 aff = SQLITE_AFF_TEXT;
1153 zChar = zIn;
1036 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 1154 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1037 aff = SQLITE_AFF_TEXT; 1155 aff = SQLITE_AFF_TEXT;
1038 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 1156 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1039 aff = SQLITE_AFF_TEXT; 1157 aff = SQLITE_AFF_TEXT;
1040 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 1158 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1041 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 1159 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1042 aff = SQLITE_AFF_NONE; 1160 aff = SQLITE_AFF_NONE;
1161 if( zIn[0]=='(' ) zChar = zIn;
1043 #ifndef SQLITE_OMIT_FLOATING_POINT 1162 #ifndef SQLITE_OMIT_FLOATING_POINT
1044 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 1163 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1045 && aff==SQLITE_AFF_NUMERIC ){ 1164 && aff==SQLITE_AFF_NUMERIC ){
1046 aff = SQLITE_AFF_REAL; 1165 aff = SQLITE_AFF_REAL;
1047 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 1166 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1048 && aff==SQLITE_AFF_NUMERIC ){ 1167 && aff==SQLITE_AFF_NUMERIC ){
1049 aff = SQLITE_AFF_REAL; 1168 aff = SQLITE_AFF_REAL;
1050 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 1169 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1051 && aff==SQLITE_AFF_NUMERIC ){ 1170 && aff==SQLITE_AFF_NUMERIC ){
1052 aff = SQLITE_AFF_REAL; 1171 aff = SQLITE_AFF_REAL;
1053 #endif 1172 #endif
1054 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 1173 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1055 aff = SQLITE_AFF_INTEGER; 1174 aff = SQLITE_AFF_INTEGER;
1056 break; 1175 break;
1057 } 1176 }
1058 } 1177 }
1059 1178
1179 /* If pszEst is not NULL, store an estimate of the field size. The
1180 ** estimate is scaled so that the size of an integer is 1. */
1181 if( pszEst ){
1182 *pszEst = 1; /* default size is approx 4 bytes */
1183 if( aff<SQLITE_AFF_NUMERIC ){
1184 if( zChar ){
1185 while( zChar[0] ){
1186 if( sqlite3Isdigit(zChar[0]) ){
1187 int v = 0;
1188 sqlite3GetInt32(zChar, &v);
1189 v = v/4 + 1;
1190 if( v>255 ) v = 255;
1191 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1192 break;
1193 }
1194 zChar++;
1195 }
1196 }else{
1197 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1198 }
1199 }
1200 }
1060 return aff; 1201 return aff;
1061 } 1202 }
1062 1203
1063 /* 1204 /*
1064 ** This routine is called by the parser while in the middle of 1205 ** This routine is called by the parser while in the middle of
1065 ** parsing a CREATE TABLE statement. The pFirst token is the first 1206 ** parsing a CREATE TABLE statement. The pFirst token is the first
1066 ** token in the sequence of tokens that describe the type of the 1207 ** token in the sequence of tokens that describe the type of the
1067 ** column currently under construction. pLast is the last token 1208 ** column currently under construction. pLast is the last token
1068 ** in the sequence. Use this information to construct a string 1209 ** in the sequence. Use this information to construct a string
1069 ** that contains the typename of the column and store that string 1210 ** that contains the typename of the column and store that string
1070 ** in zType. 1211 ** in zType.
1071 */ 1212 */
1072 void sqlite3AddColumnType(Parse *pParse, Token *pType){ 1213 void sqlite3AddColumnType(Parse *pParse, Token *pType){
1073 Table *p; 1214 Table *p;
1074 Column *pCol; 1215 Column *pCol;
1075 1216
1076 p = pParse->pNewTable; 1217 p = pParse->pNewTable;
1077 if( p==0 || NEVER(p->nCol<1) ) return; 1218 if( p==0 || NEVER(p->nCol<1) ) return;
1078 pCol = &p->aCol[p->nCol-1]; 1219 pCol = &p->aCol[p->nCol-1];
1079 assert( pCol->zType==0 ); 1220 assert( pCol->zType==0 );
1080 pCol->zType = sqlite3NameFromToken(pParse->db, pType); 1221 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
1081 pCol->affinity = sqlite3AffinityType(pCol->zType); 1222 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
1082 } 1223 }
1083 1224
1084 /* 1225 /*
1085 ** The expression is the default value for the most recently added column 1226 ** The expression is the default value for the most recently added column
1086 ** of the table currently under construction. 1227 ** of the table currently under construction.
1087 ** 1228 **
1088 ** Default value expressions must be constant. Raise an exception if this 1229 ** Default value expressions must be constant. Raise an exception if this
1089 ** is not the case. 1230 ** is not the case.
1090 ** 1231 **
1091 ** This routine is called by the parser while in the middle of 1232 ** This routine is called by the parser while in the middle of
1092 ** parsing a CREATE TABLE statement. 1233 ** parsing a CREATE TABLE statement.
1093 */ 1234 */
1094 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ 1235 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
1095 Table *p; 1236 Table *p;
1096 Column *pCol; 1237 Column *pCol;
1097 sqlite3 *db = pParse->db; 1238 sqlite3 *db = pParse->db;
1098 p = pParse->pNewTable; 1239 p = pParse->pNewTable;
1099 if( p!=0 ){ 1240 if( p!=0 ){
1100 pCol = &(p->aCol[p->nCol-1]); 1241 pCol = &(p->aCol[p->nCol-1]);
1101 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){ 1242 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
1102 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 1243 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1103 pCol->zName); 1244 pCol->zName);
1104 }else{ 1245 }else{
1105 /* A copy of pExpr is used instead of the original, as pExpr contains 1246 /* A copy of pExpr is used instead of the original, as pExpr contains
1106 ** tokens that point to volatile memory. The 'span' of the expression 1247 ** tokens that point to volatile memory. The 'span' of the expression
1107 ** is required by pragma table_info. 1248 ** is required by pragma table_info.
1108 */ 1249 */
1109 sqlite3ExprDelete(db, pCol->pDflt); 1250 sqlite3ExprDelete(db, pCol->pDflt);
1110 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE); 1251 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1111 sqlite3DbFree(db, pCol->zDflt); 1252 sqlite3DbFree(db, pCol->zDflt);
(...skipping 25 matching lines...) Expand all
1137 void sqlite3AddPrimaryKey( 1278 void sqlite3AddPrimaryKey(
1138 Parse *pParse, /* Parsing context */ 1279 Parse *pParse, /* Parsing context */
1139 ExprList *pList, /* List of field names to be indexed */ 1280 ExprList *pList, /* List of field names to be indexed */
1140 int onError, /* What to do with a uniqueness conflict */ 1281 int onError, /* What to do with a uniqueness conflict */
1141 int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1282 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1142 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1283 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1143 ){ 1284 ){
1144 Table *pTab = pParse->pNewTable; 1285 Table *pTab = pParse->pNewTable;
1145 char *zType = 0; 1286 char *zType = 0;
1146 int iCol = -1, i; 1287 int iCol = -1, i;
1288 int nTerm;
1147 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; 1289 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
1148 if( pTab->tabFlags & TF_HasPrimaryKey ){ 1290 if( pTab->tabFlags & TF_HasPrimaryKey ){
1149 sqlite3ErrorMsg(pParse, 1291 sqlite3ErrorMsg(pParse,
1150 "table \"%s\" has more than one primary key", pTab->zName); 1292 "table \"%s\" has more than one primary key", pTab->zName);
1151 goto primary_key_exit; 1293 goto primary_key_exit;
1152 } 1294 }
1153 pTab->tabFlags |= TF_HasPrimaryKey; 1295 pTab->tabFlags |= TF_HasPrimaryKey;
1154 if( pList==0 ){ 1296 if( pList==0 ){
1155 iCol = pTab->nCol - 1; 1297 iCol = pTab->nCol - 1;
1156 pTab->aCol[iCol].isPrimKey = 1; 1298 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1299 zType = pTab->aCol[iCol].zType;
1300 nTerm = 1;
1157 }else{ 1301 }else{
1158 for(i=0; i<pList->nExpr; i++){ 1302 nTerm = pList->nExpr;
1303 for(i=0; i<nTerm; i++){
1159 for(iCol=0; iCol<pTab->nCol; iCol++){ 1304 for(iCol=0; iCol<pTab->nCol; iCol++){
1160 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ 1305 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1306 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1307 zType = pTab->aCol[iCol].zType;
1161 break; 1308 break;
1162 } 1309 }
1163 } 1310 }
1164 if( iCol<pTab->nCol ){
1165 pTab->aCol[iCol].isPrimKey = 1;
1166 }
1167 } 1311 }
1168 if( pList->nExpr>1 ) iCol = -1;
1169 } 1312 }
1170 if( iCol>=0 && iCol<pTab->nCol ){ 1313 if( nTerm==1
1171 zType = pTab->aCol[iCol].zType; 1314 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1172 } 1315 && sortOrder==SQLITE_SO_ASC
1173 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 1316 ){
1174 && sortOrder==SQLITE_SO_ASC ){
1175 pTab->iPKey = iCol; 1317 pTab->iPKey = iCol;
1176 pTab->keyConf = (u8)onError; 1318 pTab->keyConf = (u8)onError;
1177 assert( autoInc==0 || autoInc==1 ); 1319 assert( autoInc==0 || autoInc==1 );
1178 pTab->tabFlags |= autoInc*TF_Autoincrement; 1320 pTab->tabFlags |= autoInc*TF_Autoincrement;
1321 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
1179 }else if( autoInc ){ 1322 }else if( autoInc ){
1180 #ifndef SQLITE_OMIT_AUTOINCREMENT 1323 #ifndef SQLITE_OMIT_AUTOINCREMENT
1181 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1324 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1182 "INTEGER PRIMARY KEY"); 1325 "INTEGER PRIMARY KEY");
1183 #endif 1326 #endif
1184 }else{ 1327 }else{
1328 Vdbe *v = pParse->pVdbe;
1185 Index *p; 1329 Index *p;
1186 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); 1330 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
1331 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1332 0, sortOrder, 0);
1187 if( p ){ 1333 if( p ){
1188 p->autoIndex = 2; 1334 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
1335 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
1189 } 1336 }
1190 pList = 0; 1337 pList = 0;
1191 } 1338 }
1192 1339
1193 primary_key_exit: 1340 primary_key_exit:
1194 sqlite3ExprListDelete(pParse->db, pList); 1341 sqlite3ExprListDelete(pParse->db, pList);
1195 return; 1342 return;
1196 } 1343 }
1197 1344
1198 /* 1345 /*
1199 ** Add a new CHECK constraint to the table currently under construction. 1346 ** Add a new CHECK constraint to the table currently under construction.
1200 */ 1347 */
1201 void sqlite3AddCheckConstraint( 1348 void sqlite3AddCheckConstraint(
1202 Parse *pParse, /* Parsing context */ 1349 Parse *pParse, /* Parsing context */
1203 Expr *pCheckExpr /* The check expression */ 1350 Expr *pCheckExpr /* The check expression */
1204 ){ 1351 ){
1205 sqlite3 *db = pParse->db;
1206 #ifndef SQLITE_OMIT_CHECK 1352 #ifndef SQLITE_OMIT_CHECK
1207 Table *pTab = pParse->pNewTable; 1353 Table *pTab = pParse->pNewTable;
1208 if( pTab && !IN_DECLARE_VTAB ){ 1354 sqlite3 *db = pParse->db;
1209 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr); 1355 if( pTab && !IN_DECLARE_VTAB
1356 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1357 ){
1358 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1359 if( pParse->constraintName.n ){
1360 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1361 }
1210 }else 1362 }else
1211 #endif 1363 #endif
1212 { 1364 {
1213 sqlite3ExprDelete(db, pCheckExpr); 1365 sqlite3ExprDelete(pParse->db, pCheckExpr);
1214 } 1366 }
1215 } 1367 }
1216 1368
1217 /* 1369 /*
1218 ** Set the collation function of the most recently parsed table column 1370 ** Set the collation function of the most recently parsed table column
1219 ** to the CollSeq given. 1371 ** to the CollSeq given.
1220 */ 1372 */
1221 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 1373 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1222 Table *p; 1374 Table *p;
1223 int i; 1375 int i;
1224 char *zColl; /* Dequoted name of collation sequence */ 1376 char *zColl; /* Dequoted name of collation sequence */
1225 sqlite3 *db; 1377 sqlite3 *db;
1226 1378
1227 if( (p = pParse->pNewTable)==0 ) return; 1379 if( (p = pParse->pNewTable)==0 ) return;
1228 i = p->nCol-1; 1380 i = p->nCol-1;
1229 db = pParse->db; 1381 db = pParse->db;
1230 zColl = sqlite3NameFromToken(db, pToken); 1382 zColl = sqlite3NameFromToken(db, pToken);
1231 if( !zColl ) return; 1383 if( !zColl ) return;
1232 1384
1233 if( sqlite3LocateCollSeq(pParse, zColl) ){ 1385 if( sqlite3LocateCollSeq(pParse, zColl) ){
1234 Index *pIdx; 1386 Index *pIdx;
1387 sqlite3DbFree(db, p->aCol[i].zColl);
1235 p->aCol[i].zColl = zColl; 1388 p->aCol[i].zColl = zColl;
1236 1389
1237 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 1390 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1238 ** then an index may have been created on this column before the 1391 ** then an index may have been created on this column before the
1239 ** collation type was added. Correct this if it is the case. 1392 ** collation type was added. Correct this if it is the case.
1240 */ 1393 */
1241 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1394 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1242 assert( pIdx->nColumn==1 ); 1395 assert( pIdx->nKeyCol==1 );
1243 if( pIdx->aiColumn[0]==i ){ 1396 if( pIdx->aiColumn[0]==i ){
1244 pIdx->azColl[0] = p->aCol[i].zColl; 1397 pIdx->azColl[0] = p->aCol[i].zColl;
1245 } 1398 }
1246 } 1399 }
1247 }else{ 1400 }else{
1248 sqlite3DbFree(db, zColl); 1401 sqlite3DbFree(db, zColl);
1249 } 1402 }
1250 } 1403 }
1251 1404
1252 /* 1405 /*
(...skipping 17 matching lines...) Expand all
1270 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() 1423 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1271 */ 1424 */
1272 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ 1425 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
1273 sqlite3 *db = pParse->db; 1426 sqlite3 *db = pParse->db;
1274 u8 enc = ENC(db); 1427 u8 enc = ENC(db);
1275 u8 initbusy = db->init.busy; 1428 u8 initbusy = db->init.busy;
1276 CollSeq *pColl; 1429 CollSeq *pColl;
1277 1430
1278 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); 1431 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
1279 if( !initbusy && (!pColl || !pColl->xCmp) ){ 1432 if( !initbusy && (!pColl || !pColl->xCmp) ){
1280 pColl = sqlite3GetCollSeq(db, enc, pColl, zName); 1433 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
1281 if( !pColl ){
1282 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
1283 }
1284 } 1434 }
1285 1435
1286 return pColl; 1436 return pColl;
1287 } 1437 }
1288 1438
1289 1439
1290 /* 1440 /*
1291 ** Generate code that will increment the schema cookie. 1441 ** Generate code that will increment the schema cookie.
1292 ** 1442 **
1293 ** The schema cookie is used to determine when the schema for the 1443 ** The schema cookie is used to determine when the schema for the
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
1343 ** it is quoted using double-quotes. 1493 ** it is quoted using double-quotes.
1344 */ 1494 */
1345 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 1495 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1346 unsigned char *zIdent = (unsigned char*)zSignedIdent; 1496 unsigned char *zIdent = (unsigned char*)zSignedIdent;
1347 int i, j, needQuote; 1497 int i, j, needQuote;
1348 i = *pIdx; 1498 i = *pIdx;
1349 1499
1350 for(j=0; zIdent[j]; j++){ 1500 for(j=0; zIdent[j]; j++){
1351 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 1501 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1352 } 1502 }
1353 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID; 1503 needQuote = sqlite3Isdigit(zIdent[0])
1354 if( !needQuote ){ 1504 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1355 needQuote = zIdent[j]; 1505 || zIdent[j]!=0
1356 } 1506 || j==0;
1357 1507
1358 if( needQuote ) z[i++] = '"'; 1508 if( needQuote ) z[i++] = '"';
1359 for(j=0; zIdent[j]; j++){ 1509 for(j=0; zIdent[j]; j++){
1360 z[i++] = zIdent[j]; 1510 z[i++] = zIdent[j];
1361 if( zIdent[j]=='"' ) z[i++] = '"'; 1511 if( zIdent[j]=='"' ) z[i++] = '"';
1362 } 1512 }
1363 if( needQuote ) z[i++] = '"'; 1513 if( needQuote ) z[i++] = '"';
1364 z[i] = 0; 1514 z[i] = 0;
1365 *pIdx = i; 1515 *pIdx = i;
1366 } 1516 }
(...skipping 27 matching lines...) Expand all
1394 if( zStmt==0 ){ 1544 if( zStmt==0 ){
1395 db->mallocFailed = 1; 1545 db->mallocFailed = 1;
1396 return 0; 1546 return 0;
1397 } 1547 }
1398 sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 1548 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1399 k = sqlite3Strlen30(zStmt); 1549 k = sqlite3Strlen30(zStmt);
1400 identPut(zStmt, &k, p->zName); 1550 identPut(zStmt, &k, p->zName);
1401 zStmt[k++] = '('; 1551 zStmt[k++] = '(';
1402 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1552 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1403 static const char * const azType[] = { 1553 static const char * const azType[] = {
1554 /* SQLITE_AFF_NONE */ "",
1404 /* SQLITE_AFF_TEXT */ " TEXT", 1555 /* SQLITE_AFF_TEXT */ " TEXT",
1405 /* SQLITE_AFF_NONE */ "",
1406 /* SQLITE_AFF_NUMERIC */ " NUM", 1556 /* SQLITE_AFF_NUMERIC */ " NUM",
1407 /* SQLITE_AFF_INTEGER */ " INT", 1557 /* SQLITE_AFF_INTEGER */ " INT",
1408 /* SQLITE_AFF_REAL */ " REAL" 1558 /* SQLITE_AFF_REAL */ " REAL"
1409 }; 1559 };
1410 int len; 1560 int len;
1411 const char *zType; 1561 const char *zType;
1412 1562
1413 sqlite3_snprintf(n-k, &zStmt[k], zSep); 1563 sqlite3_snprintf(n-k, &zStmt[k], zSep);
1414 k += sqlite3Strlen30(&zStmt[k]); 1564 k += sqlite3Strlen30(&zStmt[k]);
1415 zSep = zSep2; 1565 zSep = zSep2;
1416 identPut(zStmt, &k, pCol->zName); 1566 identPut(zStmt, &k, pCol->zName);
1417 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 ); 1567 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
1418 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) ); 1568 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
1569 testcase( pCol->affinity==SQLITE_AFF_NONE );
1419 testcase( pCol->affinity==SQLITE_AFF_TEXT ); 1570 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1420 testcase( pCol->affinity==SQLITE_AFF_NONE );
1421 testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 1571 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1422 testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 1572 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1423 testcase( pCol->affinity==SQLITE_AFF_REAL ); 1573 testcase( pCol->affinity==SQLITE_AFF_REAL );
1424 1574
1425 zType = azType[pCol->affinity - SQLITE_AFF_TEXT]; 1575 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
1426 len = sqlite3Strlen30(zType); 1576 len = sqlite3Strlen30(zType);
1427 assert( pCol->affinity==SQLITE_AFF_NONE 1577 assert( pCol->affinity==SQLITE_AFF_NONE
1428 || pCol->affinity==sqlite3AffinityType(zType) ); 1578 || pCol->affinity==sqlite3AffinityType(zType, 0) );
1429 memcpy(&zStmt[k], zType, len); 1579 memcpy(&zStmt[k], zType, len);
1430 k += len; 1580 k += len;
1431 assert( k<=n ); 1581 assert( k<=n );
1432 } 1582 }
1433 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 1583 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1434 return zStmt; 1584 return zStmt;
1435 } 1585 }
1436 1586
1437 /* 1587 /*
1588 ** Resize an Index object to hold N columns total. Return SQLITE_OK
1589 ** on success and SQLITE_NOMEM on an OOM error.
1590 */
1591 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1592 char *zExtra;
1593 int nByte;
1594 if( pIdx->nColumn>=N ) return SQLITE_OK;
1595 assert( pIdx->isResized==0 );
1596 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1597 zExtra = sqlite3DbMallocZero(db, nByte);
1598 if( zExtra==0 ) return SQLITE_NOMEM;
1599 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1600 pIdx->azColl = (char**)zExtra;
1601 zExtra += sizeof(char*)*N;
1602 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1603 pIdx->aiColumn = (i16*)zExtra;
1604 zExtra += sizeof(i16)*N;
1605 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1606 pIdx->aSortOrder = (u8*)zExtra;
1607 pIdx->nColumn = N;
1608 pIdx->isResized = 1;
1609 return SQLITE_OK;
1610 }
1611
1612 /*
1613 ** Estimate the total row width for a table.
1614 */
1615 static void estimateTableWidth(Table *pTab){
1616 unsigned wTable = 0;
1617 const Column *pTabCol;
1618 int i;
1619 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1620 wTable += pTabCol->szEst;
1621 }
1622 if( pTab->iPKey<0 ) wTable++;
1623 pTab->szTabRow = sqlite3LogEst(wTable*4);
1624 }
1625
1626 /*
1627 ** Estimate the average size of a row for an index.
1628 */
1629 static void estimateIndexWidth(Index *pIdx){
1630 unsigned wIndex = 0;
1631 int i;
1632 const Column *aCol = pIdx->pTable->aCol;
1633 for(i=0; i<pIdx->nColumn; i++){
1634 i16 x = pIdx->aiColumn[i];
1635 assert( x<pIdx->pTable->nCol );
1636 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
1637 }
1638 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
1639 }
1640
1641 /* Return true if value x is found any of the first nCol entries of aiCol[]
1642 */
1643 static int hasColumn(const i16 *aiCol, int nCol, int x){
1644 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1645 return 0;
1646 }
1647
1648 /*
1649 ** This routine runs at the end of parsing a CREATE TABLE statement that
1650 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
1651 ** internal schema data structures and the generated VDBE code so that they
1652 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1653 ** Changes include:
1654 **
1655 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1656 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1657 ** data storage is a covering index btree.
1658 ** (2) Bypass the creation of the sqlite_master table entry
1659 ** for the PRIMARY KEY as the primary key index is now
1660 ** identified by the sqlite_master table entry of the table itself.
1661 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1662 ** schema to the rootpage from the main table.
1663 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1664 ** (5) Add all table columns to the PRIMARY KEY Index object
1665 ** so that the PRIMARY KEY is a covering index. The surplus
1666 ** columns are part of KeyInfo.nXField and are not used for
1667 ** sorting or lookup or uniqueness checks.
1668 ** (6) Replace the rowid tail on all automatically generated UNIQUE
1669 ** indices with the PRIMARY KEY columns.
1670 */
1671 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1672 Index *pIdx;
1673 Index *pPk;
1674 int nPk;
1675 int i, j;
1676 sqlite3 *db = pParse->db;
1677 Vdbe *v = pParse->pVdbe;
1678
1679 /* Convert the OP_CreateTable opcode that would normally create the
1680 ** root-page for the table into an OP_CreateIndex opcode. The index
1681 ** created will become the PRIMARY KEY index.
1682 */
1683 if( pParse->addrCrTab ){
1684 assert( v );
1685 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1686 }
1687
1688 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1689 ** table entry.
1690 */
1691 if( pParse->addrSkipPK ){
1692 assert( v );
1693 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
1694 }
1695
1696 /* Locate the PRIMARY KEY index. Or, if this table was originally
1697 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1698 */
1699 if( pTab->iPKey>=0 ){
1700 ExprList *pList;
1701 pList = sqlite3ExprListAppend(pParse, 0, 0);
1702 if( pList==0 ) return;
1703 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1704 pTab->aCol[pTab->iPKey].zName);
1705 pList->a[0].sortOrder = pParse->iPkSortOrder;
1706 assert( pParse->pNewTable==pTab );
1707 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1708 if( pPk==0 ) return;
1709 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
1710 pTab->iPKey = -1;
1711 }else{
1712 pPk = sqlite3PrimaryKeyIndex(pTab);
1713 }
1714 pPk->isCovering = 1;
1715 assert( pPk!=0 );
1716 nPk = pPk->nKeyCol;
1717
1718 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1719 for(i=0; i<nPk; i++){
1720 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1721 }
1722 pPk->uniqNotNull = 1;
1723
1724 /* The root page of the PRIMARY KEY is the table root page */
1725 pPk->tnum = pTab->tnum;
1726
1727 /* Update the in-memory representation of all UNIQUE indices by converting
1728 ** the final rowid column into one or more columns of the PRIMARY KEY.
1729 */
1730 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1731 int n;
1732 if( IsPrimaryKeyIndex(pIdx) ) continue;
1733 for(i=n=0; i<nPk; i++){
1734 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1735 }
1736 if( n==0 ){
1737 /* This index is a superset of the primary key */
1738 pIdx->nColumn = pIdx->nKeyCol;
1739 continue;
1740 }
1741 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1742 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
1743 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
1744 pIdx->aiColumn[j] = pPk->aiColumn[i];
1745 pIdx->azColl[j] = pPk->azColl[i];
1746 j++;
1747 }
1748 }
1749 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1750 assert( pIdx->nColumn>=j );
1751 }
1752
1753 /* Add all table columns to the PRIMARY KEY index
1754 */
1755 if( nPk<pTab->nCol ){
1756 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1757 for(i=0, j=nPk; i<pTab->nCol; i++){
1758 if( !hasColumn(pPk->aiColumn, j, i) ){
1759 assert( j<pPk->nColumn );
1760 pPk->aiColumn[j] = i;
1761 pPk->azColl[j] = "BINARY";
1762 j++;
1763 }
1764 }
1765 assert( pPk->nColumn==j );
1766 assert( pTab->nCol==j );
1767 }else{
1768 pPk->nColumn = pTab->nCol;
1769 }
1770 }
1771
1772 /*
1438 ** This routine is called to report the final ")" that terminates 1773 ** This routine is called to report the final ")" that terminates
1439 ** a CREATE TABLE statement. 1774 ** a CREATE TABLE statement.
1440 ** 1775 **
1441 ** The table structure that other action routines have been building 1776 ** The table structure that other action routines have been building
1442 ** is added to the internal hash tables, assuming no errors have 1777 ** is added to the internal hash tables, assuming no errors have
1443 ** occurred. 1778 ** occurred.
1444 ** 1779 **
1445 ** An entry for the table is made in the master table on disk, unless 1780 ** An entry for the table is made in the master table on disk, unless
1446 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 1781 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
1447 ** it means we are reading the sqlite_master table because we just 1782 ** it means we are reading the sqlite_master table because we just
1448 ** connected to the database or because the sqlite_master table has 1783 ** connected to the database or because the sqlite_master table has
1449 ** recently changed, so the entry for this table already exists in 1784 ** recently changed, so the entry for this table already exists in
1450 ** the sqlite_master table. We do not want to create it again. 1785 ** the sqlite_master table. We do not want to create it again.
1451 ** 1786 **
1452 ** If the pSelect argument is not NULL, it means that this routine 1787 ** If the pSelect argument is not NULL, it means that this routine
1453 ** was called to create a table generated from a 1788 ** was called to create a table generated from a
1454 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 1789 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1455 ** the new table will match the result set of the SELECT. 1790 ** the new table will match the result set of the SELECT.
1456 */ 1791 */
1457 void sqlite3EndTable( 1792 void sqlite3EndTable(
1458 Parse *pParse, /* Parse context */ 1793 Parse *pParse, /* Parse context */
1459 Token *pCons, /* The ',' token after the last column defn. */ 1794 Token *pCons, /* The ',' token after the last column defn. */
1460 Token *pEnd, /* The final ')' token in the CREATE TABLE */ 1795 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1796 u8 tabOpts, /* Extra table options. Usually 0. */
1461 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 1797 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1462 ){ 1798 ){
1463 Table *p; 1799 Table *p; /* The new table */
1464 sqlite3 *db = pParse->db; 1800 sqlite3 *db = pParse->db; /* The database connection */
1465 int iDb; 1801 int iDb; /* Database in which the table lives */
1802 Index *pIdx; /* An implied index of the table */
1466 1803
1467 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){ 1804 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1468 return; 1805 return;
1469 } 1806 }
1470 p = pParse->pNewTable; 1807 p = pParse->pNewTable;
1471 if( p==0 ) return; 1808 if( p==0 ) return;
1472 1809
1473 assert( !db->init.busy || !pSelect ); 1810 assert( !db->init.busy || !pSelect );
1474 1811
1475 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1476
1477 #ifndef SQLITE_OMIT_CHECK
1478 /* Resolve names in all CHECK constraint expressions.
1479 */
1480 if( p->pCheck ){
1481 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1482 NameContext sNC; /* Name context for pParse->pNewTable */
1483
1484 memset(&sNC, 0, sizeof(sNC));
1485 memset(&sSrc, 0, sizeof(sSrc));
1486 sSrc.nSrc = 1;
1487 sSrc.a[0].zName = p->zName;
1488 sSrc.a[0].pTab = p;
1489 sSrc.a[0].iCursor = -1;
1490 sNC.pParse = pParse;
1491 sNC.pSrcList = &sSrc;
1492 sNC.isCheck = 1;
1493 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
1494 return;
1495 }
1496 }
1497 #endif /* !defined(SQLITE_OMIT_CHECK) */
1498
1499 /* If the db->init.busy is 1 it means we are reading the SQL off the 1812 /* If the db->init.busy is 1 it means we are reading the SQL off the
1500 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 1813 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1501 ** So do not write to the disk again. Extract the root page number 1814 ** So do not write to the disk again. Extract the root page number
1502 ** for the table from the db->init.newTnum field. (The page number 1815 ** for the table from the db->init.newTnum field. (The page number
1503 ** should have been put there by the sqliteOpenCb routine.) 1816 ** should have been put there by the sqliteOpenCb routine.)
1504 */ 1817 */
1505 if( db->init.busy ){ 1818 if( db->init.busy ){
1506 p->tnum = db->init.newTnum; 1819 p->tnum = db->init.newTnum;
1507 } 1820 }
1508 1821
1822 /* Special processing for WITHOUT ROWID Tables */
1823 if( tabOpts & TF_WithoutRowid ){
1824 if( (p->tabFlags & TF_Autoincrement) ){
1825 sqlite3ErrorMsg(pParse,
1826 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1827 return;
1828 }
1829 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
1830 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
1831 }else{
1832 p->tabFlags |= TF_WithoutRowid;
1833 convertToWithoutRowidTable(pParse, p);
1834 }
1835 }
1836
1837 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1838
1839 #ifndef SQLITE_OMIT_CHECK
1840 /* Resolve names in all CHECK constraint expressions.
1841 */
1842 if( p->pCheck ){
1843 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
1844 }
1845 #endif /* !defined(SQLITE_OMIT_CHECK) */
1846
1847 /* Estimate the average row size for the table and for all implied indices */
1848 estimateTableWidth(p);
1849 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1850 estimateIndexWidth(pIdx);
1851 }
1852
1509 /* If not initializing, then create a record for the new table 1853 /* If not initializing, then create a record for the new table
1510 ** in the SQLITE_MASTER table of the database. 1854 ** in the SQLITE_MASTER table of the database.
1511 ** 1855 **
1512 ** If this is a TEMPORARY table, write the entry into the auxiliary 1856 ** If this is a TEMPORARY table, write the entry into the auxiliary
1513 ** file instead of into the main database file. 1857 ** file instead of into the main database file.
1514 */ 1858 */
1515 if( !db->init.busy ){ 1859 if( !db->init.busy ){
1516 int n; 1860 int n;
1517 Vdbe *v; 1861 Vdbe *v;
1518 char *zType; /* "view" or "table" */ 1862 char *zType; /* "view" or "table" */
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1551 ** as a schema-lock must have already been obtained to create it. Since 1895 ** as a schema-lock must have already been obtained to create it. Since
1552 ** a schema-lock excludes all other database users, the write-lock would 1896 ** a schema-lock excludes all other database users, the write-lock would
1553 ** be redundant. 1897 ** be redundant.
1554 */ 1898 */
1555 if( pSelect ){ 1899 if( pSelect ){
1556 SelectDest dest; 1900 SelectDest dest;
1557 Table *pSelTab; 1901 Table *pSelTab;
1558 1902
1559 assert(pParse->nTab==1); 1903 assert(pParse->nTab==1);
1560 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 1904 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
1561 sqlite3VdbeChangeP5(v, 1); 1905 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
1562 pParse->nTab = 2; 1906 pParse->nTab = 2;
1563 sqlite3SelectDestInit(&dest, SRT_Table, 1); 1907 sqlite3SelectDestInit(&dest, SRT_Table, 1);
1564 sqlite3Select(pParse, pSelect, &dest); 1908 sqlite3Select(pParse, pSelect, &dest);
1565 sqlite3VdbeAddOp1(v, OP_Close, 1); 1909 sqlite3VdbeAddOp1(v, OP_Close, 1);
1566 if( pParse->nErr==0 ){ 1910 if( pParse->nErr==0 ){
1567 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); 1911 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1568 if( pSelTab==0 ) return; 1912 if( pSelTab==0 ) return;
1569 assert( p->aCol==0 ); 1913 assert( p->aCol==0 );
1570 p->nCol = pSelTab->nCol; 1914 p->nCol = pSelTab->nCol;
1571 p->aCol = pSelTab->aCol; 1915 p->aCol = pSelTab->aCol;
1572 pSelTab->nCol = 0; 1916 pSelTab->nCol = 0;
1573 pSelTab->aCol = 0; 1917 pSelTab->aCol = 0;
1574 sqlite3DeleteTable(db, pSelTab); 1918 sqlite3DeleteTable(db, pSelTab);
1575 } 1919 }
1576 } 1920 }
1577 1921
1578 /* Compute the complete text of the CREATE statement */ 1922 /* Compute the complete text of the CREATE statement */
1579 if( pSelect ){ 1923 if( pSelect ){
1580 zStmt = createTableStmt(db, p); 1924 zStmt = createTableStmt(db, p);
1581 }else{ 1925 }else{
1582 n = (int)(pEnd->z - pParse->sNameToken.z) + 1; 1926 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1927 n = (int)(pEnd2->z - pParse->sNameToken.z);
1928 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
1583 zStmt = sqlite3MPrintf(db, 1929 zStmt = sqlite3MPrintf(db,
1584 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 1930 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1585 ); 1931 );
1586 } 1932 }
1587 1933
1588 /* A slot for the record has already been allocated in the 1934 /* A slot for the record has already been allocated in the
1589 ** SQLITE_MASTER table. We just need to update that slot with all 1935 ** SQLITE_MASTER table. We just need to update that slot with all
1590 ** the information we've collected. 1936 ** the information we've collected.
1591 */ 1937 */
1592 sqlite3NestedParse(pParse, 1938 sqlite3NestedParse(pParse,
(...skipping 21 matching lines...) Expand all
1614 if( pDb->pSchema->pSeqTab==0 ){ 1960 if( pDb->pSchema->pSeqTab==0 ){
1615 sqlite3NestedParse(pParse, 1961 sqlite3NestedParse(pParse,
1616 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 1962 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1617 pDb->zName 1963 pDb->zName
1618 ); 1964 );
1619 } 1965 }
1620 } 1966 }
1621 #endif 1967 #endif
1622 1968
1623 /* Reparse everything to update our internal data structures */ 1969 /* Reparse everything to update our internal data structures */
1624 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 1970 sqlite3VdbeAddParseSchemaOp(v, iDb,
1625 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC); 1971 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
1626 } 1972 }
1627 1973
1628 1974
1629 /* Add the table to the in-memory representation of the database. 1975 /* Add the table to the in-memory representation of the database.
1630 */ 1976 */
1631 if( db->init.busy ){ 1977 if( db->init.busy ){
1632 Table *pOld; 1978 Table *pOld;
1633 Schema *pSchema = p->pSchema; 1979 Schema *pSchema = p->pSchema;
1634 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 1980 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1635 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, 1981 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
1636 sqlite3Strlen30(p->zName),p);
1637 if( pOld ){ 1982 if( pOld ){
1638 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 1983 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1639 db->mallocFailed = 1; 1984 db->mallocFailed = 1;
1640 return; 1985 return;
1641 } 1986 }
1642 pParse->pNewTable = 0; 1987 pParse->pNewTable = 0;
1643 db->nTable++;
1644 db->flags |= SQLITE_InternChanges; 1988 db->flags |= SQLITE_InternChanges;
1645 1989
1646 #ifndef SQLITE_OMIT_ALTERTABLE 1990 #ifndef SQLITE_OMIT_ALTERTABLE
1647 if( !p->pSelect ){ 1991 if( !p->pSelect ){
1648 const char *zName = (const char *)pParse->sNameToken.z; 1992 const char *zName = (const char *)pParse->sNameToken.z;
1649 int nName; 1993 int nName;
1650 assert( !pSelect && pCons && pEnd ); 1994 assert( !pSelect && pCons && pEnd );
1651 if( pCons->z==0 ){ 1995 if( pCons->z==0 ){
1652 pCons = pEnd; 1996 pCons = pEnd;
1653 } 1997 }
(...skipping 15 matching lines...) Expand all
1669 Token *pName2, /* The token that holds the name of the view */ 2013 Token *pName2, /* The token that holds the name of the view */
1670 Select *pSelect, /* A SELECT statement that will become the new view */ 2014 Select *pSelect, /* A SELECT statement that will become the new view */
1671 int isTemp, /* TRUE for a TEMPORARY view */ 2015 int isTemp, /* TRUE for a TEMPORARY view */
1672 int noErr /* Suppress error messages if VIEW already exists */ 2016 int noErr /* Suppress error messages if VIEW already exists */
1673 ){ 2017 ){
1674 Table *p; 2018 Table *p;
1675 int n; 2019 int n;
1676 const char *z; 2020 const char *z;
1677 Token sEnd; 2021 Token sEnd;
1678 DbFixer sFix; 2022 DbFixer sFix;
1679 Token *pName; 2023 Token *pName = 0;
1680 int iDb; 2024 int iDb;
1681 sqlite3 *db = pParse->db; 2025 sqlite3 *db = pParse->db;
1682 2026
1683 if( pParse->nVar>0 ){ 2027 if( pParse->nVar>0 ){
1684 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 2028 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1685 sqlite3SelectDelete(db, pSelect); 2029 sqlite3SelectDelete(db, pSelect);
1686 return; 2030 return;
1687 } 2031 }
1688 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 2032 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
1689 p = pParse->pNewTable; 2033 p = pParse->pNewTable;
1690 if( p==0 || pParse->nErr ){ 2034 if( p==0 || pParse->nErr ){
1691 sqlite3SelectDelete(db, pSelect); 2035 sqlite3SelectDelete(db, pSelect);
1692 return; 2036 return;
1693 } 2037 }
1694 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2038 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1695 iDb = sqlite3SchemaToIndex(db, p->pSchema); 2039 iDb = sqlite3SchemaToIndex(db, p->pSchema);
1696 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName) 2040 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
1697 && sqlite3FixSelect(&sFix, pSelect) 2041 if( sqlite3FixSelect(&sFix, pSelect) ){
1698 ){
1699 sqlite3SelectDelete(db, pSelect); 2042 sqlite3SelectDelete(db, pSelect);
1700 return; 2043 return;
1701 } 2044 }
1702 2045
1703 /* Make a copy of the entire SELECT statement that defines the view. 2046 /* Make a copy of the entire SELECT statement that defines the view.
1704 ** This will force all the Expr.token.z values to be dynamically 2047 ** This will force all the Expr.token.z values to be dynamically
1705 ** allocated rather than point to the input string - which means that 2048 ** allocated rather than point to the input string - which means that
1706 ** they will persist after the current sqlite3_exec() call returns. 2049 ** they will persist after the current sqlite3_exec() call returns.
1707 */ 2050 */
1708 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 2051 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
(...skipping 13 matching lines...) Expand all
1722 sEnd.z += sEnd.n; 2065 sEnd.z += sEnd.n;
1723 } 2066 }
1724 sEnd.n = 0; 2067 sEnd.n = 0;
1725 n = (int)(sEnd.z - pBegin->z); 2068 n = (int)(sEnd.z - pBegin->z);
1726 z = pBegin->z; 2069 z = pBegin->z;
1727 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; } 2070 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
1728 sEnd.z = &z[n-1]; 2071 sEnd.z = &z[n-1];
1729 sEnd.n = 1; 2072 sEnd.n = 1;
1730 2073
1731 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 2074 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1732 sqlite3EndTable(pParse, 0, &sEnd, 0); 2075 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
1733 return; 2076 return;
1734 } 2077 }
1735 #endif /* SQLITE_OMIT_VIEW */ 2078 #endif /* SQLITE_OMIT_VIEW */
1736 2079
1737 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 2080 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1738 /* 2081 /*
1739 ** The Table structure pTable is really a VIEW. Fill in the names of 2082 ** The Table structure pTable is really a VIEW. Fill in the names of
1740 ** the columns of the view in the pTable structure. Return the number 2083 ** the columns of the view in the pTable structure. Return the number
1741 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 2084 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
1742 */ 2085 */
1743 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 2086 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1744 Table *pSelTab; /* A fake table from which we get the result set */ 2087 Table *pSelTab; /* A fake table from which we get the result set */
1745 Select *pSel; /* Copy of the SELECT that implements the view */ 2088 Select *pSel; /* Copy of the SELECT that implements the view */
1746 int nErr = 0; /* Number of errors encountered */ 2089 int nErr = 0; /* Number of errors encountered */
1747 int n; /* Temporarily holds the number of cursors assigned */ 2090 int n; /* Temporarily holds the number of cursors assigned */
1748 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 2091 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
1749 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); 2092 sqlite3_xauth xAuth; /* Saved xAuth pointer */
1750 2093
1751 assert( pTable ); 2094 assert( pTable );
1752 2095
1753 #ifndef SQLITE_OMIT_VIRTUALTABLE 2096 #ifndef SQLITE_OMIT_VIRTUALTABLE
1754 if( sqlite3VtabCallConnect(pParse, pTable) ){ 2097 if( sqlite3VtabCallConnect(pParse, pTable) ){
1755 return SQLITE_ERROR; 2098 return SQLITE_ERROR;
1756 } 2099 }
1757 if( IsVirtual(pTable) ) return 0; 2100 if( IsVirtual(pTable) ) return 0;
1758 #endif 2101 #endif
1759 2102
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
1810 db->lookaside.bEnabled = enableLookaside; 2153 db->lookaside.bEnabled = enableLookaside;
1811 pParse->nTab = n; 2154 pParse->nTab = n;
1812 if( pSelTab ){ 2155 if( pSelTab ){
1813 assert( pTable->aCol==0 ); 2156 assert( pTable->aCol==0 );
1814 pTable->nCol = pSelTab->nCol; 2157 pTable->nCol = pSelTab->nCol;
1815 pTable->aCol = pSelTab->aCol; 2158 pTable->aCol = pSelTab->aCol;
1816 pSelTab->nCol = 0; 2159 pSelTab->nCol = 0;
1817 pSelTab->aCol = 0; 2160 pSelTab->aCol = 0;
1818 sqlite3DeleteTable(db, pSelTab); 2161 sqlite3DeleteTable(db, pSelTab);
1819 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 2162 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
1820 pTable->pSchema->flags |= DB_UnresetViews; 2163 pTable->pSchema->schemaFlags |= DB_UnresetViews;
1821 }else{ 2164 }else{
1822 pTable->nCol = 0; 2165 pTable->nCol = 0;
1823 nErr++; 2166 nErr++;
1824 } 2167 }
1825 sqlite3SelectDelete(db, pSel); 2168 sqlite3SelectDelete(db, pSel);
1826 } else { 2169 } else {
1827 nErr++; 2170 nErr++;
1828 } 2171 }
1829 #endif /* SQLITE_OMIT_VIEW */ 2172 #endif /* SQLITE_OMIT_VIEW */
1830 return nErr; 2173 return nErr;
(...skipping 137 matching lines...) Expand 10 before | Expand all | Expand 10 after
1968 int iIdx = pIdx->tnum; 2311 int iIdx = pIdx->tnum;
1969 assert( pIdx->pSchema==pTab->pSchema ); 2312 assert( pIdx->pSchema==pTab->pSchema );
1970 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 2313 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1971 iLargest = iIdx; 2314 iLargest = iIdx;
1972 } 2315 }
1973 } 2316 }
1974 if( iLargest==0 ){ 2317 if( iLargest==0 ){
1975 return; 2318 return;
1976 }else{ 2319 }else{
1977 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 2320 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2321 assert( iDb>=0 && iDb<pParse->db->nDb );
1978 destroyRootPage(pParse, iLargest, iDb); 2322 destroyRootPage(pParse, iLargest, iDb);
1979 iDestroyed = iLargest; 2323 iDestroyed = iLargest;
1980 } 2324 }
1981 } 2325 }
1982 #endif 2326 #endif
1983 } 2327 }
1984 2328
1985 /* 2329 /*
2330 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
2331 ** after a DROP INDEX or DROP TABLE command.
2332 */
2333 static void sqlite3ClearStatTables(
2334 Parse *pParse, /* The parsing context */
2335 int iDb, /* The database number */
2336 const char *zType, /* "idx" or "tbl" */
2337 const char *zName /* Name of index or table */
2338 ){
2339 int i;
2340 const char *zDbName = pParse->db->aDb[iDb].zName;
2341 for(i=1; i<=4; i++){
2342 char zTab[24];
2343 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2344 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
2345 sqlite3NestedParse(pParse,
2346 "DELETE FROM %Q.%s WHERE %s=%Q",
2347 zDbName, zTab, zType, zName
2348 );
2349 }
2350 }
2351 }
2352
2353 /*
2354 ** Generate code to drop a table.
2355 */
2356 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2357 Vdbe *v;
2358 sqlite3 *db = pParse->db;
2359 Trigger *pTrigger;
2360 Db *pDb = &db->aDb[iDb];
2361
2362 v = sqlite3GetVdbe(pParse);
2363 assert( v!=0 );
2364 sqlite3BeginWriteOperation(pParse, 1, iDb);
2365
2366 #ifndef SQLITE_OMIT_VIRTUALTABLE
2367 if( IsVirtual(pTab) ){
2368 sqlite3VdbeAddOp0(v, OP_VBegin);
2369 }
2370 #endif
2371
2372 /* Drop all triggers associated with the table being dropped. Code
2373 ** is generated to remove entries from sqlite_master and/or
2374 ** sqlite_temp_master if required.
2375 */
2376 pTrigger = sqlite3TriggerList(pParse, pTab);
2377 while( pTrigger ){
2378 assert( pTrigger->pSchema==pTab->pSchema ||
2379 pTrigger->pSchema==db->aDb[1].pSchema );
2380 sqlite3DropTriggerPtr(pParse, pTrigger);
2381 pTrigger = pTrigger->pNext;
2382 }
2383
2384 #ifndef SQLITE_OMIT_AUTOINCREMENT
2385 /* Remove any entries of the sqlite_sequence table associated with
2386 ** the table being dropped. This is done before the table is dropped
2387 ** at the btree level, in case the sqlite_sequence table needs to
2388 ** move as a result of the drop (can happen in auto-vacuum mode).
2389 */
2390 if( pTab->tabFlags & TF_Autoincrement ){
2391 sqlite3NestedParse(pParse,
2392 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2393 pDb->zName, pTab->zName
2394 );
2395 }
2396 #endif
2397
2398 /* Drop all SQLITE_MASTER table and index entries that refer to the
2399 ** table. The program name loops through the master table and deletes
2400 ** every row that refers to a table of the same name as the one being
2401 ** dropped. Triggers are handled separately because a trigger can be
2402 ** created in the temp database that refers to a table in another
2403 ** database.
2404 */
2405 sqlite3NestedParse(pParse,
2406 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2407 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2408 if( !isView && !IsVirtual(pTab) ){
2409 destroyTable(pParse, pTab);
2410 }
2411
2412 /* Remove the table entry from SQLite's internal schema and modify
2413 ** the schema cookie.
2414 */
2415 if( IsVirtual(pTab) ){
2416 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2417 }
2418 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2419 sqlite3ChangeCookie(pParse, iDb);
2420 sqliteViewResetAll(db, iDb);
2421 }
2422
2423 /*
1986 ** This routine is called to do the work of a DROP TABLE statement. 2424 ** This routine is called to do the work of a DROP TABLE statement.
1987 ** pName is the name of the table to be dropped. 2425 ** pName is the name of the table to be dropped.
1988 */ 2426 */
1989 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 2427 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
1990 Table *pTab; 2428 Table *pTab;
1991 Vdbe *v; 2429 Vdbe *v;
1992 sqlite3 *db = pParse->db; 2430 sqlite3 *db = pParse->db;
1993 int iDb; 2431 int iDb;
1994 2432
1995 if( db->mallocFailed ){ 2433 if( db->mallocFailed ){
1996 goto exit_drop_table; 2434 goto exit_drop_table;
1997 } 2435 }
1998 assert( pParse->nErr==0 ); 2436 assert( pParse->nErr==0 );
1999 assert( pName->nSrc==1 ); 2437 assert( pName->nSrc==1 );
2000 if( noErr ) db->suppressErr++; 2438 if( noErr ) db->suppressErr++;
2001 pTab = sqlite3LocateTable(pParse, isView, 2439 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
2002 pName->a[0].zName, pName->a[0].zDatabase);
2003 if( noErr ) db->suppressErr--; 2440 if( noErr ) db->suppressErr--;
2004 2441
2005 if( pTab==0 ){ 2442 if( pTab==0 ){
2006 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 2443 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2007 goto exit_drop_table; 2444 goto exit_drop_table;
2008 } 2445 }
2009 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2446 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2010 assert( iDb>=0 && iDb<db->nDb ); 2447 assert( iDb>=0 && iDb<db->nDb );
2011 2448
2012 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 2449 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
(...skipping 30 matching lines...) Expand all
2043 } 2480 }
2044 } 2481 }
2045 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 2482 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2046 goto exit_drop_table; 2483 goto exit_drop_table;
2047 } 2484 }
2048 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 2485 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2049 goto exit_drop_table; 2486 goto exit_drop_table;
2050 } 2487 }
2051 } 2488 }
2052 #endif 2489 #endif
2053 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 2490 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2491 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
2054 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 2492 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2055 goto exit_drop_table; 2493 goto exit_drop_table;
2056 } 2494 }
2057 2495
2058 #ifndef SQLITE_OMIT_VIEW 2496 #ifndef SQLITE_OMIT_VIEW
2059 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 2497 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2060 ** on a table. 2498 ** on a table.
2061 */ 2499 */
2062 if( isView && pTab->pSelect==0 ){ 2500 if( isView && pTab->pSelect==0 ){
2063 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 2501 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2064 goto exit_drop_table; 2502 goto exit_drop_table;
2065 } 2503 }
2066 if( !isView && pTab->pSelect ){ 2504 if( !isView && pTab->pSelect ){
2067 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 2505 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2068 goto exit_drop_table; 2506 goto exit_drop_table;
2069 } 2507 }
2070 #endif 2508 #endif
2071 2509
2072 /* Generate code to remove the table from the master table 2510 /* Generate code to remove the table from the master table
2073 ** on disk. 2511 ** on disk.
2074 */ 2512 */
2075 v = sqlite3GetVdbe(pParse); 2513 v = sqlite3GetVdbe(pParse);
2076 if( v ){ 2514 if( v ){
2077 Trigger *pTrigger;
2078 Db *pDb = &db->aDb[iDb];
2079 sqlite3BeginWriteOperation(pParse, 1, iDb); 2515 sqlite3BeginWriteOperation(pParse, 1, iDb);
2080 2516 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
2081 #ifndef SQLITE_OMIT_VIRTUALTABLE
2082 if( IsVirtual(pTab) ){
2083 sqlite3VdbeAddOp0(v, OP_VBegin);
2084 }
2085 #endif
2086 sqlite3FkDropTable(pParse, pName, pTab); 2517 sqlite3FkDropTable(pParse, pName, pTab);
2087 2518 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
2088 /* Drop all triggers associated with the table being dropped. Code
2089 ** is generated to remove entries from sqlite_master and/or
2090 ** sqlite_temp_master if required.
2091 */
2092 pTrigger = sqlite3TriggerList(pParse, pTab);
2093 while( pTrigger ){
2094 assert( pTrigger->pSchema==pTab->pSchema ||
2095 pTrigger->pSchema==db->aDb[1].pSchema );
2096 sqlite3DropTriggerPtr(pParse, pTrigger);
2097 pTrigger = pTrigger->pNext;
2098 }
2099
2100 #ifndef SQLITE_OMIT_AUTOINCREMENT
2101 /* Remove any entries of the sqlite_sequence table associated with
2102 ** the table being dropped. This is done before the table is dropped
2103 ** at the btree level, in case the sqlite_sequence table needs to
2104 ** move as a result of the drop (can happen in auto-vacuum mode).
2105 */
2106 if( pTab->tabFlags & TF_Autoincrement ){
2107 sqlite3NestedParse(pParse,
2108 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2109 pDb->zName, pTab->zName
2110 );
2111 }
2112 #endif
2113
2114 /* Drop all SQLITE_MASTER table and index entries that refer to the
2115 ** table. The program name loops through the master table and deletes
2116 ** every row that refers to a table of the same name as the one being
2117 ** dropped. Triggers are handled seperately because a trigger can be
2118 ** created in the temp database that refers to a table in another
2119 ** database.
2120 */
2121 sqlite3NestedParse(pParse,
2122 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2123 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2124
2125 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2126 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2127 sqlite3NestedParse(pParse,
2128 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2129 );
2130 }
2131
2132 if( !isView && !IsVirtual(pTab) ){
2133 destroyTable(pParse, pTab);
2134 }
2135
2136 /* Remove the table entry from SQLite's internal schema and modify
2137 ** the schema cookie.
2138 */
2139 if( IsVirtual(pTab) ){
2140 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2141 }
2142 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2143 sqlite3ChangeCookie(pParse, iDb);
2144 } 2519 }
2145 sqliteViewResetAll(db, iDb);
2146 2520
2147 exit_drop_table: 2521 exit_drop_table:
2148 sqlite3SrcListDelete(db, pName); 2522 sqlite3SrcListDelete(db, pName);
2149 } 2523 }
2150 2524
2151 /* 2525 /*
2152 ** This routine is called to create a new foreign key on the table 2526 ** This routine is called to create a new foreign key on the table
2153 ** currently under construction. pFromCol determines which columns 2527 ** currently under construction. pFromCol determines which columns
2154 ** in the current table point to the foreign key. If pFromCol==0 then 2528 ** in the current table point to the foreign key. If pFromCol==0 then
2155 ** connect the key to the last column inserted. pTo is the name of 2529 ** connect the key to the last column inserted. pTo is the name of
2156 ** the table referred to. pToCol is a list of tables in the other 2530 ** the table referred to (a.k.a the "parent" table). pToCol is a list
2157 ** pTo table that the foreign key points to. flags contains all 2531 ** of tables in the parent pTo table. flags contains all
2158 ** information about the conflict resolution algorithms specified 2532 ** information about the conflict resolution algorithms specified
2159 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 2533 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2160 ** 2534 **
2161 ** An FKey structure is created and added to the table currently 2535 ** An FKey structure is created and added to the table currently
2162 ** under construction in the pParse->pNewTable field. 2536 ** under construction in the pParse->pNewTable field.
2163 ** 2537 **
2164 ** The foreign key is set for IMMEDIATE processing. A subsequent call 2538 ** The foreign key is set for IMMEDIATE processing. A subsequent call
2165 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 2539 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2166 */ 2540 */
2167 void sqlite3CreateForeignKey( 2541 void sqlite3CreateForeignKey(
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
2247 z[n] = 0; 2621 z[n] = 0;
2248 z += n+1; 2622 z += n+1;
2249 } 2623 }
2250 } 2624 }
2251 pFKey->isDeferred = 0; 2625 pFKey->isDeferred = 0;
2252 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 2626 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2253 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 2627 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
2254 2628
2255 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 2629 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2256 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 2630 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2257 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey 2631 pFKey->zTo, (void *)pFKey
2258 ); 2632 );
2259 if( pNextTo==pFKey ){ 2633 if( pNextTo==pFKey ){
2260 db->mallocFailed = 1; 2634 db->mallocFailed = 1;
2261 goto fk_end; 2635 goto fk_end;
2262 } 2636 }
2263 if( pNextTo ){ 2637 if( pNextTo ){
2264 assert( pNextTo->pPrevTo==0 ); 2638 assert( pNextTo->pPrevTo==0 );
2265 pFKey->pNextTo = pNextTo; 2639 pFKey->pNextTo = pNextTo;
2266 pNextTo->pPrevTo = pFKey; 2640 pNextTo->pPrevTo = pFKey;
2267 } 2641 }
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
2303 ** if memRootPage is not negative, it means that the index is newly 2677 ** if memRootPage is not negative, it means that the index is newly
2304 ** created. The register specified by memRootPage contains the 2678 ** created. The register specified by memRootPage contains the
2305 ** root page number of the index. If memRootPage is negative, then 2679 ** root page number of the index. If memRootPage is negative, then
2306 ** the index already exists and must be cleared before being refilled and 2680 ** the index already exists and must be cleared before being refilled and
2307 ** the root page number of the index is taken from pIndex->tnum. 2681 ** the root page number of the index is taken from pIndex->tnum.
2308 */ 2682 */
2309 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 2683 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2310 Table *pTab = pIndex->pTable; /* The table that is indexed */ 2684 Table *pTab = pIndex->pTable; /* The table that is indexed */
2311 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 2685 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2312 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 2686 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
2687 int iSorter; /* Cursor opened by OpenSorter (if in use) */
2313 int addr1; /* Address of top of loop */ 2688 int addr1; /* Address of top of loop */
2689 int addr2; /* Address to jump to for next iteration */
2314 int tnum; /* Root page of index */ 2690 int tnum; /* Root page of index */
2691 int iPartIdxLabel; /* Jump to this label to skip a row */
2315 Vdbe *v; /* Generate code into this virtual machine */ 2692 Vdbe *v; /* Generate code into this virtual machine */
2316 KeyInfo *pKey; /* KeyInfo for index */ 2693 KeyInfo *pKey; /* KeyInfo for index */
2317 int regIdxKey; /* Registers containing the index key */ 2694 int regRecord; /* Register holding assembled index record */
2318 int regRecord; /* Register holding assemblied index record */
2319 sqlite3 *db = pParse->db; /* The database connection */ 2695 sqlite3 *db = pParse->db; /* The database connection */
2320 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2696 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2321 2697
2322 #ifndef SQLITE_OMIT_AUTHORIZATION 2698 #ifndef SQLITE_OMIT_AUTHORIZATION
2323 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 2699 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2324 db->aDb[iDb].zName ) ){ 2700 db->aDb[iDb].zName ) ){
2325 return; 2701 return;
2326 } 2702 }
2327 #endif 2703 #endif
2328 2704
2329 /* Require a write-lock on the table to perform this operation */ 2705 /* Require a write-lock on the table to perform this operation */
2330 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 2706 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2331 2707
2332 v = sqlite3GetVdbe(pParse); 2708 v = sqlite3GetVdbe(pParse);
2333 if( v==0 ) return; 2709 if( v==0 ) return;
2334 if( memRootPage>=0 ){ 2710 if( memRootPage>=0 ){
2335 tnum = memRootPage; 2711 tnum = memRootPage;
2336 }else{ 2712 }else{
2337 tnum = pIndex->tnum; 2713 tnum = pIndex->tnum;
2338 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2339 } 2714 }
2340 pKey = sqlite3IndexKeyinfo(pParse, pIndex); 2715 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
2716
2717 /* Open the sorter cursor if we are to use one. */
2718 iSorter = pParse->nTab++;
2719 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
2720 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
2721
2722 /* Open the table. Loop through all rows of the table, inserting index
2723 ** records into the sorter. */
2724 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2725 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
2726 regRecord = sqlite3GetTempReg(pParse);
2727
2728 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
2729 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
2730 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
2731 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
2732 sqlite3VdbeJumpHere(v, addr1);
2733 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2341 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 2734 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
2342 (char *)pKey, P4_KEYINFO_HANDOFF); 2735 (char *)pKey, P4_KEYINFO);
2343 if( memRootPage>=0 ){ 2736 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2344 sqlite3VdbeChangeP5(v, 1); 2737
2738 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
2739 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
2740 if( IsUniqueIndex(pIndex) && pKey!=0 ){
2741 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2742 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2743 addr2 = sqlite3VdbeCurrentAddr(v);
2744 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
2745 pIndex->nKeyCol); VdbeCoverage(v);
2746 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
2747 }else{
2748 addr2 = sqlite3VdbeCurrentAddr(v);
2345 } 2749 }
2346 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2750 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
2347 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); 2751 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2348 regRecord = sqlite3GetTempReg(pParse);
2349 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2350 if( pIndex->onError!=OE_None ){
2351 const int regRowid = regIdxKey + pIndex->nColumn;
2352 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2353 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
2354
2355 /* The registers accessed by the OP_IsUnique opcode were allocated
2356 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2357 ** call above. Just before that function was freed they were released
2358 ** (made available to the compiler for reuse) using
2359 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2360 ** opcode use the values stored within seems dangerous. However, since
2361 ** we can be sure that no other temp registers have been allocated
2362 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2363 */
2364 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
2365 sqlite3HaltConstraint(
2366 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
2367 }
2368 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
2369 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 2752 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2370 sqlite3ReleaseTempReg(pParse, regRecord); 2753 sqlite3ReleaseTempReg(pParse, regRecord);
2371 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); 2754 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
2372 sqlite3VdbeJumpHere(v, addr1); 2755 sqlite3VdbeJumpHere(v, addr1);
2756
2373 sqlite3VdbeAddOp1(v, OP_Close, iTab); 2757 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2374 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 2758 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
2759 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
2375 } 2760 }
2376 2761
2377 /* 2762 /*
2763 ** Allocate heap space to hold an Index object with nCol columns.
2764 **
2765 ** Increase the allocation size to provide an extra nExtra bytes
2766 ** of 8-byte aligned space after the Index object and return a
2767 ** pointer to this extra space in *ppExtra.
2768 */
2769 Index *sqlite3AllocateIndexObject(
2770 sqlite3 *db, /* Database connection */
2771 i16 nCol, /* Total number of columns in the index */
2772 int nExtra, /* Number of bytes of extra space to alloc */
2773 char **ppExtra /* Pointer to the "extra" space */
2774 ){
2775 Index *p; /* Allocated index object */
2776 int nByte; /* Bytes of space for Index object + arrays */
2777
2778 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2779 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
2780 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
2781 sizeof(i16)*nCol + /* Index.aiColumn */
2782 sizeof(u8)*nCol); /* Index.aSortOrder */
2783 p = sqlite3DbMallocZero(db, nByte + nExtra);
2784 if( p ){
2785 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
2786 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2787 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2788 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
2789 p->aSortOrder = (u8*)pExtra;
2790 p->nColumn = nCol;
2791 p->nKeyCol = nCol - 1;
2792 *ppExtra = ((char*)p) + nByte;
2793 }
2794 return p;
2795 }
2796
2797 /*
2378 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 2798 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
2379 ** and pTblList is the name of the table that is to be indexed. Both will 2799 ** and pTblList is the name of the table that is to be indexed. Both will
2380 ** be NULL for a primary key or an index that is created to satisfy a 2800 ** be NULL for a primary key or an index that is created to satisfy a
2381 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 2801 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
2382 ** as the table to be indexed. pParse->pNewTable is a table that is 2802 ** as the table to be indexed. pParse->pNewTable is a table that is
2383 ** currently being constructed by a CREATE TABLE statement. 2803 ** currently being constructed by a CREATE TABLE statement.
2384 ** 2804 **
2385 ** pList is a list of columns to be indexed. pList will be NULL if this 2805 ** pList is a list of columns to be indexed. pList will be NULL if this
2386 ** is a primary key or unique-constraint on the most recent column added 2806 ** is a primary key or unique-constraint on the most recent column added
2387 ** to the table currently under construction. 2807 ** to the table currently under construction.
2388 ** 2808 **
2389 ** If the index is created successfully, return a pointer to the new Index 2809 ** If the index is created successfully, return a pointer to the new Index
2390 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index 2810 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2391 ** as the tables primary key (Index.autoIndex==2). 2811 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
2392 */ 2812 */
2393 Index *sqlite3CreateIndex( 2813 Index *sqlite3CreateIndex(
2394 Parse *pParse, /* All information about this parse */ 2814 Parse *pParse, /* All information about this parse */
2395 Token *pName1, /* First part of index name. May be NULL */ 2815 Token *pName1, /* First part of index name. May be NULL */
2396 Token *pName2, /* Second part of index name. May be NULL */ 2816 Token *pName2, /* Second part of index name. May be NULL */
2397 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 2817 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2398 ExprList *pList, /* A list of columns to be indexed */ 2818 ExprList *pList, /* A list of columns to be indexed */
2399 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 2819 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2400 Token *pStart, /* The CREATE token that begins this statement */ 2820 Token *pStart, /* The CREATE token that begins this statement */
2401 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */ 2821 Expr *pPIWhere, /* WHERE clause for partial indices */
2402 int sortOrder, /* Sort order of primary key when pList==NULL */ 2822 int sortOrder, /* Sort order of primary key when pList==NULL */
2403 int ifNotExist /* Omit error if index already exists */ 2823 int ifNotExist /* Omit error if index already exists */
2404 ){ 2824 ){
2405 Index *pRet = 0; /* Pointer to return */ 2825 Index *pRet = 0; /* Pointer to return */
2406 Table *pTab = 0; /* Table to be indexed */ 2826 Table *pTab = 0; /* Table to be indexed */
2407 Index *pIndex = 0; /* The index to be created */ 2827 Index *pIndex = 0; /* The index to be created */
2408 char *zName = 0; /* Name of the index */ 2828 char *zName = 0; /* Name of the index */
2409 int nName; /* Number of characters in zName */ 2829 int nName; /* Number of characters in zName */
2410 int i, j; 2830 int i, j;
2411 Token nullId; /* Fake token for an empty ID list */
2412 DbFixer sFix; /* For assigning database names to pTable */ 2831 DbFixer sFix; /* For assigning database names to pTable */
2413 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 2832 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
2414 sqlite3 *db = pParse->db; 2833 sqlite3 *db = pParse->db;
2415 Db *pDb; /* The specific table containing the indexed database */ 2834 Db *pDb; /* The specific table containing the indexed database */
2416 int iDb; /* Index of the database that is being written */ 2835 int iDb; /* Index of the database that is being written */
2417 Token *pName = 0; /* Unqualified name of the index to create */ 2836 Token *pName = 0; /* Unqualified name of the index to create */
2418 struct ExprList_item *pListItem; /* For looping over pList */ 2837 struct ExprList_item *pListItem; /* For looping over pList */
2419 int nCol; 2838 const Column *pTabCol; /* A column in the table */
2420 int nExtra = 0; 2839 int nExtra = 0; /* Space allocated for zExtra[] */
2421 char *zExtra; 2840 int nExtraCol; /* Number of extra columns needed */
2841 char *zExtra = 0; /* Extra space after the Index object */
2842 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
2422 2843
2423 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
2424 assert( pParse->nErr==0 ); /* Never called with prior errors */ 2844 assert( pParse->nErr==0 ); /* Never called with prior errors */
2425 if( db->mallocFailed || IN_DECLARE_VTAB ){ 2845 if( db->mallocFailed || IN_DECLARE_VTAB ){
2426 goto exit_create_index; 2846 goto exit_create_index;
2427 } 2847 }
2428 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2848 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2429 goto exit_create_index; 2849 goto exit_create_index;
2430 } 2850 }
2431 2851
2432 /* 2852 /*
2433 ** Find the table that is to be indexed. Return early if not found. 2853 ** Find the table that is to be indexed. Return early if not found.
2434 */ 2854 */
2435 if( pTblName!=0 ){ 2855 if( pTblName!=0 ){
2436 2856
2437 /* Use the two-part index name to determine the database 2857 /* Use the two-part index name to determine the database
2438 ** to search for the table. 'Fix' the table name to this db 2858 ** to search for the table. 'Fix' the table name to this db
2439 ** before looking up the table. 2859 ** before looking up the table.
2440 */ 2860 */
2441 assert( pName1 && pName2 ); 2861 assert( pName1 && pName2 );
2442 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2862 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2443 if( iDb<0 ) goto exit_create_index; 2863 if( iDb<0 ) goto exit_create_index;
2864 assert( pName && pName->z );
2444 2865
2445 #ifndef SQLITE_OMIT_TEMPDB 2866 #ifndef SQLITE_OMIT_TEMPDB
2446 /* If the index name was unqualified, check if the the table 2867 /* If the index name was unqualified, check if the table
2447 ** is a temp table. If so, set the database to 1. Do not do this 2868 ** is a temp table. If so, set the database to 1. Do not do this
2448 ** if initialising a database schema. 2869 ** if initialising a database schema.
2449 */ 2870 */
2450 if( !db->init.busy ){ 2871 if( !db->init.busy ){
2451 pTab = sqlite3SrcListLookup(pParse, pTblName); 2872 pTab = sqlite3SrcListLookup(pParse, pTblName);
2452 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 2873 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2453 iDb = 1; 2874 iDb = 1;
2454 } 2875 }
2455 } 2876 }
2456 #endif 2877 #endif
2457 2878
2458 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && 2879 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2459 sqlite3FixSrcList(&sFix, pTblName) 2880 if( sqlite3FixSrcList(&sFix, pTblName) ){
2460 ){
2461 /* Because the parser constructs pTblName from a single identifier, 2881 /* Because the parser constructs pTblName from a single identifier,
2462 ** sqlite3FixSrcList can never fail. */ 2882 ** sqlite3FixSrcList can never fail. */
2463 assert(0); 2883 assert(0);
2464 } 2884 }
2465 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 2885 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
2466 pTblName->a[0].zDatabase); 2886 assert( db->mallocFailed==0 || pTab==0 );
2467 if( !pTab || db->mallocFailed ) goto exit_create_index; 2887 if( pTab==0 ) goto exit_create_index;
2468 assert( db->aDb[iDb].pSchema==pTab->pSchema ); 2888 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2889 sqlite3ErrorMsg(pParse,
2890 "cannot create a TEMP index on non-TEMP table \"%s\"",
2891 pTab->zName);
2892 goto exit_create_index;
2893 }
2894 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
2469 }else{ 2895 }else{
2470 assert( pName==0 ); 2896 assert( pName==0 );
2897 assert( pStart==0 );
2471 pTab = pParse->pNewTable; 2898 pTab = pParse->pNewTable;
2472 if( !pTab ) goto exit_create_index; 2899 if( !pTab ) goto exit_create_index;
2473 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2900 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2474 } 2901 }
2475 pDb = &db->aDb[iDb]; 2902 pDb = &db->aDb[iDb];
2476 2903
2477 assert( pTab!=0 ); 2904 assert( pTab!=0 );
2478 assert( pParse->nErr==0 ); 2905 assert( pParse->nErr==0 );
2479 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 2906 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2907 && db->init.busy==0
2908 #if SQLITE_USER_AUTHENTICATION
2909 && sqlite3UserAuthTable(pTab->zName)==0
2910 #endif
2480 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ 2911 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
2481 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 2912 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2482 goto exit_create_index; 2913 goto exit_create_index;
2483 } 2914 }
2484 #ifndef SQLITE_OMIT_VIEW 2915 #ifndef SQLITE_OMIT_VIEW
2485 if( pTab->pSelect ){ 2916 if( pTab->pSelect ){
2486 sqlite3ErrorMsg(pParse, "views may not be indexed"); 2917 sqlite3ErrorMsg(pParse, "views may not be indexed");
2487 goto exit_create_index; 2918 goto exit_create_index;
2488 } 2919 }
2489 #endif 2920 #endif
(...skipping 13 matching lines...) Expand all
2503 ** one of the index names collides with the name of a temporary table or 2934 ** one of the index names collides with the name of a temporary table or
2504 ** index, then we will continue to process this index. 2935 ** index, then we will continue to process this index.
2505 ** 2936 **
2506 ** If pName==0 it means that we are 2937 ** If pName==0 it means that we are
2507 ** dealing with a primary key or UNIQUE constraint. We have to invent our 2938 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2508 ** own name. 2939 ** own name.
2509 */ 2940 */
2510 if( pName ){ 2941 if( pName ){
2511 zName = sqlite3NameFromToken(db, pName); 2942 zName = sqlite3NameFromToken(db, pName);
2512 if( zName==0 ) goto exit_create_index; 2943 if( zName==0 ) goto exit_create_index;
2944 assert( pName->z!=0 );
2513 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 2945 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2514 goto exit_create_index; 2946 goto exit_create_index;
2515 } 2947 }
2516 if( !db->init.busy ){ 2948 if( !db->init.busy ){
2517 if( sqlite3FindTable(db, zName, 0)!=0 ){ 2949 if( sqlite3FindTable(db, zName, 0)!=0 ){
2518 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 2950 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2519 goto exit_create_index; 2951 goto exit_create_index;
2520 } 2952 }
2521 } 2953 }
2522 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ 2954 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
(...skipping 29 matching lines...) Expand all
2552 goto exit_create_index; 2984 goto exit_create_index;
2553 } 2985 }
2554 } 2986 }
2555 #endif 2987 #endif
2556 2988
2557 /* If pList==0, it means this routine was called to make a primary 2989 /* If pList==0, it means this routine was called to make a primary
2558 ** key out of the last column added to the table under construction. 2990 ** key out of the last column added to the table under construction.
2559 ** So create a fake list to simulate this. 2991 ** So create a fake list to simulate this.
2560 */ 2992 */
2561 if( pList==0 ){ 2993 if( pList==0 ){
2562 nullId.z = pTab->aCol[pTab->nCol-1].zName;
2563 nullId.n = sqlite3Strlen30((char*)nullId.z);
2564 pList = sqlite3ExprListAppend(pParse, 0, 0); 2994 pList = sqlite3ExprListAppend(pParse, 0, 0);
2565 if( pList==0 ) goto exit_create_index; 2995 if( pList==0 ) goto exit_create_index;
2566 sqlite3ExprListSetName(pParse, pList, &nullId, 0); 2996 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2997 pTab->aCol[pTab->nCol-1].zName);
2567 pList->a[0].sortOrder = (u8)sortOrder; 2998 pList->a[0].sortOrder = (u8)sortOrder;
2568 } 2999 }
2569 3000
2570 /* Figure out how many bytes of space are required to store explicitly 3001 /* Figure out how many bytes of space are required to store explicitly
2571 ** specified collation sequence names. 3002 ** specified collation sequence names.
2572 */ 3003 */
2573 for(i=0; i<pList->nExpr; i++){ 3004 for(i=0; i<pList->nExpr; i++){
2574 Expr *pExpr = pList->a[i].pExpr; 3005 Expr *pExpr = pList->a[i].pExpr;
2575 if( pExpr ){ 3006 if( pExpr ){
2576 CollSeq *pColl = pExpr->pColl; 3007 assert( pExpr->op==TK_COLLATE );
2577 /* Either pColl!=0 or there was an OOM failure. But if an OOM 3008 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
2578 ** failure we have quit before reaching this point. */
2579 if( ALWAYS(pColl) ){
2580 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2581 }
2582 } 3009 }
2583 } 3010 }
2584 3011
2585 /* 3012 /*
2586 ** Allocate the index structure. 3013 ** Allocate the index structure.
2587 */ 3014 */
2588 nName = sqlite3Strlen30(zName); 3015 nName = sqlite3Strlen30(zName);
2589 nCol = pList->nExpr; 3016 nExtraCol = pPk ? pPk->nKeyCol : 1;
2590 pIndex = sqlite3DbMallocZero(db, 3017 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
2591 sizeof(Index) + /* Index structure */ 3018 nName + nExtra + 1, &zExtra);
2592 sizeof(int)*nCol + /* Index.aiColumn */
2593 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2594 sizeof(char *)*nCol + /* Index.azColl */
2595 sizeof(u8)*nCol + /* Index.aSortOrder */
2596 nName + 1 + /* Index.zName */
2597 nExtra /* Collation sequence names */
2598 );
2599 if( db->mallocFailed ){ 3019 if( db->mallocFailed ){
2600 goto exit_create_index; 3020 goto exit_create_index;
2601 } 3021 }
2602 pIndex->azColl = (char**)(&pIndex[1]); 3022 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
2603 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); 3023 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
2604 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]); 3024 pIndex->zName = zExtra;
2605 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]); 3025 zExtra += nName + 1;
2606 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2607 zExtra = (char *)(&pIndex->zName[nName+1]);
2608 memcpy(pIndex->zName, zName, nName+1); 3026 memcpy(pIndex->zName, zName, nName+1);
2609 pIndex->pTable = pTab; 3027 pIndex->pTable = pTab;
2610 pIndex->nColumn = pList->nExpr;
2611 pIndex->onError = (u8)onError; 3028 pIndex->onError = (u8)onError;
2612 pIndex->autoIndex = (u8)(pName==0); 3029 pIndex->uniqNotNull = onError!=OE_None;
3030 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
2613 pIndex->pSchema = db->aDb[iDb].pSchema; 3031 pIndex->pSchema = db->aDb[iDb].pSchema;
3032 pIndex->nKeyCol = pList->nExpr;
3033 if( pPIWhere ){
3034 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3035 pIndex->pPartIdxWhere = pPIWhere;
3036 pPIWhere = 0;
3037 }
2614 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3038 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2615 3039
2616 /* Check to see if we should honor DESC requests on index columns 3040 /* Check to see if we should honor DESC requests on index columns
2617 */ 3041 */
2618 if( pDb->pSchema->file_format>=4 ){ 3042 if( pDb->pSchema->file_format>=4 ){
2619 sortOrderMask = -1; /* Honor DESC */ 3043 sortOrderMask = -1; /* Honor DESC */
2620 }else{ 3044 }else{
2621 sortOrderMask = 0; /* Ignore DESC */ 3045 sortOrderMask = 0; /* Ignore DESC */
2622 } 3046 }
2623 3047
2624 /* Scan the names of the columns of the table to be indexed and 3048 /* Scan the names of the columns of the table to be indexed and
2625 ** load the column indices into the Index structure. Report an error 3049 ** load the column indices into the Index structure. Report an error
2626 ** if any column is not found. 3050 ** if any column is not found.
2627 ** 3051 **
2628 ** TODO: Add a test to make sure that the same column is not named 3052 ** TODO: Add a test to make sure that the same column is not named
2629 ** more than once within the same index. Only the first instance of 3053 ** more than once within the same index. Only the first instance of
2630 ** the column will ever be used by the optimizer. Note that using the 3054 ** the column will ever be used by the optimizer. Note that using the
2631 ** same column more than once cannot be an error because that would 3055 ** same column more than once cannot be an error because that would
2632 ** break backwards compatibility - it needs to be a warning. 3056 ** break backwards compatibility - it needs to be a warning.
2633 */ 3057 */
2634 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 3058 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2635 const char *zColName = pListItem->zName; 3059 const char *zColName = pListItem->zName;
2636 Column *pTabCol;
2637 int requestedSortOrder; 3060 int requestedSortOrder;
2638 char *zColl; /* Collation sequence name */ 3061 char *zColl; /* Collation sequence name */
2639 3062
2640 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){ 3063 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2641 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; 3064 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
2642 } 3065 }
2643 if( j>=pTab->nCol ){ 3066 if( j>=pTab->nCol ){
2644 sqlite3ErrorMsg(pParse, "table %s has no column named %s", 3067 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2645 pTab->zName, zColName); 3068 pTab->zName, zColName);
2646 pParse->checkSchema = 1; 3069 pParse->checkSchema = 1;
2647 goto exit_create_index; 3070 goto exit_create_index;
2648 } 3071 }
2649 pIndex->aiColumn[i] = j; 3072 assert( j<=0x7fff );
2650 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of 3073 pIndex->aiColumn[i] = (i16)j;
2651 ** the way the "idxlist" non-terminal is constructed by the parser, 3074 if( pListItem->pExpr ){
2652 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2653 ** must exist or else there must have been an OOM error. But if there
2654 ** was an OOM error, we would never reach this point. */
2655 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2656 int nColl; 3075 int nColl;
2657 zColl = pListItem->pExpr->pColl->zName; 3076 assert( pListItem->pExpr->op==TK_COLLATE );
3077 zColl = pListItem->pExpr->u.zToken;
2658 nColl = sqlite3Strlen30(zColl) + 1; 3078 nColl = sqlite3Strlen30(zColl) + 1;
2659 assert( nExtra>=nColl ); 3079 assert( nExtra>=nColl );
2660 memcpy(zExtra, zColl, nColl); 3080 memcpy(zExtra, zColl, nColl);
2661 zColl = zExtra; 3081 zColl = zExtra;
2662 zExtra += nColl; 3082 zExtra += nColl;
2663 nExtra -= nColl; 3083 nExtra -= nColl;
2664 }else{ 3084 }else{
2665 zColl = pTab->aCol[j].zColl; 3085 zColl = pTab->aCol[j].zColl;
2666 if( !zColl ){ 3086 if( !zColl ) zColl = "BINARY";
2667 zColl = db->pDfltColl->zName;
2668 }
2669 } 3087 }
2670 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 3088 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
2671 goto exit_create_index; 3089 goto exit_create_index;
2672 } 3090 }
2673 pIndex->azColl[i] = zColl; 3091 pIndex->azColl[i] = zColl;
2674 requestedSortOrder = pListItem->sortOrder & sortOrderMask; 3092 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
2675 pIndex->aSortOrder[i] = (u8)requestedSortOrder; 3093 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
3094 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
3095 }
3096 if( pPk ){
3097 for(j=0; j<pPk->nKeyCol; j++){
3098 int x = pPk->aiColumn[j];
3099 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3100 pIndex->nColumn--;
3101 }else{
3102 pIndex->aiColumn[i] = x;
3103 pIndex->azColl[i] = pPk->azColl[j];
3104 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3105 i++;
3106 }
3107 }
3108 assert( i==pIndex->nColumn );
3109 }else{
3110 pIndex->aiColumn[i] = -1;
3111 pIndex->azColl[i] = "BINARY";
2676 } 3112 }
2677 sqlite3DefaultRowEst(pIndex); 3113 sqlite3DefaultRowEst(pIndex);
3114 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
2678 3115
2679 if( pTab==pParse->pNewTable ){ 3116 if( pTab==pParse->pNewTable ){
2680 /* This routine has been called to create an automatic index as a 3117 /* This routine has been called to create an automatic index as a
2681 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 3118 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2682 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 3119 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2683 ** i.e. one of: 3120 ** i.e. one of:
2684 ** 3121 **
2685 ** CREATE TABLE t(x PRIMARY KEY, y); 3122 ** CREATE TABLE t(x PRIMARY KEY, y);
2686 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 3123 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2687 ** 3124 **
2688 ** Either way, check to see if the table already has such an index. If 3125 ** Either way, check to see if the table already has such an index. If
2689 ** so, don't bother creating this one. This only applies to 3126 ** so, don't bother creating this one. This only applies to
2690 ** automatically created indices. Users can do as they wish with 3127 ** automatically created indices. Users can do as they wish with
2691 ** explicit indices. 3128 ** explicit indices.
2692 ** 3129 **
2693 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 3130 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2694 ** (and thus suppressing the second one) even if they have different 3131 ** (and thus suppressing the second one) even if they have different
2695 ** sort orders. 3132 ** sort orders.
2696 ** 3133 **
2697 ** If there are different collating sequences or if the columns of 3134 ** If there are different collating sequences or if the columns of
2698 ** the constraint occur in different orders, then the constraints are 3135 ** the constraint occur in different orders, then the constraints are
2699 ** considered distinct and both result in separate indices. 3136 ** considered distinct and both result in separate indices.
2700 */ 3137 */
2701 Index *pIdx; 3138 Index *pIdx;
2702 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 3139 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2703 int k; 3140 int k;
2704 assert( pIdx->onError!=OE_None ); 3141 assert( IsUniqueIndex(pIdx) );
2705 assert( pIdx->autoIndex ); 3142 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
2706 assert( pIndex->onError!=OE_None ); 3143 assert( IsUniqueIndex(pIndex) );
2707 3144
2708 if( pIdx->nColumn!=pIndex->nColumn ) continue; 3145 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
2709 for(k=0; k<pIdx->nColumn; k++){ 3146 for(k=0; k<pIdx->nKeyCol; k++){
2710 const char *z1; 3147 const char *z1;
2711 const char *z2; 3148 const char *z2;
2712 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 3149 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2713 z1 = pIdx->azColl[k]; 3150 z1 = pIdx->azColl[k];
2714 z2 = pIndex->azColl[k]; 3151 z2 = pIndex->azColl[k];
2715 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; 3152 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
2716 } 3153 }
2717 if( k==pIdx->nColumn ){ 3154 if( k==pIdx->nKeyCol ){
2718 if( pIdx->onError!=pIndex->onError ){ 3155 if( pIdx->onError!=pIndex->onError ){
2719 /* This constraint creates the same index as a previous 3156 /* This constraint creates the same index as a previous
2720 ** constraint specified somewhere in the CREATE TABLE statement. 3157 ** constraint specified somewhere in the CREATE TABLE statement.
2721 ** However the ON CONFLICT clauses are different. If both this 3158 ** However the ON CONFLICT clauses are different. If both this
2722 ** constraint and the previous equivalent constraint have explicit 3159 ** constraint and the previous equivalent constraint have explicit
2723 ** ON CONFLICT clauses this is an error. Otherwise, use the 3160 ** ON CONFLICT clauses this is an error. Otherwise, use the
2724 ** explicitly specified behaviour for the index. 3161 ** explicitly specified behavior for the index.
2725 */ 3162 */
2726 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 3163 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2727 sqlite3ErrorMsg(pParse, 3164 sqlite3ErrorMsg(pParse,
2728 "conflicting ON CONFLICT clauses specified", 0); 3165 "conflicting ON CONFLICT clauses specified", 0);
2729 } 3166 }
2730 if( pIdx->onError==OE_Default ){ 3167 if( pIdx->onError==OE_Default ){
2731 pIdx->onError = pIndex->onError; 3168 pIdx->onError = pIndex->onError;
2732 } 3169 }
2733 } 3170 }
2734 goto exit_create_index; 3171 goto exit_create_index;
2735 } 3172 }
2736 } 3173 }
2737 } 3174 }
2738 3175
2739 /* Link the new Index structure to its table and to the other 3176 /* Link the new Index structure to its table and to the other
2740 ** in-memory database structures. 3177 ** in-memory database structures.
2741 */ 3178 */
2742 if( db->init.busy ){ 3179 if( db->init.busy ){
2743 Index *p; 3180 Index *p;
2744 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 3181 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
2745 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 3182 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
2746 pIndex->zName, sqlite3Strlen30(pIndex->zName), 3183 pIndex->zName, pIndex);
2747 pIndex);
2748 if( p ){ 3184 if( p ){
2749 assert( p==pIndex ); /* Malloc must have failed */ 3185 assert( p==pIndex ); /* Malloc must have failed */
2750 db->mallocFailed = 1; 3186 db->mallocFailed = 1;
2751 goto exit_create_index; 3187 goto exit_create_index;
2752 } 3188 }
2753 db->flags |= SQLITE_InternChanges; 3189 db->flags |= SQLITE_InternChanges;
2754 if( pTblName!=0 ){ 3190 if( pTblName!=0 ){
2755 pIndex->tnum = db->init.newTnum; 3191 pIndex->tnum = db->init.newTnum;
2756 } 3192 }
2757 } 3193 }
2758 3194
2759 /* If the db->init.busy is 0 then create the index on disk. This 3195 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
2760 ** involves writing the index into the master table and filling in the 3196 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
2761 ** index with the current table contents. 3197 ** emit code to allocate the index rootpage on disk and make an entry for
3198 ** the index in the sqlite_master table and populate the index with
3199 ** content. But, do not do this if we are simply reading the sqlite_master
3200 ** table to parse the schema, or if this index is the PRIMARY KEY index
3201 ** of a WITHOUT ROWID table.
2762 ** 3202 **
2763 ** The db->init.busy is 0 when the user first enters a CREATE INDEX 3203 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
2764 ** command. db->init.busy is 1 when a database is opened and 3204 ** or UNIQUE index in a CREATE TABLE statement. Since the table
2765 ** CREATE INDEX statements are read out of the master table. In
2766 ** the latter case the index already exists on disk, which is why
2767 ** we don't want to recreate it.
2768 **
2769 ** If pTblName==0 it means this index is generated as a primary key
2770 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2771 ** has just been created, it contains no data and the index initialization 3205 ** has just been created, it contains no data and the index initialization
2772 ** step can be skipped. 3206 ** step can be skipped.
2773 */ 3207 */
2774 else{ /* if( db->init.busy==0 ) */ 3208 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
2775 Vdbe *v; 3209 Vdbe *v;
2776 char *zStmt; 3210 char *zStmt;
2777 int iMem = ++pParse->nMem; 3211 int iMem = ++pParse->nMem;
2778 3212
2779 v = sqlite3GetVdbe(pParse); 3213 v = sqlite3GetVdbe(pParse);
2780 if( v==0 ) goto exit_create_index; 3214 if( v==0 ) goto exit_create_index;
2781 3215
2782 3216
2783 /* Create the rootpage for the index 3217 /* Create the rootpage for the index
2784 */ 3218 */
2785 sqlite3BeginWriteOperation(pParse, 1, iDb); 3219 sqlite3BeginWriteOperation(pParse, 1, iDb);
2786 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 3220 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
2787 3221
2788 /* Gather the complete text of the CREATE INDEX statement into 3222 /* Gather the complete text of the CREATE INDEX statement into
2789 ** the zStmt variable 3223 ** the zStmt variable
2790 */ 3224 */
2791 if( pStart ){ 3225 if( pStart ){
2792 assert( pEnd!=0 ); 3226 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
3227 if( pName->z[n-1]==';' ) n--;
2793 /* A named index with an explicit CREATE INDEX statement */ 3228 /* A named index with an explicit CREATE INDEX statement */
2794 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 3229 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
2795 onError==OE_None ? "" : " UNIQUE", 3230 onError==OE_None ? "" : " UNIQUE", n, pName->z);
2796 pEnd->z - pName->z + 1,
2797 pName->z);
2798 }else{ 3231 }else{
2799 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 3232 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
2800 /* zStmt = sqlite3MPrintf(""); */ 3233 /* zStmt = sqlite3MPrintf(""); */
2801 zStmt = 0; 3234 zStmt = 0;
2802 } 3235 }
2803 3236
2804 /* Add an entry in sqlite_master for this index 3237 /* Add an entry in sqlite_master for this index
2805 */ 3238 */
2806 sqlite3NestedParse(pParse, 3239 sqlite3NestedParse(pParse,
2807 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 3240 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
2808 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 3241 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2809 pIndex->zName, 3242 pIndex->zName,
2810 pTab->zName, 3243 pTab->zName,
2811 iMem, 3244 iMem,
2812 zStmt 3245 zStmt
2813 ); 3246 );
2814 sqlite3DbFree(db, zStmt); 3247 sqlite3DbFree(db, zStmt);
2815 3248
2816 /* Fill the index with data and reparse the schema. Code an OP_Expire 3249 /* Fill the index with data and reparse the schema. Code an OP_Expire
2817 ** to invalidate all pre-compiled statements. 3250 ** to invalidate all pre-compiled statements.
2818 */ 3251 */
2819 if( pTblName ){ 3252 if( pTblName ){
2820 sqlite3RefillIndex(pParse, pIndex, iMem); 3253 sqlite3RefillIndex(pParse, pIndex, iMem);
2821 sqlite3ChangeCookie(pParse, iDb); 3254 sqlite3ChangeCookie(pParse, iDb);
2822 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 3255 sqlite3VdbeAddParseSchemaOp(v, iDb,
2823 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 3256 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
2824 P4_DYNAMIC);
2825 sqlite3VdbeAddOp1(v, OP_Expire, 0); 3257 sqlite3VdbeAddOp1(v, OP_Expire, 0);
2826 } 3258 }
2827 } 3259 }
2828 3260
2829 /* When adding an index to the list of indices for a table, make 3261 /* When adding an index to the list of indices for a table, make
2830 ** sure all indices labeled OE_Replace come after all those labeled 3262 ** sure all indices labeled OE_Replace come after all those labeled
2831 ** OE_Ignore. This is necessary for the correct constraint check 3263 ** OE_Ignore. This is necessary for the correct constraint check
2832 ** processing (in sqlite3GenerateConstraintChecks()) as part of 3264 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2833 ** UPDATE and INSERT statements. 3265 ** UPDATE and INSERT statements.
2834 */ 3266 */
2835 if( db->init.busy || pTblName==0 ){ 3267 if( db->init.busy || pTblName==0 ){
2836 if( onError!=OE_Replace || pTab->pIndex==0 3268 if( onError!=OE_Replace || pTab->pIndex==0
2837 || pTab->pIndex->onError==OE_Replace){ 3269 || pTab->pIndex->onError==OE_Replace){
2838 pIndex->pNext = pTab->pIndex; 3270 pIndex->pNext = pTab->pIndex;
2839 pTab->pIndex = pIndex; 3271 pTab->pIndex = pIndex;
2840 }else{ 3272 }else{
2841 Index *pOther = pTab->pIndex; 3273 Index *pOther = pTab->pIndex;
2842 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 3274 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2843 pOther = pOther->pNext; 3275 pOther = pOther->pNext;
2844 } 3276 }
2845 pIndex->pNext = pOther->pNext; 3277 pIndex->pNext = pOther->pNext;
2846 pOther->pNext = pIndex; 3278 pOther->pNext = pIndex;
2847 } 3279 }
2848 pRet = pIndex; 3280 pRet = pIndex;
2849 pIndex = 0; 3281 pIndex = 0;
2850 } 3282 }
2851 3283
2852 /* Clean up before exiting */ 3284 /* Clean up before exiting */
2853 exit_create_index: 3285 exit_create_index:
2854 if( pIndex ){ 3286 if( pIndex ) freeIndex(db, pIndex);
2855 sqlite3DbFree(db, pIndex->zColAff); 3287 sqlite3ExprDelete(db, pPIWhere);
2856 sqlite3DbFree(db, pIndex);
2857 }
2858 sqlite3ExprListDelete(db, pList); 3288 sqlite3ExprListDelete(db, pList);
2859 sqlite3SrcListDelete(db, pTblName); 3289 sqlite3SrcListDelete(db, pTblName);
2860 sqlite3DbFree(db, zName); 3290 sqlite3DbFree(db, zName);
2861 return pRet; 3291 return pRet;
2862 } 3292 }
2863 3293
2864 /* 3294 /*
2865 ** Fill the Index.aiRowEst[] array with default information - information 3295 ** Fill the Index.aiRowEst[] array with default information - information
2866 ** to be used when we have not run the ANALYZE command. 3296 ** to be used when we have not run the ANALYZE command.
2867 ** 3297 **
2868 ** aiRowEst[0] is suppose to contain the number of elements in the index. 3298 ** aiRowEst[0] is supposed to contain the number of elements in the index.
2869 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 3299 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2870 ** number of rows in the table that match any particular value of the 3300 ** number of rows in the table that match any particular value of the
2871 ** first column of the index. aiRowEst[2] is an estimate of the number 3301 ** first column of the index. aiRowEst[2] is an estimate of the number
2872 ** of rows that match any particular combiniation of the first 2 columns 3302 ** of rows that match any particular combination of the first 2 columns
2873 ** of the index. And so forth. It must always be the case that 3303 ** of the index. And so forth. It must always be the case that
2874 * 3304 *
2875 ** aiRowEst[N]<=aiRowEst[N-1] 3305 ** aiRowEst[N]<=aiRowEst[N-1]
2876 ** aiRowEst[N]>=1 3306 ** aiRowEst[N]>=1
2877 ** 3307 **
2878 ** Apart from that, we have little to go on besides intuition as to 3308 ** Apart from that, we have little to go on besides intuition as to
2879 ** how aiRowEst[] should be initialized. The numbers generated here 3309 ** how aiRowEst[] should be initialized. The numbers generated here
2880 ** are based on typical values found in actual indices. 3310 ** are based on typical values found in actual indices.
2881 */ 3311 */
2882 void sqlite3DefaultRowEst(Index *pIdx){ 3312 void sqlite3DefaultRowEst(Index *pIdx){
2883 unsigned *a = pIdx->aiRowEst; 3313 /* 10, 9, 8, 7, 6 */
3314 LogEst aVal[] = { 33, 32, 30, 28, 26 };
3315 LogEst *a = pIdx->aiRowLogEst;
3316 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
2884 int i; 3317 int i;
2885 unsigned n; 3318
2886 assert( a!=0 ); 3319 /* Set the first entry (number of rows in the index) to the estimated
2887 a[0] = pIdx->pTable->nRowEst; 3320 ** number of rows in the table. Or 10, if the estimated number of rows
2888 if( a[0]<10 ) a[0] = 10; 3321 ** in the table is less than that. */
2889 n = 10; 3322 a[0] = pIdx->pTable->nRowLogEst;
2890 for(i=1; i<=pIdx->nColumn; i++){ 3323 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
2891 a[i] = n; 3324
2892 if( n>5 ) n--; 3325 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3326 ** 6 and each subsequent value (if any) is 5. */
3327 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
3328 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3329 a[i] = 23; assert( 23==sqlite3LogEst(5) );
2893 } 3330 }
2894 if( pIdx->onError!=OE_None ){ 3331
2895 a[pIdx->nColumn] = 1; 3332 assert( 0==sqlite3LogEst(1) );
2896 } 3333 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
2897 } 3334 }
2898 3335
2899 /* 3336 /*
2900 ** This routine will drop an existing named index. This routine 3337 ** This routine will drop an existing named index. This routine
2901 ** implements the DROP INDEX statement. 3338 ** implements the DROP INDEX statement.
2902 */ 3339 */
2903 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 3340 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
2904 Index *pIndex; 3341 Index *pIndex;
2905 Vdbe *v; 3342 Vdbe *v;
2906 sqlite3 *db = pParse->db; 3343 sqlite3 *db = pParse->db;
(...skipping 10 matching lines...) Expand all
2917 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 3354 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2918 if( pIndex==0 ){ 3355 if( pIndex==0 ){
2919 if( !ifExists ){ 3356 if( !ifExists ){
2920 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 3357 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2921 }else{ 3358 }else{
2922 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 3359 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2923 } 3360 }
2924 pParse->checkSchema = 1; 3361 pParse->checkSchema = 1;
2925 goto exit_drop_index; 3362 goto exit_drop_index;
2926 } 3363 }
2927 if( pIndex->autoIndex ){ 3364 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
2928 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 3365 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
2929 "or PRIMARY KEY constraint cannot be dropped", 0); 3366 "or PRIMARY KEY constraint cannot be dropped", 0);
2930 goto exit_drop_index; 3367 goto exit_drop_index;
2931 } 3368 }
2932 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 3369 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2933 #ifndef SQLITE_OMIT_AUTHORIZATION 3370 #ifndef SQLITE_OMIT_AUTHORIZATION
2934 { 3371 {
2935 int code = SQLITE_DROP_INDEX; 3372 int code = SQLITE_DROP_INDEX;
2936 Table *pTab = pIndex->pTable; 3373 Table *pTab = pIndex->pTable;
2937 const char *zDb = db->aDb[iDb].zName; 3374 const char *zDb = db->aDb[iDb].zName;
2938 const char *zTab = SCHEMA_TABLE(iDb); 3375 const char *zTab = SCHEMA_TABLE(iDb);
2939 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 3376 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
2940 goto exit_drop_index; 3377 goto exit_drop_index;
2941 } 3378 }
2942 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 3379 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
2943 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 3380 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
2944 goto exit_drop_index; 3381 goto exit_drop_index;
2945 } 3382 }
2946 } 3383 }
2947 #endif 3384 #endif
2948 3385
2949 /* Generate code to remove the index and from the master table */ 3386 /* Generate code to remove the index and from the master table */
2950 v = sqlite3GetVdbe(pParse); 3387 v = sqlite3GetVdbe(pParse);
2951 if( v ){ 3388 if( v ){
2952 sqlite3BeginWriteOperation(pParse, 1, iDb); 3389 sqlite3BeginWriteOperation(pParse, 1, iDb);
2953 sqlite3NestedParse(pParse, 3390 sqlite3NestedParse(pParse,
2954 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", 3391 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
2955 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 3392 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
2956 pIndex->zName
2957 ); 3393 );
2958 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 3394 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
2959 sqlite3NestedParse(pParse,
2960 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2961 db->aDb[iDb].zName, pIndex->zName
2962 );
2963 }
2964 sqlite3ChangeCookie(pParse, iDb); 3395 sqlite3ChangeCookie(pParse, iDb);
2965 destroyRootPage(pParse, pIndex->tnum, iDb); 3396 destroyRootPage(pParse, pIndex->tnum, iDb);
2966 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 3397 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
2967 } 3398 }
2968 3399
2969 exit_drop_index: 3400 exit_drop_index:
2970 sqlite3SrcListDelete(db, pName); 3401 sqlite3SrcListDelete(db, pName);
2971 } 3402 }
2972 3403
2973 /* 3404 /*
2974 ** pArray is a pointer to an array of objects. Each object in the 3405 ** pArray is a pointer to an array of objects. Each object in the
2975 ** array is szEntry bytes in size. This routine allocates a new 3406 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
2976 ** object on the end of the array. 3407 ** to extend the array so that there is space for a new object at the end.
2977 ** 3408 **
2978 ** *pnEntry is the number of entries already in use. *pnAlloc is 3409 ** When this function is called, *pnEntry contains the current size of
2979 ** the previously allocated size of the array. initSize is the 3410 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
2980 ** suggested initial array size allocation. 3411 ** in total).
2981 ** 3412 **
2982 ** The index of the new entry is returned in *pIdx. 3413 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
3414 ** space allocated for the new object is zeroed, *pnEntry updated to
3415 ** reflect the new size of the array and a pointer to the new allocation
3416 ** returned. *pIdx is set to the index of the new array entry in this case.
2983 ** 3417 **
2984 ** This routine returns a pointer to the array of objects. This 3418 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
2985 ** might be the same as the pArray parameter or it might be a different 3419 ** unchanged and a copy of pArray returned.
2986 ** pointer if the array was resized.
2987 */ 3420 */
2988 void *sqlite3ArrayAllocate( 3421 void *sqlite3ArrayAllocate(
2989 sqlite3 *db, /* Connection to notify of malloc failures */ 3422 sqlite3 *db, /* Connection to notify of malloc failures */
2990 void *pArray, /* Array of objects. Might be reallocated */ 3423 void *pArray, /* Array of objects. Might be reallocated */
2991 int szEntry, /* Size of each object in the array */ 3424 int szEntry, /* Size of each object in the array */
2992 int initSize, /* Suggested initial allocation, in elements */
2993 int *pnEntry, /* Number of objects currently in use */ 3425 int *pnEntry, /* Number of objects currently in use */
2994 int *pnAlloc, /* Current size of the allocation, in elements */
2995 int *pIdx /* Write the index of a new slot here */ 3426 int *pIdx /* Write the index of a new slot here */
2996 ){ 3427 ){
2997 char *z; 3428 char *z;
2998 if( *pnEntry >= *pnAlloc ){ 3429 int n = *pnEntry;
2999 void *pNew; 3430 if( (n & (n-1))==0 ){
3000 int newSize; 3431 int sz = (n==0) ? 1 : 2*n;
3001 newSize = (*pnAlloc)*2 + initSize; 3432 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
3002 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
3003 if( pNew==0 ){ 3433 if( pNew==0 ){
3004 *pIdx = -1; 3434 *pIdx = -1;
3005 return pArray; 3435 return pArray;
3006 } 3436 }
3007 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
3008 pArray = pNew; 3437 pArray = pNew;
3009 } 3438 }
3010 z = (char*)pArray; 3439 z = (char*)pArray;
3011 memset(&z[*pnEntry * szEntry], 0, szEntry); 3440 memset(&z[n * szEntry], 0, szEntry);
3012 *pIdx = *pnEntry; 3441 *pIdx = n;
3013 ++*pnEntry; 3442 ++*pnEntry;
3014 return pArray; 3443 return pArray;
3015 } 3444 }
3016 3445
3017 /* 3446 /*
3018 ** Append a new element to the given IdList. Create a new IdList if 3447 ** Append a new element to the given IdList. Create a new IdList if
3019 ** need be. 3448 ** need be.
3020 ** 3449 **
3021 ** A new IdList is returned, or NULL if malloc() fails. 3450 ** A new IdList is returned, or NULL if malloc() fails.
3022 */ 3451 */
3023 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 3452 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
3024 int i; 3453 int i;
3025 if( pList==0 ){ 3454 if( pList==0 ){
3026 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 3455 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3027 if( pList==0 ) return 0; 3456 if( pList==0 ) return 0;
3028 pList->nAlloc = 0;
3029 } 3457 }
3030 pList->a = sqlite3ArrayAllocate( 3458 pList->a = sqlite3ArrayAllocate(
3031 db, 3459 db,
3032 pList->a, 3460 pList->a,
3033 sizeof(pList->a[0]), 3461 sizeof(pList->a[0]),
3034 5,
3035 &pList->nId, 3462 &pList->nId,
3036 &pList->nAlloc,
3037 &i 3463 &i
3038 ); 3464 );
3039 if( i<0 ){ 3465 if( i<0 ){
3040 sqlite3IdListDelete(db, pList); 3466 sqlite3IdListDelete(db, pList);
3041 return 0; 3467 return 0;
3042 } 3468 }
3043 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 3469 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3044 return pList; 3470 return pList;
3045 } 3471 }
3046 3472
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
3097 ){ 3523 ){
3098 int i; 3524 int i;
3099 3525
3100 /* Sanity checking on calling parameters */ 3526 /* Sanity checking on calling parameters */
3101 assert( iStart>=0 ); 3527 assert( iStart>=0 );
3102 assert( nExtra>=1 ); 3528 assert( nExtra>=1 );
3103 assert( pSrc!=0 ); 3529 assert( pSrc!=0 );
3104 assert( iStart<=pSrc->nSrc ); 3530 assert( iStart<=pSrc->nSrc );
3105 3531
3106 /* Allocate additional space if needed */ 3532 /* Allocate additional space if needed */
3107 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){ 3533 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
3108 SrcList *pNew; 3534 SrcList *pNew;
3109 int nAlloc = pSrc->nSrc+nExtra; 3535 int nAlloc = pSrc->nSrc+nExtra;
3110 int nGot; 3536 int nGot;
3111 pNew = sqlite3DbRealloc(db, pSrc, 3537 pNew = sqlite3DbRealloc(db, pSrc,
3112 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 3538 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3113 if( pNew==0 ){ 3539 if( pNew==0 ){
3114 assert( db->mallocFailed ); 3540 assert( db->mallocFailed );
3115 return pSrc; 3541 return pSrc;
3116 } 3542 }
3117 pSrc = pNew; 3543 pSrc = pNew;
3118 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; 3544 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3119 pSrc->nAlloc = (u16)nGot; 3545 pSrc->nAlloc = nGot;
3120 } 3546 }
3121 3547
3122 /* Move existing slots that come after the newly inserted slots 3548 /* Move existing slots that come after the newly inserted slots
3123 ** out of the way */ 3549 ** out of the way */
3124 for(i=pSrc->nSrc-1; i>=iStart; i--){ 3550 for(i=pSrc->nSrc-1; i>=iStart; i--){
3125 pSrc->a[i+nExtra] = pSrc->a[i]; 3551 pSrc->a[i+nExtra] = pSrc->a[i];
3126 } 3552 }
3127 pSrc->nSrc += (i16)nExtra; 3553 pSrc->nSrc += nExtra;
3128 3554
3129 /* Zero the newly allocated slots */ 3555 /* Zero the newly allocated slots */
3130 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 3556 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3131 for(i=iStart; i<iStart+nExtra; i++){ 3557 for(i=iStart; i<iStart+nExtra; i++){
3132 pSrc->a[i].iCursor = -1; 3558 pSrc->a[i].iCursor = -1;
3133 } 3559 }
3134 3560
3135 /* Return a pointer to the enlarged SrcList */ 3561 /* Return a pointer to the enlarged SrcList */
3136 return pSrc; 3562 return pSrc;
3137 } 3563 }
(...skipping 103 matching lines...) Expand 10 before | Expand all | Expand 10 after
3241 sqlite3DbFree(db, pList); 3667 sqlite3DbFree(db, pList);
3242 } 3668 }
3243 3669
3244 /* 3670 /*
3245 ** This routine is called by the parser to add a new term to the 3671 ** This routine is called by the parser to add a new term to the
3246 ** end of a growing FROM clause. The "p" parameter is the part of 3672 ** end of a growing FROM clause. The "p" parameter is the part of
3247 ** the FROM clause that has already been constructed. "p" is NULL 3673 ** the FROM clause that has already been constructed. "p" is NULL
3248 ** if this is the first term of the FROM clause. pTable and pDatabase 3674 ** if this is the first term of the FROM clause. pTable and pDatabase
3249 ** are the name of the table and database named in the FROM clause term. 3675 ** are the name of the table and database named in the FROM clause term.
3250 ** pDatabase is NULL if the database name qualifier is missing - the 3676 ** pDatabase is NULL if the database name qualifier is missing - the
3251 ** usual case. If the term has a alias, then pAlias points to the 3677 ** usual case. If the term has an alias, then pAlias points to the
3252 ** alias token. If the term is a subquery, then pSubquery is the 3678 ** alias token. If the term is a subquery, then pSubquery is the
3253 ** SELECT statement that the subquery encodes. The pTable and 3679 ** SELECT statement that the subquery encodes. The pTable and
3254 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 3680 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3255 ** parameters are the content of the ON and USING clauses. 3681 ** parameters are the content of the ON and USING clauses.
3256 ** 3682 **
3257 ** Return a new SrcList which encodes is the FROM with the new 3683 ** Return a new SrcList which encodes is the FROM with the new
3258 ** term added. 3684 ** term added.
3259 */ 3685 */
3260 SrcList *sqlite3SrcListAppendFromTerm( 3686 SrcList *sqlite3SrcListAppendFromTerm(
3261 Parse *pParse, /* Parsing context */ 3687 Parse *pParse, /* Parsing context */
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
3325 ** 3751 **
3326 ** Example: Suppose the join is like this: 3752 ** Example: Suppose the join is like this:
3327 ** 3753 **
3328 ** A natural cross join B 3754 ** A natural cross join B
3329 ** 3755 **
3330 ** The operator is "natural cross join". The A and B operands are stored 3756 ** The operator is "natural cross join". The A and B operands are stored
3331 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 3757 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
3332 ** operator with A. This routine shifts that operator over to B. 3758 ** operator with A. This routine shifts that operator over to B.
3333 */ 3759 */
3334 void sqlite3SrcListShiftJoinType(SrcList *p){ 3760 void sqlite3SrcListShiftJoinType(SrcList *p){
3335 if( p && p->a ){ 3761 if( p ){
3336 int i; 3762 int i;
3763 assert( p->a || p->nSrc==0 );
3337 for(i=p->nSrc-1; i>0; i--){ 3764 for(i=p->nSrc-1; i>0; i--){
3338 p->a[i].jointype = p->a[i-1].jointype; 3765 p->a[i].jointype = p->a[i-1].jointype;
3339 } 3766 }
3340 p->a[0].jointype = 0; 3767 p->a[0].jointype = 0;
3341 } 3768 }
3342 } 3769 }
3343 3770
3344 /* 3771 /*
3345 ** Begin a transaction 3772 ** Begin a transaction
3346 */ 3773 */
(...skipping 17 matching lines...) Expand all
3364 sqlite3VdbeUsesBtree(v, i); 3791 sqlite3VdbeUsesBtree(v, i);
3365 } 3792 }
3366 } 3793 }
3367 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); 3794 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
3368 } 3795 }
3369 3796
3370 /* 3797 /*
3371 ** Commit a transaction 3798 ** Commit a transaction
3372 */ 3799 */
3373 void sqlite3CommitTransaction(Parse *pParse){ 3800 void sqlite3CommitTransaction(Parse *pParse){
3374 sqlite3 *db;
3375 Vdbe *v; 3801 Vdbe *v;
3376 3802
3377 assert( pParse!=0 ); 3803 assert( pParse!=0 );
3378 db = pParse->db; 3804 assert( pParse->db!=0 );
3379 assert( db!=0 );
3380 /* if( db->aDb[0].pBt==0 ) return; */
3381 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ 3805 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3382 return; 3806 return;
3383 } 3807 }
3384 v = sqlite3GetVdbe(pParse); 3808 v = sqlite3GetVdbe(pParse);
3385 if( v ){ 3809 if( v ){
3386 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); 3810 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
3387 } 3811 }
3388 } 3812 }
3389 3813
3390 /* 3814 /*
3391 ** Rollback a transaction 3815 ** Rollback a transaction
3392 */ 3816 */
3393 void sqlite3RollbackTransaction(Parse *pParse){ 3817 void sqlite3RollbackTransaction(Parse *pParse){
3394 sqlite3 *db;
3395 Vdbe *v; 3818 Vdbe *v;
3396 3819
3397 assert( pParse!=0 ); 3820 assert( pParse!=0 );
3398 db = pParse->db; 3821 assert( pParse->db!=0 );
3399 assert( db!=0 );
3400 /* if( db->aDb[0].pBt==0 ) return; */
3401 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ 3822 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3402 return; 3823 return;
3403 } 3824 }
3404 v = sqlite3GetVdbe(pParse); 3825 v = sqlite3GetVdbe(pParse);
3405 if( v ){ 3826 if( v ){
3406 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 3827 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
3407 } 3828 }
3408 } 3829 }
3409 3830
3410 /* 3831 /*
(...skipping 25 matching lines...) Expand all
3436 if( db->aDb[1].pBt==0 && !pParse->explain ){ 3857 if( db->aDb[1].pBt==0 && !pParse->explain ){
3437 int rc; 3858 int rc;
3438 Btree *pBt; 3859 Btree *pBt;
3439 static const int flags = 3860 static const int flags =
3440 SQLITE_OPEN_READWRITE | 3861 SQLITE_OPEN_READWRITE |
3441 SQLITE_OPEN_CREATE | 3862 SQLITE_OPEN_CREATE |
3442 SQLITE_OPEN_EXCLUSIVE | 3863 SQLITE_OPEN_EXCLUSIVE |
3443 SQLITE_OPEN_DELETEONCLOSE | 3864 SQLITE_OPEN_DELETEONCLOSE |
3444 SQLITE_OPEN_TEMP_DB; 3865 SQLITE_OPEN_TEMP_DB;
3445 3866
3446 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags); 3867 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
3447 if( rc!=SQLITE_OK ){ 3868 if( rc!=SQLITE_OK ){
3448 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 3869 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3449 "file for storing temporary tables"); 3870 "file for storing temporary tables");
3450 pParse->rc = rc; 3871 pParse->rc = rc;
3451 return 1; 3872 return 1;
3452 } 3873 }
3453 db->aDb[1].pBt = pBt; 3874 db->aDb[1].pBt = pBt;
3454 assert( db->aDb[1].pSchema ); 3875 assert( db->aDb[1].pSchema );
3455 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ 3876 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3456 db->mallocFailed = 1; 3877 db->mallocFailed = 1;
3457 return 1; 3878 return 1;
3458 } 3879 }
3459 } 3880 }
3460 return 0; 3881 return 0;
3461 } 3882 }
3462 3883
3463 /* 3884 /*
3464 ** Generate VDBE code that will verify the schema cookie and start 3885 ** Record the fact that the schema cookie will need to be verified
3465 ** a read-transaction for all named database files. 3886 ** for database iDb. The code to actually verify the schema cookie
3466 ** 3887 ** will occur at the end of the top-level VDBE and will be generated
3467 ** It is important that all schema cookies be verified and all 3888 ** later, by sqlite3FinishCoding().
3468 ** read transactions be started before anything else happens in
3469 ** the VDBE program. But this routine can be called after much other
3470 ** code has been generated. So here is what we do:
3471 **
3472 ** The first time this routine is called, we code an OP_Goto that
3473 ** will jump to a subroutine at the end of the program. Then we
3474 ** record every database that needs its schema verified in the
3475 ** pParse->cookieMask field. Later, after all other code has been
3476 ** generated, the subroutine that does the cookie verifications and
3477 ** starts the transactions will be coded and the OP_Goto P2 value
3478 ** will be made to point to that subroutine. The generation of the
3479 ** cookie verification subroutine code happens in sqlite3FinishCoding().
3480 **
3481 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3482 ** schema on any databases. This can be used to position the OP_Goto
3483 ** early in the code, before we know if any database tables will be used.
3484 */ 3889 */
3485 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 3890 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3486 Parse *pToplevel = sqlite3ParseToplevel(pParse); 3891 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3892 sqlite3 *db = pToplevel->db;
3487 3893
3488 if( pToplevel->cookieGoto==0 ){ 3894 assert( iDb>=0 && iDb<db->nDb );
3489 Vdbe *v = sqlite3GetVdbe(pToplevel); 3895 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3490 if( v==0 ) return; /* This only happens if there was a prior error */ 3896 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3491 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; 3897 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3492 } 3898 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3493 if( iDb>=0 ){ 3899 DbMaskSet(pToplevel->cookieMask, iDb);
3494 sqlite3 *db = pToplevel->db; 3900 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3495 yDbMask mask; 3901 if( !OMIT_TEMPDB && iDb==1 ){
3496 3902 sqlite3OpenTempDatabase(pToplevel);
3497 assert( iDb<db->nDb );
3498 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3499 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3500 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3501 mask = ((yDbMask)1)<<iDb;
3502 if( (pToplevel->cookieMask & mask)==0 ){
3503 pToplevel->cookieMask |= mask;
3504 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3505 if( !OMIT_TEMPDB && iDb==1 ){
3506 sqlite3OpenTempDatabase(pToplevel);
3507 }
3508 } 3903 }
3509 } 3904 }
3510 } 3905 }
3511 3906
3512 /* 3907 /*
3513 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 3908 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3514 ** attached database. Otherwise, invoke it for the database named zDb only. 3909 ** attached database. Otherwise, invoke it for the database named zDb only.
3515 */ 3910 */
3516 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 3911 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3517 sqlite3 *db = pParse->db; 3912 sqlite3 *db = pParse->db;
(...skipping 15 matching lines...) Expand all
3533 ** is set if the setStatement parameter is true. A checkpoint should 3928 ** is set if the setStatement parameter is true. A checkpoint should
3534 ** be set for operations that might fail (due to a constraint) part of 3929 ** be set for operations that might fail (due to a constraint) part of
3535 ** the way through and which will need to undo some writes without having to 3930 ** the way through and which will need to undo some writes without having to
3536 ** rollback the whole transaction. For operations where all constraints 3931 ** rollback the whole transaction. For operations where all constraints
3537 ** can be checked before any changes are made to the database, it is never 3932 ** can be checked before any changes are made to the database, it is never
3538 ** necessary to undo a write and the checkpoint should not be set. 3933 ** necessary to undo a write and the checkpoint should not be set.
3539 */ 3934 */
3540 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 3935 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3541 Parse *pToplevel = sqlite3ParseToplevel(pParse); 3936 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3542 sqlite3CodeVerifySchema(pParse, iDb); 3937 sqlite3CodeVerifySchema(pParse, iDb);
3543 pToplevel->writeMask |= ((yDbMask)1)<<iDb; 3938 DbMaskSet(pToplevel->writeMask, iDb);
3544 pToplevel->isMultiWrite |= setStatement; 3939 pToplevel->isMultiWrite |= setStatement;
3545 } 3940 }
3546 3941
3547 /* 3942 /*
3548 ** Indicate that the statement currently under construction might write 3943 ** Indicate that the statement currently under construction might write
3549 ** more than one entry (example: deleting one row then inserting another, 3944 ** more than one entry (example: deleting one row then inserting another,
3550 ** inserting multiple rows in a table, or inserting a row and index entries.) 3945 ** inserting multiple rows in a table, or inserting a row and index entries.)
3551 ** If an abort occurs after some of these writes have completed, then it will 3946 ** If an abort occurs after some of these writes have completed, then it will
3552 ** be necessary to undo the completed writes. 3947 ** be necessary to undo the completed writes.
3553 */ 3948 */
(...skipping 21 matching lines...) Expand all
3575 void sqlite3MayAbort(Parse *pParse){ 3970 void sqlite3MayAbort(Parse *pParse){
3576 Parse *pToplevel = sqlite3ParseToplevel(pParse); 3971 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3577 pToplevel->mayAbort = 1; 3972 pToplevel->mayAbort = 1;
3578 } 3973 }
3579 3974
3580 /* 3975 /*
3581 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 3976 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3582 ** error. The onError parameter determines which (if any) of the statement 3977 ** error. The onError parameter determines which (if any) of the statement
3583 ** and/or current transaction is rolled back. 3978 ** and/or current transaction is rolled back.
3584 */ 3979 */
3585 void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){ 3980 void sqlite3HaltConstraint(
3981 Parse *pParse, /* Parsing context */
3982 int errCode, /* extended error code */
3983 int onError, /* Constraint type */
3984 char *p4, /* Error message */
3985 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3986 u8 p5Errmsg /* P5_ErrMsg type */
3987 ){
3586 Vdbe *v = sqlite3GetVdbe(pParse); 3988 Vdbe *v = sqlite3GetVdbe(pParse);
3989 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
3587 if( onError==OE_Abort ){ 3990 if( onError==OE_Abort ){
3588 sqlite3MayAbort(pParse); 3991 sqlite3MayAbort(pParse);
3589 } 3992 }
3590 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type); 3993 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
3994 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3591 } 3995 }
3592 3996
3593 /* 3997 /*
3998 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3999 */
4000 void sqlite3UniqueConstraint(
4001 Parse *pParse, /* Parsing context */
4002 int onError, /* Constraint type */
4003 Index *pIdx /* The index that triggers the constraint */
4004 ){
4005 char *zErr;
4006 int j;
4007 StrAccum errMsg;
4008 Table *pTab = pIdx->pTable;
4009
4010 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
4011 errMsg.db = pParse->db;
4012 for(j=0; j<pIdx->nKeyCol; j++){
4013 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4014 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
4015 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
4016 sqlite3StrAccumAppend(&errMsg, ".", 1);
4017 sqlite3StrAccumAppendAll(&errMsg, zCol);
4018 }
4019 zErr = sqlite3StrAccumFinish(&errMsg);
4020 sqlite3HaltConstraint(pParse,
4021 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4022 : SQLITE_CONSTRAINT_UNIQUE,
4023 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
4024 }
4025
4026
4027 /*
4028 ** Code an OP_Halt due to non-unique rowid.
4029 */
4030 void sqlite3RowidConstraint(
4031 Parse *pParse, /* Parsing context */
4032 int onError, /* Conflict resolution algorithm */
4033 Table *pTab /* The table with the non-unique rowid */
4034 ){
4035 char *zMsg;
4036 int rc;
4037 if( pTab->iPKey>=0 ){
4038 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4039 pTab->aCol[pTab->iPKey].zName);
4040 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4041 }else{
4042 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4043 rc = SQLITE_CONSTRAINT_ROWID;
4044 }
4045 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4046 P5_ConstraintUnique);
4047 }
4048
4049 /*
3594 ** Check to see if pIndex uses the collating sequence pColl. Return 4050 ** Check to see if pIndex uses the collating sequence pColl. Return
3595 ** true if it does and false if it does not. 4051 ** true if it does and false if it does not.
3596 */ 4052 */
3597 #ifndef SQLITE_OMIT_REINDEX 4053 #ifndef SQLITE_OMIT_REINDEX
3598 static int collationMatch(const char *zColl, Index *pIndex){ 4054 static int collationMatch(const char *zColl, Index *pIndex){
3599 int i; 4055 int i;
3600 assert( zColl!=0 ); 4056 assert( zColl!=0 );
3601 for(i=0; i<pIndex->nColumn; i++){ 4057 for(i=0; i<pIndex->nColumn; i++){
3602 const char *z = pIndex->azColl[i]; 4058 const char *z = pIndex->azColl[i];
3603 assert( z!=0 ); 4059 assert( z!=0 || pIndex->aiColumn[i]<0 );
3604 if( 0==sqlite3StrICmp(z, zColl) ){ 4060 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
3605 return 1; 4061 return 1;
3606 } 4062 }
3607 } 4063 }
3608 return 0; 4064 return 0;
3609 } 4065 }
3610 #endif 4066 #endif
3611 4067
3612 /* 4068 /*
3613 ** Recompute all indices of pTab that use the collating sequence pColl. 4069 ** Recompute all indices of pTab that use the collating sequence pColl.
3614 ** If pColl==0 then recompute all indices of pTab. 4070 ** If pColl==0 then recompute all indices of pTab.
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
3713 if( pIndex ){ 4169 if( pIndex ){
3714 sqlite3BeginWriteOperation(pParse, 0, iDb); 4170 sqlite3BeginWriteOperation(pParse, 0, iDb);
3715 sqlite3RefillIndex(pParse, pIndex, -1); 4171 sqlite3RefillIndex(pParse, pIndex, -1);
3716 return; 4172 return;
3717 } 4173 }
3718 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 4174 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3719 } 4175 }
3720 #endif 4176 #endif
3721 4177
3722 /* 4178 /*
3723 ** Return a dynamicly allocated KeyInfo structure that can be used 4179 ** Return a KeyInfo structure that is appropriate for the given Index.
3724 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3725 ** 4180 **
3726 ** If successful, a pointer to the new structure is returned. In this case 4181 ** The KeyInfo structure for an index is cached in the Index object.
3727 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 4182 ** So there might be multiple references to the returned pointer. The
3728 ** pointer. If an error occurs (out of memory or missing collation 4183 ** caller should not try to modify the KeyInfo object.
3729 ** sequence), NULL is returned and the state of pParse updated to reflect 4184 **
3730 ** the error. 4185 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4186 ** when it has finished using it.
3731 */ 4187 */
3732 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ 4188 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
3733 int i; 4189 if( pParse->nErr ) return 0;
3734 int nCol = pIdx->nColumn; 4190 #ifndef SQLITE_OMIT_SHARED_CACHE
3735 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol; 4191 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4192 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4193 pIdx->pKeyInfo = 0;
4194 }
4195 #endif
4196 if( pIdx->pKeyInfo==0 ){
4197 int i;
4198 int nCol = pIdx->nColumn;
4199 int nKey = pIdx->nKeyCol;
4200 KeyInfo *pKey;
4201 if( pIdx->uniqNotNull ){
4202 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4203 }else{
4204 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4205 }
4206 if( pKey ){
4207 assert( sqlite3KeyInfoIsWriteable(pKey) );
4208 for(i=0; i<nCol; i++){
4209 char *zColl = pIdx->azColl[i];
4210 assert( zColl!=0 );
4211 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4212 sqlite3LocateCollSeq(pParse, zColl);
4213 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4214 }
4215 if( pParse->nErr ){
4216 sqlite3KeyInfoUnref(pKey);
4217 }else{
4218 pIdx->pKeyInfo = pKey;
4219 }
4220 }
4221 }
4222 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
4223 }
4224
4225 #ifndef SQLITE_OMIT_CTE
4226 /*
4227 ** This routine is invoked once per CTE by the parser while parsing a
4228 ** WITH clause.
4229 */
4230 With *sqlite3WithAdd(
4231 Parse *pParse, /* Parsing context */
4232 With *pWith, /* Existing WITH clause, or NULL */
4233 Token *pName, /* Name of the common-table */
4234 ExprList *pArglist, /* Optional column name list for the table */
4235 Select *pQuery /* Query used to initialize the table */
4236 ){
3736 sqlite3 *db = pParse->db; 4237 sqlite3 *db = pParse->db;
3737 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes); 4238 With *pNew;
4239 char *zName;
3738 4240
3739 if( pKey ){ 4241 /* Check that the CTE name is unique within this WITH clause. If
3740 pKey->db = pParse->db; 4242 ** not, store an error in the Parse structure. */
3741 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]); 4243 zName = sqlite3NameFromToken(pParse->db, pName);
3742 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) ); 4244 if( zName && pWith ){
3743 for(i=0; i<nCol; i++){ 4245 int i;
3744 char *zColl = pIdx->azColl[i]; 4246 for(i=0; i<pWith->nCte; i++){
3745 assert( zColl ); 4247 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
3746 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl); 4248 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
3747 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 4249 }
3748 } 4250 }
3749 pKey->nField = (u16)nCol;
3750 } 4251 }
3751 4252
3752 if( pParse->nErr ){ 4253 if( pWith ){
3753 sqlite3DbFree(db, pKey); 4254 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
3754 pKey = 0; 4255 pNew = sqlite3DbRealloc(db, pWith, nByte);
4256 }else{
4257 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
3755 } 4258 }
3756 return pKey; 4259 assert( zName!=0 || pNew==0 );
4260 assert( db->mallocFailed==0 || pNew==0 );
4261
4262 if( pNew==0 ){
4263 sqlite3ExprListDelete(db, pArglist);
4264 sqlite3SelectDelete(db, pQuery);
4265 sqlite3DbFree(db, zName);
4266 pNew = pWith;
4267 }else{
4268 pNew->a[pNew->nCte].pSelect = pQuery;
4269 pNew->a[pNew->nCte].pCols = pArglist;
4270 pNew->a[pNew->nCte].zName = zName;
4271 pNew->a[pNew->nCte].zErr = 0;
4272 pNew->nCte++;
4273 }
4274
4275 return pNew;
3757 } 4276 }
4277
4278 /*
4279 ** Free the contents of the With object passed as the second argument.
4280 */
4281 void sqlite3WithDelete(sqlite3 *db, With *pWith){
4282 if( pWith ){
4283 int i;
4284 for(i=0; i<pWith->nCte; i++){
4285 struct Cte *pCte = &pWith->a[i];
4286 sqlite3ExprListDelete(db, pCte->pCols);
4287 sqlite3SelectDelete(db, pCte->pSelect);
4288 sqlite3DbFree(db, pCte->zName);
4289 }
4290 sqlite3DbFree(db, pWith);
4291 }
4292 }
4293 #endif /* !defined(SQLITE_OMIT_CTE) */
OLDNEW
« no previous file with comments | « third_party/sqlite/sqlite-src-3080704/src/btreeInt.h ('k') | third_party/sqlite/sqlite-src-3080704/src/callback.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698