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

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

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

Powered by Google App Engine
This is Rietveld 408576698