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