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