blob: 8615fe76d4d61762cb43daee11021ae7f3be4c7c [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhb19a2bc2001-09-16 00:13:26 +000012** 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:
drh75897232000-05-29 14:26:00 +000015**
drhbed86902000-06-02 13:27:59 +000016** CREATE TABLE
17** DROP TABLE
18** CREATE INDEX
19** DROP INDEX
drh832508b2002-03-02 17:04:07 +000020** creating ID lists
drhb19a2bc2001-09-16 00:13:26 +000021** BEGIN TRANSACTION
22** COMMIT
23** ROLLBACK
drh75897232000-05-29 14:26:00 +000024*/
25#include "sqliteInt.h"
26
27/*
drhe0bc4042002-06-25 01:09:11 +000028** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000029** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000030*/
danielk19774adee202004-05-08 08:23:19 +000031void sqlite3BeginParse(Parse *pParse, int explainFlag){
drh1bd10f82008-12-10 21:19:56 +000032 pParse->explain = (u8)explainFlag;
drh7c972de2003-09-06 22:18:07 +000033 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000034}
35
danielk1977c00da102006-01-07 13:21:04 +000036#ifndef SQLITE_OMIT_SHARED_CACHE
37/*
38** The TableLock structure is only used by the sqlite3TableLock() and
39** codeTableLocks() functions.
40*/
41struct TableLock {
drhd698bc12006-03-23 23:33:26 +000042 int iDb; /* The database containing the table to be locked */
43 int iTab; /* The root page of the table to be locked */
44 u8 isWriteLock; /* True for write lock. False for a read lock */
45 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000046};
47
48/*
drhd698bc12006-03-23 23:33:26 +000049** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000050**
drhd698bc12006-03-23 23:33:26 +000051** The table to be locked has root page iTab and is found in database iDb.
52** A read or a write lock can be taken depending on isWritelock.
53**
54** This routine just records the fact that the lock is desired. The
55** code to make the lock occur is generated by a later call to
56** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000057*/
58void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000059 Parse *pParse, /* Parsing context */
60 int iDb, /* Index of the database containing the table to lock */
61 int iTab, /* Root page number of the table to be locked */
62 u8 isWriteLock, /* True for a write lock */
63 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000064){
dan65a7cd12009-09-01 12:16:01 +000065 Parse *pToplevel = sqlite3ParseToplevel(pParse);
danielk1977c00da102006-01-07 13:21:04 +000066 int i;
67 int nBytes;
68 TableLock *p;
drh8af73d42009-05-13 22:58:28 +000069 assert( iDb>=0 );
dan165921a2009-08-28 18:53:45 +000070
dan65a7cd12009-09-01 12:16:01 +000071 for(i=0; i<pToplevel->nTableLock; i++){
72 p = &pToplevel->aTableLock[i];
danielk1977c00da102006-01-07 13:21:04 +000073 if( p->iDb==iDb && p->iTab==iTab ){
74 p->isWriteLock = (p->isWriteLock || isWriteLock);
75 return;
76 }
77 }
78
dan65a7cd12009-09-01 12:16:01 +000079 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80 pToplevel->aTableLock =
81 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82 if( pToplevel->aTableLock ){
83 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
danielk1977c00da102006-01-07 13:21:04 +000084 p->iDb = iDb;
85 p->iTab = iTab;
86 p->isWriteLock = isWriteLock;
87 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000088 }else{
dan65a7cd12009-09-01 12:16:01 +000089 pToplevel->nTableLock = 0;
90 pToplevel->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000091 }
92}
93
94/*
95** Code an OP_TableLock instruction for each table locked by the
96** statement (configured by calls to sqlite3TableLock()).
97*/
98static void codeTableLocks(Parse *pParse){
99 int i;
100 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000101
drh04491712009-05-13 17:21:13 +0000102 pVdbe = sqlite3GetVdbe(pParse);
103 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
danielk1977c00da102006-01-07 13:21:04 +0000104
105 for(i=0; i<pParse->nTableLock; i++){
106 TableLock *p = &pParse->aTableLock[i];
107 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
109 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000110 }
111}
112#else
113 #define codeTableLocks(x)
114#endif
115
drhe0bc4042002-06-25 01:09:11 +0000116/*
drh75897232000-05-29 14:26:00 +0000117** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000118** parsed and a VDBE program to execute that statement has been
119** prepared. This routine puts the finishing touches on the
120** VDBE program and resets the pParse structure for the next
121** parse.
drh75897232000-05-29 14:26:00 +0000122**
123** Note that if an error occurred, it might be the case that
124** no VDBE code was generated.
125*/
drh80242052004-06-09 00:48:12 +0000126void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000127 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000128 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000129
danf78baaf2012-12-06 19:37:22 +0000130 assert( pParse->pToplevel==0 );
drh17435752007-08-16 04:30:38 +0000131 db = pParse->db;
132 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000133 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000134 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000135
drh80242052004-06-09 00:48:12 +0000136 /* Begin by generating some termination code at the end of the
137 ** vdbe program
138 */
drh80242052004-06-09 00:48:12 +0000139 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000140 assert( !pParse->isMultiWrite
141 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000142 if( v ){
drh61019c72014-01-04 16:49:02 +0000143 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
drh66a51672008-01-03 00:01:23 +0000144 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000145
146 /* The cookie mask contains one bit for each database file open.
147 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
148 ** set for each database that is used. Generate code to start a
149 ** transaction on each used database and to verify the schema cookie
150 ** on each used database.
151 */
drhe0e261a2014-02-08 04:24:37 +0000152 if( db->mallocFailed==0 && (pParse->cookieMask || pParse->pConstExpr) ){
drh64123582011-04-02 20:01:02 +0000153 yDbMask mask;
drhaceb31b2014-02-08 01:40:27 +0000154 int iDb, i;
155 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
156 sqlite3VdbeJumpHere(v, 0);
drh80242052004-06-09 00:48:12 +0000157 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
158 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000159 sqlite3VdbeUsesBtree(v, iDb);
drhb22f7c82014-02-06 23:56:27 +0000160 sqlite3VdbeAddOp4Int(v,
161 OP_Transaction, /* Opcode */
162 iDb, /* P1 */
163 (mask & pParse->writeMask)!=0, /* P2 */
164 pParse->cookieValue[iDb], /* P3 */
165 db->aDb[iDb].pSchema->iGeneration /* P4 */
166 );
167 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
drh80242052004-06-09 00:48:12 +0000168 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000169#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000170 for(i=0; i<pParse->nVtabLock; i++){
171 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
172 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000173 }
drhf30a9692013-11-15 01:10:18 +0000174 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000175#endif
danielk1977c00da102006-01-07 13:21:04 +0000176
177 /* Once all the cookies have been verified and transactions opened,
178 ** obtain the required table-locks. This is a no-op unless the
179 ** shared-cache feature is enabled.
180 */
181 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000182
183 /* Initialize any AUTOINCREMENT data structures required.
184 */
185 sqlite3AutoincrementBegin(pParse);
186
drhf30a9692013-11-15 01:10:18 +0000187 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000188 if( pParse->pConstExpr ){
189 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000190 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000191 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000192 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000193 }
194 }
195
drh0b9f50d2009-06-23 20:28:53 +0000196 /* Finally, jump back to the beginning of the executable code. */
drhaceb31b2014-02-08 01:40:27 +0000197 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
drh80242052004-06-09 00:48:12 +0000198 }
drh71c697e2004-08-08 23:39:19 +0000199 }
200
drh3f7d4e42004-07-24 14:35:58 +0000201
drh80242052004-06-09 00:48:12 +0000202 /* Get the VDBE program ready for execution
203 */
drh04491712009-05-13 17:21:13 +0000204 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000205 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000206 /* A minimum of one cursor is required if autoincrement is used
207 * See ticket [a696379c1f08866] */
208 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000209 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000210 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000211 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000212 }else{
drh483750b2003-01-29 18:46:51 +0000213 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000214 }
drha226d052002-09-25 19:04:07 +0000215 pParse->nTab = 0;
216 pParse->nMem = 0;
217 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000218 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000219 pParse->cookieMask = 0;
drh75897232000-05-29 14:26:00 +0000220}
221
222/*
drh205f48e2004-11-05 00:43:11 +0000223** Run the parser and code generator recursively in order to generate
224** code for the SQL statement given onto the end of the pParse context
225** currently under construction. When the parser is run recursively
226** this way, the final OP_Halt is not appended and other initialization
227** and finalization steps are omitted because those are handling by the
228** outermost parser.
229**
230** Not everything is nestable. This facility is designed to permit
231** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000232** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000233*/
234void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
235 va_list ap;
236 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000237 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000238 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000239# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
240 char saveBuf[SAVE_SZ];
241
drh205f48e2004-11-05 00:43:11 +0000242 if( pParse->nErr ) return;
243 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
244 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000245 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000246 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000247 if( zSql==0 ){
248 return; /* A malloc must have failed */
249 }
drh205f48e2004-11-05 00:43:11 +0000250 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000251 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
252 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000253 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000254 sqlite3DbFree(db, zErrMsg);
255 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000256 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000257 pParse->nested--;
258}
259
260/*
danielk19778a414492004-06-29 08:59:35 +0000261** Locate the in-memory structure that describes a particular database
262** table given the name of that table and (optionally) the name of the
263** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000264**
danielk19778a414492004-06-29 08:59:35 +0000265** If zDatabase is 0, all databases are searched for the table and the
266** first matching table is returned. (No checking for duplicate table
267** names is done.) The search order is TEMP first, then MAIN, then any
268** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000269**
danielk19774adee202004-05-08 08:23:19 +0000270** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000271*/
drh9bb575f2004-09-06 17:24:11 +0000272Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000273 Table *p = 0;
274 int i;
drh0a687d12008-07-08 14:52:07 +0000275 int nName;
drh645f63e2004-06-22 13:22:40 +0000276 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000277 nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000278 /* All mutexes are required for schema access. Make sure we hold them. */
279 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000280 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000281 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000282 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000283 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh0a687d12008-07-08 14:52:07 +0000284 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000285 if( p ) break;
286 }
drh74e24cd2002-01-09 03:19:59 +0000287 return p;
drh75897232000-05-29 14:26:00 +0000288}
289
290/*
danielk19778a414492004-06-29 08:59:35 +0000291** Locate the in-memory structure that describes a particular database
292** table given the name of that table and (optionally) the name of the
293** database containing the table. Return NULL if not found. Also leave an
294** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000295**
danielk19778a414492004-06-29 08:59:35 +0000296** The difference between this routine and sqlite3FindTable() is that this
297** routine leaves an error message in pParse->zErrMsg where
298** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000299*/
drhca424112008-01-25 15:04:48 +0000300Table *sqlite3LocateTable(
301 Parse *pParse, /* context in which to report errors */
302 int isView, /* True if looking for a VIEW rather than a TABLE */
303 const char *zName, /* Name of the table we are looking for */
304 const char *zDbase /* Name of the database. Might be NULL */
305){
drha69d9162003-04-17 22:57:53 +0000306 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000307
danielk19778a414492004-06-29 08:59:35 +0000308 /* Read the database schema. If an error occurs, leave an error message
309 ** and code in pParse and return NULL. */
310 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
311 return 0;
312 }
313
danielk19774adee202004-05-08 08:23:19 +0000314 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000315 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000316 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000317 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000318 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000319 }else{
drhca424112008-01-25 15:04:48 +0000320 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000321 }
drha6ecd332004-06-10 00:29:09 +0000322 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000323 }
324 return p;
325}
326
327/*
dan41fb5cd2012-10-04 19:33:00 +0000328** Locate the table identified by *p.
329**
330** This is a wrapper around sqlite3LocateTable(). The difference between
331** sqlite3LocateTable() and this function is that this function restricts
332** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
333** non-NULL if it is part of a view or trigger program definition. See
334** sqlite3FixSrcList() for details.
335*/
336Table *sqlite3LocateTableItem(
337 Parse *pParse,
338 int isView,
339 struct SrcList_item *p
340){
341 const char *zDb;
342 assert( p->pSchema==0 || p->zDatabase==0 );
343 if( p->pSchema ){
344 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
345 zDb = pParse->db->aDb[iDb].zName;
346 }else{
347 zDb = p->zDatabase;
348 }
349 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
350}
351
352/*
drha69d9162003-04-17 22:57:53 +0000353** Locate the in-memory structure that describes
354** a particular index given the name of that index
355** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000356** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000357**
358** If zDatabase is 0, all databases are searched for the
359** table and the first matching index is returned. (No checking
360** for duplicate index names is done.) The search order is
361** TEMP first, then MAIN, then any auxiliary databases added
362** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000363*/
drh9bb575f2004-09-06 17:24:11 +0000364Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000365 Index *p = 0;
366 int i;
drhdee0e402009-05-03 20:23:53 +0000367 int nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000368 /* All mutexes are required for schema access. Make sure we hold them. */
369 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000370 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000371 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000372 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000373 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000374 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000375 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh04491712009-05-13 17:21:13 +0000376 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000377 if( p ) break;
378 }
drh74e24cd2002-01-09 03:19:59 +0000379 return p;
drh75897232000-05-29 14:26:00 +0000380}
381
382/*
drh956bc922004-07-24 17:38:29 +0000383** Reclaim the memory used by an index
384*/
dan1feeaed2010-07-23 15:41:47 +0000385static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000386#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000387 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000388#endif
drh2ec2fb22013-11-06 19:59:23 +0000389 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
drh1fe05372013-07-31 18:12:26 +0000390 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000391 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000392 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh633e6d52008-07-28 19:34:53 +0000393 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000394}
395
396/*
drhc96d8532005-05-03 12:30:33 +0000397** For the index called zIdxName which is found in the database iDb,
398** unlike that index from its Table then remove the index from
399** the index hash table and free all memory structures associated
400** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000401*/
drh9bb575f2004-09-06 17:24:11 +0000402void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000403 Index *pIndex;
404 int len;
drh21206082011-04-04 18:22:02 +0000405 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000406
drh21206082011-04-04 18:22:02 +0000407 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
408 pHash = &db->aDb[iDb].pSchema->idxHash;
drhdee0e402009-05-03 20:23:53 +0000409 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000410 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh22645842011-03-24 01:34:03 +0000411 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000412 if( pIndex->pTable->pIndex==pIndex ){
413 pIndex->pTable->pIndex = pIndex->pNext;
414 }else{
415 Index *p;
drh04491712009-05-13 17:21:13 +0000416 /* Justification of ALWAYS(); The index must be on the list of
417 ** indices. */
418 p = pIndex->pTable->pIndex;
419 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
420 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000421 p->pNext = pIndex->pNext;
422 }
drh5e00f6c2001-09-13 13:46:56 +0000423 }
dan1feeaed2010-07-23 15:41:47 +0000424 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000425 }
drh956bc922004-07-24 17:38:29 +0000426 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000427}
428
429/*
drh81028a42012-05-15 18:28:27 +0000430** Look through the list of open database files in db->aDb[] and if
431** any have been closed, remove them from the list. Reallocate the
432** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000433**
drh81028a42012-05-15 18:28:27 +0000434** Entry 0 (the "main" database) and entry 1 (the "temp" database)
435** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000436*/
drh81028a42012-05-15 18:28:27 +0000437void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000438 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000439 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000440 struct Db *pDb = &db->aDb[i];
441 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000442 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000443 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000444 continue;
445 }
446 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000447 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000448 }
drh8bf8dc92003-05-17 17:35:10 +0000449 j++;
drh1c2d8412003-03-31 00:30:47 +0000450 }
451 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
452 db->nDb = j;
453 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
454 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000455 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000456 db->aDb = db->aDbStatic;
457 }
drhe0bc4042002-06-25 01:09:11 +0000458}
459
460/*
drh81028a42012-05-15 18:28:27 +0000461** Reset the schema for the database at index iDb. Also reset the
462** TEMP schema.
463*/
464void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000465 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000466 assert( iDb<db->nDb );
467
468 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000469 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000470 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
471 assert( pDb->pSchema!=0 );
472 sqlite3SchemaClear(pDb->pSchema);
473
474 /* If any database other than TEMP is reset, then also reset TEMP
475 ** since TEMP might be holding triggers that reference tables in the
476 ** other database.
477 */
478 if( iDb!=1 ){
479 pDb = &db->aDb[1];
480 assert( pDb->pSchema!=0 );
481 sqlite3SchemaClear(pDb->pSchema);
482 }
483 return;
484}
485
486/*
487** Erase all schema information from all attached databases (including
488** "main" and "temp") for a single database connection.
489*/
490void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
491 int i;
492 sqlite3BtreeEnterAll(db);
493 for(i=0; i<db->nDb; i++){
494 Db *pDb = &db->aDb[i];
495 if( pDb->pSchema ){
496 sqlite3SchemaClear(pDb->pSchema);
497 }
498 }
499 db->flags &= ~SQLITE_InternChanges;
500 sqlite3VtabUnlockList(db);
501 sqlite3BtreeLeaveAll(db);
502 sqlite3CollapseDatabaseArray(db);
503}
504
505/*
drhe0bc4042002-06-25 01:09:11 +0000506** This routine is called when a commit occurs.
507*/
drh9bb575f2004-09-06 17:24:11 +0000508void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000509 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000510}
511
512/*
dand46def72010-07-24 11:28:28 +0000513** Delete memory allocated for the column names of a table or view (the
514** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000515*/
dand46def72010-07-24 11:28:28 +0000516static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000517 int i;
518 Column *pCol;
519 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000520 if( (pCol = pTable->aCol)!=0 ){
521 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000522 sqlite3DbFree(db, pCol->zName);
523 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000524 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000525 sqlite3DbFree(db, pCol->zType);
526 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000527 }
drh633e6d52008-07-28 19:34:53 +0000528 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000529 }
drh956bc922004-07-24 17:38:29 +0000530}
531
532/*
drh75897232000-05-29 14:26:00 +0000533** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000534** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000535**
536** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000537** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000538** memory structures of the indices and foreign keys associated with
539** the table.
drh29ddd3a2012-05-15 12:49:32 +0000540**
541** The db parameter is optional. It is needed if the Table object
542** contains lookaside memory. (Table objects in the schema do not use
543** lookaside memory, but some ephemeral Table objects do.) Or the
544** db parameter can be used with db->pnBytesFreed to measure the memory
545** used by the Table object.
drh75897232000-05-29 14:26:00 +0000546*/
dan1feeaed2010-07-23 15:41:47 +0000547void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000548 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000549 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000550
dand46def72010-07-24 11:28:28 +0000551 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000552
drhed8a3bb2005-06-06 21:19:56 +0000553 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000554 if( !pTable ) return;
555 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000556
drh29ddd3a2012-05-15 12:49:32 +0000557 /* Record the number of outstanding lookaside allocations in schema Tables
558 ** prior to doing any free() operations. Since schema Tables do not use
559 ** lookaside, this number should not change. */
560 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
561 db->lookaside.nOut : 0 );
562
dand46def72010-07-24 11:28:28 +0000563 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000564 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
565 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000566 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000567 if( !db || db->pnBytesFreed==0 ){
568 char *zName = pIndex->zName;
569 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhf2f105d2012-08-20 15:53:54 +0000570 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
dand46def72010-07-24 11:28:28 +0000571 );
drh21206082011-04-04 18:22:02 +0000572 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000573 assert( pOld==pIndex || pOld==0 );
574 }
575 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000576 }
577
dan1da40a32009-09-19 17:00:31 +0000578 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000579 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000580
581 /* Delete the Table structure itself.
582 */
dand46def72010-07-24 11:28:28 +0000583 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000584 sqlite3DbFree(db, pTable->zName);
585 sqlite3DbFree(db, pTable->zColAff);
586 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000587#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000588 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000589#endif
drh078e4082010-07-28 19:17:51 +0000590#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000591 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000592#endif
drh633e6d52008-07-28 19:34:53 +0000593 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000594
595 /* Verify that no lookaside memory was used by schema tables */
596 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000597}
598
599/*
drh5edc3122001-09-13 21:53:09 +0000600** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000601** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000602*/
drh9bb575f2004-09-06 17:24:11 +0000603void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000604 Table *p;
drh956bc922004-07-24 17:38:29 +0000605 Db *pDb;
606
drhd229ca92002-01-09 13:30:41 +0000607 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000608 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000609 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000610 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000611 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000612 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000613 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000614 sqlite3Strlen30(zTabName),0);
dan1feeaed2010-07-23 15:41:47 +0000615 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000616 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000617}
618
619/*
drha99db3b2004-06-19 14:49:12 +0000620** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000621** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000622** is obtained from sqliteMalloc() and must be freed by the calling
623** function.
drh75897232000-05-29 14:26:00 +0000624**
drh24fb6272009-05-01 21:13:36 +0000625** Any quotation marks (ex: "name", 'name', [name], or `name`) that
626** surround the body of the token are removed.
627**
drhc96d8532005-05-03 12:30:33 +0000628** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000629** are not \000 terminated and are not persistent. The returned string
630** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000631*/
drh17435752007-08-16 04:30:38 +0000632char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000633 char *zName;
634 if( pName ){
drh17435752007-08-16 04:30:38 +0000635 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000636 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000637 }else{
638 zName = 0;
639 }
drh75897232000-05-29 14:26:00 +0000640 return zName;
641}
642
643/*
danielk1977cbb18d22004-05-28 11:37:27 +0000644** Open the sqlite_master table stored in database number iDb for
645** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000646*/
danielk1977c00da102006-01-07 13:21:04 +0000647void sqlite3OpenMasterTable(Parse *p, int iDb){
648 Vdbe *v = sqlite3GetVdbe(p);
649 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000650 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000651 if( p->nTab==0 ){
652 p->nTab = 1;
653 }
drhe0bc4042002-06-25 01:09:11 +0000654}
655
656/*
danielk197704103022009-02-03 16:51:24 +0000657** Parameter zName points to a nul-terminated buffer containing the name
658** of a database ("main", "temp" or the name of an attached db). This
659** function returns the index of the named database in db->aDb[], or
660** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000661*/
danielk197704103022009-02-03 16:51:24 +0000662int sqlite3FindDbName(sqlite3 *db, const char *zName){
663 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000664 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000665 Db *pDb;
666 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000667 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000668 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000669 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000670 break;
drh73c42a12004-11-20 18:13:10 +0000671 }
danielk1977cbb18d22004-05-28 11:37:27 +0000672 }
673 }
danielk1977576ec6b2005-01-21 11:55:25 +0000674 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000675}
676
danielk197704103022009-02-03 16:51:24 +0000677/*
678** The token *pName contains the name of a database (either "main" or
679** "temp" or the name of an attached db). This routine returns the
680** index of the named database in db->aDb[], or -1 if the named db
681** does not exist.
682*/
683int sqlite3FindDb(sqlite3 *db, Token *pName){
684 int i; /* Database number */
685 char *zName; /* Name we are searching for */
686 zName = sqlite3NameFromToken(db, pName);
687 i = sqlite3FindDbName(db, zName);
688 sqlite3DbFree(db, zName);
689 return i;
690}
691
drh0e3d7472004-06-19 17:33:07 +0000692/* The table or view or trigger name is passed to this routine via tokens
693** pName1 and pName2. If the table name was fully qualified, for example:
694**
695** CREATE TABLE xxx.yyy (...);
696**
697** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
698** the table name is not fully qualified, i.e.:
699**
700** CREATE TABLE yyy(...);
701**
702** Then pName1 is set to "yyy" and pName2 is "".
703**
704** This routine sets the *ppUnqual pointer to point at the token (pName1 or
705** pName2) that stores the unqualified table name. The index of the
706** database "xxx" is returned.
707*/
danielk1977ef2cb632004-05-29 02:37:19 +0000708int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000709 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000710 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000711 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
712 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000713){
drh0e3d7472004-06-19 17:33:07 +0000714 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000715 sqlite3 *db = pParse->db;
716
drhc4a64fa2009-05-11 20:53:28 +0000717 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000718 if( db->init.busy ) {
719 sqlite3ErrorMsg(pParse, "corrupt database");
720 pParse->nErr++;
721 return -1;
722 }
danielk1977cbb18d22004-05-28 11:37:27 +0000723 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000724 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000725 if( iDb<0 ){
726 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
727 pParse->nErr++;
728 return -1;
729 }
730 }else{
731 assert( db->init.iDb==0 || db->init.busy );
732 iDb = db->init.iDb;
733 *pUnqual = pName1;
734 }
735 return iDb;
736}
737
738/*
danielk1977d8123362004-06-12 09:25:12 +0000739** This routine is used to check if the UTF-8 string zName is a legal
740** unqualified name for a new schema object (table, index, view or
741** trigger). All names are legal except those that begin with the string
742** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
743** is reserved for internal use.
744*/
745int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000746 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000747 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000748 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000749 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
750 return SQLITE_ERROR;
751 }
752 return SQLITE_OK;
753}
754
755/*
drh44156282013-10-23 22:23:03 +0000756** Return the PRIMARY KEY index of a table
757*/
758Index *sqlite3PrimaryKeyIndex(Table *pTab){
759 Index *p;
760 for(p=pTab->pIndex; p && p->autoIndex!=2; p=p->pNext){}
761 return p;
762}
763
764/*
765** Return the column of index pIdx that corresponds to table
766** column iCol. Return -1 if not found.
767*/
768i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
769 int i;
770 for(i=0; i<pIdx->nColumn; i++){
771 if( iCol==pIdx->aiColumn[i] ) return i;
772 }
773 return -1;
774}
775
776/*
drh75897232000-05-29 14:26:00 +0000777** Begin constructing a new table representation in memory. This is
778** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000779** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000780** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000781** flag is true if the table should be stored in the auxiliary database
782** file instead of in the main database file. This is normally the case
783** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000784** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000785**
drhf57b3392001-10-08 13:22:32 +0000786** The new table record is initialized and put in pParse->pNewTable.
787** As more of the CREATE TABLE statement is parsed, additional action
788** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000789** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000790** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000791*/
danielk19774adee202004-05-08 08:23:19 +0000792void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000793 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000794 Token *pName1, /* First part of the name of the table or view */
795 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000796 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000797 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000798 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000799 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000800){
drh75897232000-05-29 14:26:00 +0000801 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000802 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000803 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000804 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000805 int iDb; /* Database number to create the table in */
806 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000807
danielk1977cbb18d22004-05-28 11:37:27 +0000808 /* The table or view name to create is passed to this routine via tokens
809 ** pName1 and pName2. If the table name was fully qualified, for example:
810 **
811 ** CREATE TABLE xxx.yyy (...);
812 **
813 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
814 ** the table name is not fully qualified, i.e.:
815 **
816 ** CREATE TABLE yyy(...);
817 **
818 ** Then pName1 is set to "yyy" and pName2 is "".
819 **
820 ** The call below sets the pName pointer to point at the token (pName1 or
821 ** pName2) that stores the unqualified table name. The variable iDb is
822 ** set to the index of the database that the table or view is to be
823 ** created in.
824 */
danielk1977ef2cb632004-05-29 02:37:19 +0000825 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000826 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000827 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
828 /* If creating a temp table, the name may not be qualified. Unless
829 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000830 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000831 return;
832 }
danielk197753c0f742005-03-29 03:10:59 +0000833 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000834
835 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000836 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000837 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000838 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000839 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000840 }
drh1d85d932004-02-14 23:05:52 +0000841 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000842#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000843 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000844 {
845 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000846 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000847 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000848 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000849 }
drhe5f9c642003-01-13 23:27:31 +0000850 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000851 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000852 code = SQLITE_CREATE_TEMP_VIEW;
853 }else{
854 code = SQLITE_CREATE_VIEW;
855 }
856 }else{
danielk197753c0f742005-03-29 03:10:59 +0000857 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000858 code = SQLITE_CREATE_TEMP_TABLE;
859 }else{
860 code = SQLITE_CREATE_TABLE;
861 }
862 }
danielk1977f1a381e2006-06-16 08:01:02 +0000863 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000864 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000865 }
866 }
867#endif
drhf57b3392001-10-08 13:22:32 +0000868
drhf57b3392001-10-08 13:22:32 +0000869 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000870 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000871 ** it does. The exception is if the statement being parsed was passed
872 ** to an sqlite3_declare_vtab() call. In that case only the column names
873 ** and types will be used, so there is no need to test for namespace
874 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000875 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000876 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000877 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000878 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
879 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000880 }
dana16d1062010-09-28 17:37:28 +0000881 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000882 if( pTable ){
883 if( !noErr ){
884 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000885 }else{
886 assert( !db->init.busy );
887 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000888 }
889 goto begin_table_error;
890 }
drh8a8a0d12010-09-28 20:26:44 +0000891 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000892 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
893 goto begin_table_error;
894 }
drh75897232000-05-29 14:26:00 +0000895 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000896
danielk197726783a52007-08-29 14:06:22 +0000897 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000898 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000899 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000900 pParse->rc = SQLITE_NOMEM;
901 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000902 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000903 }
drh75897232000-05-29 14:26:00 +0000904 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000905 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000906 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000907 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000908 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000909 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000910 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000911
drh4794f732004-11-05 17:17:50 +0000912 /* If this is the magic sqlite_sequence table used by autoincrement,
913 ** then record a pointer to this table in the main database structure
914 ** so that INSERT can find the table easily.
915 */
916#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000917 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000918 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000919 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000920 }
921#endif
922
drh17f71932002-02-21 12:01:27 +0000923 /* Begin generating the code that will insert the table record into
924 ** the SQLITE_MASTER table. Note in particular that we must go ahead
925 ** and allocate the record number for the table entry now. Before any
926 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
927 ** indices to be created and the table record must come before the
928 ** indices. Hence, the record number for the table must be allocated
929 ** now.
930 */
danielk19774adee202004-05-08 08:23:19 +0000931 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000932 int j1;
drhe321c292006-01-12 01:56:43 +0000933 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000934 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000935 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000936
danielk197720b1eaf2006-07-26 16:22:14 +0000937#ifndef SQLITE_OMIT_VIRTUALTABLE
938 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000939 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000940 }
941#endif
942
danielk197736963fd2005-02-19 08:18:05 +0000943 /* If the file format and encoding in the database have not been set,
944 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000945 */
drhb7654112008-01-12 12:48:07 +0000946 reg1 = pParse->regRowid = ++pParse->nMem;
947 reg2 = pParse->regRoot = ++pParse->nMem;
948 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000949 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000950 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +0000951 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +0000952 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000953 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000954 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000955 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000956 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000957 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000958 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000959
drh4794f732004-11-05 17:17:50 +0000960 /* This just creates a place-holder record in the sqlite_master table.
961 ** The record created does not contain anything yet. It will be replaced
962 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000963 **
drh0fa991b2009-03-21 16:19:26 +0000964 ** The rowid for the new entry is left in register pParse->regRowid.
965 ** The root page number of the new table is left in reg pParse->regRoot.
966 ** The rowid and root page number values are needed by the code that
967 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000968 */
danielk1977f1a381e2006-06-16 08:01:02 +0000969#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
970 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000971 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000972 }else
973#endif
974 {
drh8a120f82013-11-01 17:59:53 +0000975 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000976 }
danielk1977c00da102006-01-07 13:21:04 +0000977 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000978 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
979 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
980 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
981 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000982 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000983 }
drh23bf66d2004-12-14 03:34:34 +0000984
985 /* Normal (non-error) return. */
986 return;
987
988 /* If an error occurs, we jump here */
989begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000990 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000991 return;
drh75897232000-05-29 14:26:00 +0000992}
993
994/*
danielk1977c60e9b82005-01-31 12:42:29 +0000995** This macro is used to compare two strings in a case-insensitive manner.
996** It is slightly faster than calling sqlite3StrICmp() directly, but
997** produces larger code.
998**
999** WARNING: This macro is not compatible with the strcmp() family. It
1000** returns true if the two strings are equal, otherwise false.
1001*/
1002#define STRICMP(x, y) (\
1003sqlite3UpperToLower[*(unsigned char *)(x)]== \
1004sqlite3UpperToLower[*(unsigned char *)(y)] \
1005&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1006
1007/*
drh75897232000-05-29 14:26:00 +00001008** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001009**
1010** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001011** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001012** first to get things going. Then this routine is called for each
1013** column.
drh75897232000-05-29 14:26:00 +00001014*/
danielk19774adee202004-05-08 08:23:19 +00001015void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001016 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001017 int i;
drha99db3b2004-06-19 14:49:12 +00001018 char *z;
drhc9b84a12002-06-20 11:36:48 +00001019 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001020 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001021 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001022#if SQLITE_MAX_COLUMN
1023 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001024 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1025 return;
1026 }
drhbb4957f2008-03-20 14:03:29 +00001027#endif
danielk1977ae74e032008-12-23 11:11:51 +00001028 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001029 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001030 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001031 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001032 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001033 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001034 return;
1035 }
1036 }
drh75897232000-05-29 14:26:00 +00001037 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001038 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001039 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001040 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001041 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001042 return;
1043 }
drh6d4abfb2001-10-22 02:58:08 +00001044 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001045 }
drhc9b84a12002-06-20 11:36:48 +00001046 pCol = &p->aCol[p->nCol];
1047 memset(pCol, 0, sizeof(p->aCol[0]));
1048 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001049
1050 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001051 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1052 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001053 */
danielk19774f057f92004-06-08 00:02:33 +00001054 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001055 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001056 p->nCol++;
drh75897232000-05-29 14:26:00 +00001057}
1058
1059/*
drh382c0242001-10-06 16:33:02 +00001060** This routine is called by the parser while in the middle of
1061** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1062** been seen on a column. This routine sets the notNull flag on
1063** the column currently under construction.
1064*/
danielk19774adee202004-05-08 08:23:19 +00001065void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001066 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001067 p = pParse->pNewTable;
1068 if( p==0 || NEVER(p->nCol<1) ) return;
1069 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001070}
1071
1072/*
danielk197752a83fb2005-01-31 12:56:44 +00001073** Scan the column type name zType (length nType) and return the
1074** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001075**
1076** This routine does a case-independent search of zType for the
1077** substrings in the following table. If one of the substrings is
1078** found, the corresponding affinity is returned. If zType contains
1079** more than one of the substrings, entries toward the top of
1080** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001081** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001082**
1083** Substring | Affinity
1084** --------------------------------
1085** 'INT' | SQLITE_AFF_INTEGER
1086** 'CHAR' | SQLITE_AFF_TEXT
1087** 'CLOB' | SQLITE_AFF_TEXT
1088** 'TEXT' | SQLITE_AFF_TEXT
1089** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001090** 'REAL' | SQLITE_AFF_REAL
1091** 'FLOA' | SQLITE_AFF_REAL
1092** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001093**
1094** If none of the substrings in the above table are found,
1095** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001096*/
drhfdaac672013-10-04 15:30:21 +00001097char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001098 u32 h = 0;
1099 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001100 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001101
drhfdaac672013-10-04 15:30:21 +00001102 if( zIn==0 ) return aff;
1103 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001104 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001105 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001106 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001107 aff = SQLITE_AFF_TEXT;
1108 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001109 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1110 aff = SQLITE_AFF_TEXT;
1111 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1112 aff = SQLITE_AFF_TEXT;
1113 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001114 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001115 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001116 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001117#ifndef SQLITE_OMIT_FLOATING_POINT
1118 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1119 && aff==SQLITE_AFF_NUMERIC ){
1120 aff = SQLITE_AFF_REAL;
1121 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1122 && aff==SQLITE_AFF_NUMERIC ){
1123 aff = SQLITE_AFF_REAL;
1124 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1125 && aff==SQLITE_AFF_NUMERIC ){
1126 aff = SQLITE_AFF_REAL;
1127#endif
danielk1977201f7162005-02-01 02:13:29 +00001128 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001129 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001130 break;
danielk197752a83fb2005-01-31 12:56:44 +00001131 }
1132 }
drhd3037a42013-10-04 18:29:25 +00001133
1134 /* If pszEst is not NULL, store an estimate of the field size. The
1135 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001136 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001137 *pszEst = 1; /* default size is approx 4 bytes */
1138 if( aff<=SQLITE_AFF_NONE ){
1139 if( zChar ){
1140 while( zChar[0] ){
1141 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001142 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001143 sqlite3GetInt32(zChar, &v);
1144 v = v/4 + 1;
1145 if( v>255 ) v = 255;
1146 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1147 break;
1148 }
1149 zChar++;
drhfdaac672013-10-04 15:30:21 +00001150 }
drhd3037a42013-10-04 18:29:25 +00001151 }else{
1152 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001153 }
drhfdaac672013-10-04 15:30:21 +00001154 }
1155 }
danielk1977b3dff962005-02-01 01:21:55 +00001156 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001157}
1158
1159/*
drh382c0242001-10-06 16:33:02 +00001160** This routine is called by the parser while in the middle of
1161** parsing a CREATE TABLE statement. The pFirst token is the first
1162** token in the sequence of tokens that describe the type of the
1163** column currently under construction. pLast is the last token
1164** in the sequence. Use this information to construct a string
1165** that contains the typename of the column and store that string
1166** in zType.
1167*/
drh487e2622005-06-25 18:42:14 +00001168void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001169 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001170 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001171
drhc4a64fa2009-05-11 20:53:28 +00001172 p = pParse->pNewTable;
1173 if( p==0 || NEVER(p->nCol<1) ) return;
1174 pCol = &p->aCol[p->nCol-1];
1175 assert( pCol->zType==0 );
1176 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001177 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001178}
1179
1180/*
danielk19777977a172004-11-09 12:44:37 +00001181** The expression is the default value for the most recently added column
1182** of the table currently under construction.
1183**
1184** Default value expressions must be constant. Raise an exception if this
1185** is not the case.
drhd9b02572001-04-15 00:37:09 +00001186**
1187** This routine is called by the parser while in the middle of
1188** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001189*/
drhb7916a72009-05-27 10:31:29 +00001190void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001191 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001192 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001193 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001194 p = pParse->pNewTable;
1195 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001196 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001197 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001198 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1199 pCol->zName);
1200 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001201 /* A copy of pExpr is used instead of the original, as pExpr contains
1202 ** tokens that point to volatile memory. The 'span' of the expression
1203 ** is required by pragma table_info.
1204 */
drh633e6d52008-07-28 19:34:53 +00001205 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001206 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1207 sqlite3DbFree(db, pCol->zDflt);
1208 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001209 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001210 }
danielk19777977a172004-11-09 12:44:37 +00001211 }
drhb7916a72009-05-27 10:31:29 +00001212 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001213}
1214
1215/*
drh4a324312001-12-21 14:30:42 +00001216** Designate the PRIMARY KEY for the table. pList is a list of names
1217** of columns that form the primary key. If pList is NULL, then the
1218** most recently added column of the table is the primary key.
1219**
1220** A table can have at most one primary key. If the table already has
1221** a primary key (and this is the second primary key) then create an
1222** error.
1223**
1224** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001225** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001226** field of the table under construction to be the index of the
1227** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1228** no INTEGER PRIMARY KEY.
1229**
1230** If the key is not an INTEGER PRIMARY KEY, then create a unique
1231** index for the key. No index is created for INTEGER PRIMARY KEYs.
1232*/
drh205f48e2004-11-05 00:43:11 +00001233void sqlite3AddPrimaryKey(
1234 Parse *pParse, /* Parsing context */
1235 ExprList *pList, /* List of field names to be indexed */
1236 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001237 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1238 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001239){
drh4a324312001-12-21 14:30:42 +00001240 Table *pTab = pParse->pNewTable;
1241 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001242 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001243 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001244 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001245 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001246 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001247 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001248 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001249 }
drh7d10d5a2008-08-20 16:35:10 +00001250 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001251 if( pList==0 ){
1252 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001253 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001254 zType = pTab->aCol[iCol].zType;
1255 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001256 }else{
drh8ea30bf2013-10-22 01:18:17 +00001257 nTerm = pList->nExpr;
1258 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001259 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001260 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001261 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1262 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001263 break;
1264 }
drh78100cc2003-08-23 22:40:53 +00001265 }
drh4a324312001-12-21 14:30:42 +00001266 }
1267 }
drh8ea30bf2013-10-22 01:18:17 +00001268 if( nTerm==1
1269 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1270 && sortOrder==SQLITE_SO_ASC
1271 ){
drh4a324312001-12-21 14:30:42 +00001272 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001273 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001274 assert( autoInc==0 || autoInc==1 );
1275 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001276 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001277 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001278#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001279 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1280 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001281#endif
drh4a324312001-12-21 14:30:42 +00001282 }else{
drhc6bd4e42013-11-02 14:37:18 +00001283 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001284 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001285 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001286 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001287 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001288 if( p ){
1289 p->autoIndex = 2;
drhc6bd4e42013-11-02 14:37:18 +00001290 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001291 }
drhe0194f22003-02-26 13:52:51 +00001292 pList = 0;
drh4a324312001-12-21 14:30:42 +00001293 }
drhe0194f22003-02-26 13:52:51 +00001294
1295primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001296 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001297 return;
drh4a324312001-12-21 14:30:42 +00001298}
1299
1300/*
drhffe07b22005-11-03 00:41:17 +00001301** Add a new CHECK constraint to the table currently under construction.
1302*/
1303void sqlite3AddCheckConstraint(
1304 Parse *pParse, /* Parsing context */
1305 Expr *pCheckExpr /* The check expression */
1306){
1307#ifndef SQLITE_OMIT_CHECK
1308 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001309 sqlite3 *db = pParse->db;
1310 if( pTab && !IN_DECLARE_VTAB
1311 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1312 ){
drh2938f922012-03-07 19:13:29 +00001313 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1314 if( pParse->constraintName.n ){
1315 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1316 }
drh33e619f2009-05-28 01:00:55 +00001317 }else
drhffe07b22005-11-03 00:41:17 +00001318#endif
drh33e619f2009-05-28 01:00:55 +00001319 {
drh2938f922012-03-07 19:13:29 +00001320 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001321 }
drhffe07b22005-11-03 00:41:17 +00001322}
1323
1324/*
drhd3d39e92004-05-20 22:16:29 +00001325** Set the collation function of the most recently parsed table column
1326** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001327*/
danielk197739002502007-11-12 09:50:26 +00001328void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001329 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001330 int i;
danielk197739002502007-11-12 09:50:26 +00001331 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001332 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001333
danielk1977b8cbb872006-06-19 05:33:45 +00001334 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001335 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001336 db = pParse->db;
1337 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001338 if( !zColl ) return;
1339
drhc4a64fa2009-05-11 20:53:28 +00001340 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001341 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001342 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001343 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001344
1345 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1346 ** then an index may have been created on this column before the
1347 ** collation type was added. Correct this if it is the case.
1348 */
1349 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001350 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001351 if( pIdx->aiColumn[0]==i ){
1352 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001353 }
1354 }
danielk197739002502007-11-12 09:50:26 +00001355 }else{
drh633e6d52008-07-28 19:34:53 +00001356 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001357 }
danielk19777cedc8d2004-06-10 10:50:08 +00001358}
1359
danielk1977466be562004-06-10 02:16:01 +00001360/*
1361** This function returns the collation sequence for database native text
1362** encoding identified by the string zName, length nName.
1363**
1364** If the requested collation sequence is not available, or not available
1365** in the database native encoding, the collation factory is invoked to
1366** request it. If the collation factory does not supply such a sequence,
1367** and the sequence is available in another text encoding, then that is
1368** returned instead.
1369**
1370** If no versions of the requested collations sequence are available, or
1371** another error occurs, NULL is returned and an error message written into
1372** pParse.
drha34001c2007-02-02 12:44:37 +00001373**
1374** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1375** invokes the collation factory if the named collation cannot be found
1376** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001377**
1378** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001379*/
drhc4a64fa2009-05-11 20:53:28 +00001380CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001381 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001382 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001383 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001384 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001385
drhc4a64fa2009-05-11 20:53:28 +00001386 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001387 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001388 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001389 }
1390
danielk19770202b292004-06-09 09:55:16 +00001391 return pColl;
1392}
1393
1394
drh8e2ca022002-06-17 17:07:19 +00001395/*
drh3f7d4e42004-07-24 14:35:58 +00001396** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001397**
1398** The schema cookie is used to determine when the schema for the
1399** database changes. After each schema change, the cookie value
1400** changes. When a process first reads the schema it records the
1401** cookie. Thereafter, whenever it goes to access the database,
1402** it checks the cookie to make sure the schema has not changed
1403** since it was last read.
1404**
1405** This plan is not completely bullet-proof. It is possible for
1406** the schema to change multiple times and for the cookie to be
1407** set back to prior value. But schema changes are infrequent
1408** and the probability of hitting the same cookie value is only
1409** 1 chance in 2^32. So we're safe enough.
1410*/
drh9cbf3422008-01-17 16:22:13 +00001411void sqlite3ChangeCookie(Parse *pParse, int iDb){
1412 int r1 = sqlite3GetTempReg(pParse);
1413 sqlite3 *db = pParse->db;
1414 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001415 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001416 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001417 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001418 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001419}
1420
1421/*
drh969fa7c2002-02-18 18:30:32 +00001422** Measure the number of characters needed to output the given
1423** identifier. The number returned includes any quotes used
1424** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001425**
1426** The estimate is conservative. It might be larger that what is
1427** really needed.
drh969fa7c2002-02-18 18:30:32 +00001428*/
1429static int identLength(const char *z){
1430 int n;
drh17f71932002-02-21 12:01:27 +00001431 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001432 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001433 }
drh234c39d2004-07-24 03:30:47 +00001434 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001435}
1436
1437/*
danielk19771b870de2009-03-14 08:37:23 +00001438** The first parameter is a pointer to an output buffer. The second
1439** parameter is a pointer to an integer that contains the offset at
1440** which to write into the output buffer. This function copies the
1441** nul-terminated string pointed to by the third parameter, zSignedIdent,
1442** to the specified offset in the buffer and updates *pIdx to refer
1443** to the first byte after the last byte written before returning.
1444**
1445** If the string zSignedIdent consists entirely of alpha-numeric
1446** characters, does not begin with a digit and is not an SQL keyword,
1447** then it is copied to the output buffer exactly as it is. Otherwise,
1448** it is quoted using double-quotes.
1449*/
drhc4a64fa2009-05-11 20:53:28 +00001450static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001451 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001452 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001453 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001454
drh17f71932002-02-21 12:01:27 +00001455 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001456 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001457 }
drhc7407522014-01-10 20:38:12 +00001458 needQuote = sqlite3Isdigit(zIdent[0])
1459 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1460 || zIdent[j]!=0
1461 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001462
drh234c39d2004-07-24 03:30:47 +00001463 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001464 for(j=0; zIdent[j]; j++){
1465 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001466 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001467 }
drh234c39d2004-07-24 03:30:47 +00001468 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001469 z[i] = 0;
1470 *pIdx = i;
1471}
1472
1473/*
1474** Generate a CREATE TABLE statement appropriate for the given
1475** table. Memory to hold the text of the statement is obtained
1476** from sqliteMalloc() and must be freed by the calling function.
1477*/
drh1d34fde2009-02-03 15:50:33 +00001478static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001479 int i, k, n;
1480 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001481 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001482 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001483 n = 0;
drh234c39d2004-07-24 03:30:47 +00001484 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001485 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001486 }
1487 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001488 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001489 zSep = "";
1490 zSep2 = ",";
1491 zEnd = ")";
1492 }else{
1493 zSep = "\n ";
1494 zSep2 = ",\n ";
1495 zEnd = "\n)";
1496 }
drhe0bc4042002-06-25 01:09:11 +00001497 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001498 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001499 if( zStmt==0 ){
1500 db->mallocFailed = 1;
1501 return 0;
1502 }
drhbdb339f2009-02-02 18:03:21 +00001503 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001504 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001505 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001506 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001507 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001508 static const char * const azType[] = {
1509 /* SQLITE_AFF_TEXT */ " TEXT",
1510 /* SQLITE_AFF_NONE */ "",
1511 /* SQLITE_AFF_NUMERIC */ " NUM",
1512 /* SQLITE_AFF_INTEGER */ " INT",
1513 /* SQLITE_AFF_REAL */ " REAL"
1514 };
1515 int len;
1516 const char *zType;
1517
drh5bb3eb92007-05-04 13:15:55 +00001518 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001519 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001520 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001521 identPut(zStmt, &k, pCol->zName);
1522 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001523 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001524 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1525 testcase( pCol->affinity==SQLITE_AFF_NONE );
1526 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1527 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1528 testcase( pCol->affinity==SQLITE_AFF_REAL );
1529
1530 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1531 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001532 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001533 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001534 memcpy(&zStmt[k], zType, len);
1535 k += len;
1536 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001537 }
drh5bb3eb92007-05-04 13:15:55 +00001538 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001539 return zStmt;
1540}
1541
1542/*
drh7f9c5db2013-10-23 00:32:58 +00001543** Resize an Index object to hold N columns total. Return SQLITE_OK
1544** on success and SQLITE_NOMEM on an OOM error.
1545*/
1546static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1547 char *zExtra;
1548 int nByte;
1549 if( pIdx->nColumn>=N ) return SQLITE_OK;
1550 assert( pIdx->isResized==0 );
1551 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1552 zExtra = sqlite3DbMallocZero(db, nByte);
1553 if( zExtra==0 ) return SQLITE_NOMEM;
1554 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1555 pIdx->azColl = (char**)zExtra;
1556 zExtra += sizeof(char*)*N;
1557 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1558 pIdx->aiColumn = (i16*)zExtra;
1559 zExtra += sizeof(i16)*N;
1560 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1561 pIdx->aSortOrder = (u8*)zExtra;
1562 pIdx->nColumn = N;
1563 pIdx->isResized = 1;
1564 return SQLITE_OK;
1565}
1566
1567/*
drhfdaac672013-10-04 15:30:21 +00001568** Estimate the total row width for a table.
1569*/
drhe13e9f52013-10-05 19:18:00 +00001570static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001571 unsigned wTable = 0;
1572 const Column *pTabCol;
1573 int i;
1574 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1575 wTable += pTabCol->szEst;
1576 }
1577 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001578 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001579}
1580
1581/*
drhe13e9f52013-10-05 19:18:00 +00001582** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001583*/
drhe13e9f52013-10-05 19:18:00 +00001584static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001585 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001586 int i;
1587 const Column *aCol = pIdx->pTable->aCol;
1588 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001589 i16 x = pIdx->aiColumn[i];
1590 assert( x<pIdx->pTable->nCol );
1591 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001592 }
drhe13e9f52013-10-05 19:18:00 +00001593 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001594}
1595
drh7f9c5db2013-10-23 00:32:58 +00001596/* Return true if value x is found any of the first nCol entries of aiCol[]
1597*/
1598static int hasColumn(const i16 *aiCol, int nCol, int x){
1599 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1600 return 0;
1601}
1602
1603/*
drhc6bd4e42013-11-02 14:37:18 +00001604** This routine runs at the end of parsing a CREATE TABLE statement that
1605** has a WITHOUT ROWID clause. The job of this routine is to convert both
1606** internal schema data structures and the generated VDBE code so that they
1607** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1608** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001609**
drhc6bd4e42013-11-02 14:37:18 +00001610** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1611** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1612** data storage is a covering index btree.
1613** (2) Bypass the creation of the sqlite_master table entry
1614** for the PRIMARY KEY as the the primary key index is now
1615** identified by the sqlite_master table entry of the table itself.
1616** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1617** schema to the rootpage from the main table.
1618** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1619** (5) Add all table columns to the PRIMARY KEY Index object
1620** so that the PRIMARY KEY is a covering index. The surplus
1621** columns are part of KeyInfo.nXField and are not used for
1622** sorting or lookup or uniqueness checks.
1623** (6) Replace the rowid tail on all automatically generated UNIQUE
1624** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001625*/
1626static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1627 Index *pIdx;
1628 Index *pPk;
1629 int nPk;
1630 int i, j;
1631 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001632 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001633
1634 /* Convert the OP_CreateTable opcode that would normally create the
drhc6bd4e42013-11-02 14:37:18 +00001635 ** root-page for the table into a OP_CreateIndex opcode. The index
1636 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001637 */
1638 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001639 assert( v );
1640 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1641 }
1642
1643 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1644 ** table entry.
1645 */
1646 if( pParse->addrSkipPK ){
1647 assert( v );
1648 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001649 }
1650
1651 /* Locate the PRIMARY KEY index. Or, if this table was originally
1652 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1653 */
1654 if( pTab->iPKey>=0 ){
1655 ExprList *pList;
1656 pList = sqlite3ExprListAppend(pParse, 0, 0);
1657 if( pList==0 ) return;
1658 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1659 pTab->aCol[pTab->iPKey].zName);
1660 pList->a[0].sortOrder = pParse->iPkSortOrder;
1661 assert( pParse->pNewTable==pTab );
1662 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1663 if( pPk==0 ) return;
drh63f0eed2013-11-02 22:09:48 +00001664 pPk->autoIndex = 2;
drh7f9c5db2013-10-23 00:32:58 +00001665 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001666 }else{
1667 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001668 }
drh12826092013-11-05 22:39:17 +00001669 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001670 assert( pPk!=0 );
1671 nPk = pPk->nKeyCol;
1672
drhec95c442013-10-23 01:57:32 +00001673 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1674 for(i=0; i<nPk; i++){
1675 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1676 }
drh9eade082013-10-24 14:16:10 +00001677 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001678
drhc6bd4e42013-11-02 14:37:18 +00001679 /* The root page of the PRIMARY KEY is the table root page */
1680 pPk->tnum = pTab->tnum;
1681
drh7f9c5db2013-10-23 00:32:58 +00001682 /* Update the in-memory representation of all UNIQUE indices by converting
1683 ** the final rowid column into one or more columns of the PRIMARY KEY.
1684 */
1685 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1686 int n;
1687 if( pIdx->autoIndex==2 ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001688 for(i=n=0; i<nPk; i++){
1689 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1690 }
drh5a9a37b2013-11-05 17:30:04 +00001691 if( n==0 ){
1692 /* This index is a superset of the primary key */
1693 pIdx->nColumn = pIdx->nKeyCol;
1694 continue;
1695 }
drh7f9c5db2013-10-23 00:32:58 +00001696 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1697 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001698 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001699 pIdx->aiColumn[j] = pPk->aiColumn[i];
1700 pIdx->azColl[j] = pPk->azColl[i];
1701 j++;
1702 }
1703 }
drh00012df2013-11-05 01:59:07 +00001704 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1705 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001706 }
1707
1708 /* Add all table columns to the PRIMARY KEY index
1709 */
1710 if( nPk<pTab->nCol ){
1711 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1712 for(i=0, j=nPk; i<pTab->nCol; i++){
1713 if( !hasColumn(pPk->aiColumn, j, i) ){
1714 assert( j<pPk->nColumn );
1715 pPk->aiColumn[j] = i;
1716 pPk->azColl[j] = "BINARY";
1717 j++;
1718 }
1719 }
1720 assert( pPk->nColumn==j );
1721 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001722 }else{
1723 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001724 }
1725}
1726
drhfdaac672013-10-04 15:30:21 +00001727/*
drh75897232000-05-29 14:26:00 +00001728** This routine is called to report the final ")" that terminates
1729** a CREATE TABLE statement.
1730**
drhf57b3392001-10-08 13:22:32 +00001731** The table structure that other action routines have been building
1732** is added to the internal hash tables, assuming no errors have
1733** occurred.
drh75897232000-05-29 14:26:00 +00001734**
drh1d85d932004-02-14 23:05:52 +00001735** An entry for the table is made in the master table on disk, unless
1736** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001737** it means we are reading the sqlite_master table because we just
1738** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001739** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001740** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001741**
1742** If the pSelect argument is not NULL, it means that this routine
1743** was called to create a table generated from a
1744** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1745** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001746*/
danielk197719a8e7e2005-03-17 05:03:38 +00001747void sqlite3EndTable(
1748 Parse *pParse, /* Parse context */
1749 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001750 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1751 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001752 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1753){
drhfdaac672013-10-04 15:30:21 +00001754 Table *p; /* The new table */
1755 sqlite3 *db = pParse->db; /* The database connection */
1756 int iDb; /* Database in which the table lives */
1757 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001758
drh5969da42013-10-21 02:14:45 +00001759 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1760 return;
danielk1977261919c2005-12-06 12:52:59 +00001761 }
drh28037572000-08-02 13:47:41 +00001762 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001763 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001764
danielk1977517eb642004-06-07 10:00:31 +00001765 assert( !db->init.busy || !pSelect );
1766
drhc6bd4e42013-11-02 14:37:18 +00001767 /* If the db->init.busy is 1 it means we are reading the SQL off the
1768 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1769 ** So do not write to the disk again. Extract the root page number
1770 ** for the table from the db->init.newTnum field. (The page number
1771 ** should have been put there by the sqliteOpenCb routine.)
1772 */
1773 if( db->init.busy ){
1774 p->tnum = db->init.newTnum;
1775 }
1776
1777 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001778 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001779 if( (p->tabFlags & TF_Autoincrement) ){
1780 sqlite3ErrorMsg(pParse,
1781 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1782 return;
1783 }
drh5969da42013-10-21 02:14:45 +00001784 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001785 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001786 }else{
1787 p->tabFlags |= TF_WithoutRowid;
1788 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001789 }
1790 }
1791
drhb9bb7c12006-06-11 23:41:55 +00001792 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001793
drhffe07b22005-11-03 00:41:17 +00001794#ifndef SQLITE_OMIT_CHECK
1795 /* Resolve names in all CHECK constraint expressions.
1796 */
1797 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001798 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001799 }
1800#endif /* !defined(SQLITE_OMIT_CHECK) */
1801
drhe13e9f52013-10-05 19:18:00 +00001802 /* Estimate the average row size for the table and for all implied indices */
1803 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001804 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001805 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001806 }
1807
drhe3c41372001-09-17 20:25:58 +00001808 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001809 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001810 **
drhe0bc4042002-06-25 01:09:11 +00001811 ** If this is a TEMPORARY table, write the entry into the auxiliary
1812 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001813 */
drh1d85d932004-02-14 23:05:52 +00001814 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001815 int n;
drhd8bc7082000-06-07 23:51:50 +00001816 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001817 char *zType; /* "view" or "table" */
1818 char *zType2; /* "VIEW" or "TABLE" */
1819 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001820
danielk19774adee202004-05-08 08:23:19 +00001821 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001822 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001823
drh66a51672008-01-03 00:01:23 +00001824 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001825
drh0fa991b2009-03-21 16:19:26 +00001826 /*
1827 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001828 */
drh4ff6dfa2002-03-03 23:06:00 +00001829 if( p->pSelect==0 ){
1830 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001831 zType = "table";
1832 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001833#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001834 }else{
1835 /* A view */
drh4794f732004-11-05 17:17:50 +00001836 zType = "view";
1837 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001838#endif
drh4ff6dfa2002-03-03 23:06:00 +00001839 }
danielk1977517eb642004-06-07 10:00:31 +00001840
danielk1977517eb642004-06-07 10:00:31 +00001841 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1842 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001843 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001844 **
1845 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1846 ** suitable state to query for the column names and types to be used
1847 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001848 **
1849 ** A shared-cache write-lock is not required to write to the new table,
1850 ** as a schema-lock must have already been obtained to create it. Since
1851 ** a schema-lock excludes all other database users, the write-lock would
1852 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001853 */
1854 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001855 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001856 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001857
danielk19776ab3a2e2009-02-19 14:39:25 +00001858 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001859 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001860 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001861 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001862 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001863 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001864 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001865 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001866 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001867 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001868 assert( p->aCol==0 );
1869 p->nCol = pSelTab->nCol;
1870 p->aCol = pSelTab->aCol;
1871 pSelTab->nCol = 0;
1872 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001873 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001874 }
1875 }
drh4794f732004-11-05 17:17:50 +00001876
drh4794f732004-11-05 17:17:50 +00001877 /* Compute the complete text of the CREATE statement */
1878 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001879 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001880 }else{
drh8ea30bf2013-10-22 01:18:17 +00001881 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1882 n = (int)(pEnd2->z - pParse->sNameToken.z);
1883 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001884 zStmt = sqlite3MPrintf(db,
1885 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1886 );
drh4794f732004-11-05 17:17:50 +00001887 }
1888
1889 /* A slot for the record has already been allocated in the
1890 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001891 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001892 */
1893 sqlite3NestedParse(pParse,
1894 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001895 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1896 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001897 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001898 zType,
1899 p->zName,
1900 p->zName,
drhb7654112008-01-12 12:48:07 +00001901 pParse->regRoot,
1902 zStmt,
1903 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001904 );
drh633e6d52008-07-28 19:34:53 +00001905 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001906 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001907
1908#ifndef SQLITE_OMIT_AUTOINCREMENT
1909 /* Check to see if we need to create an sqlite_sequence table for
1910 ** keeping track of autoincrement keys.
1911 */
drh7d10d5a2008-08-20 16:35:10 +00001912 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001913 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001914 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001915 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001916 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001917 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1918 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001919 );
1920 }
1921 }
1922#endif
drh4794f732004-11-05 17:17:50 +00001923
1924 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001925 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001926 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001927 }
drh17e9e292003-02-01 13:53:28 +00001928
drh2958a4e2004-11-12 03:56:15 +00001929
drh17e9e292003-02-01 13:53:28 +00001930 /* Add the table to the in-memory representation of the database.
1931 */
drh8af73d42009-05-13 22:58:28 +00001932 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001933 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001934 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001935 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001936 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001937 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001938 if( pOld ){
1939 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001940 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001941 return;
drh17e9e292003-02-01 13:53:28 +00001942 }
drh17e9e292003-02-01 13:53:28 +00001943 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001944 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001945
1946#ifndef SQLITE_OMIT_ALTERTABLE
1947 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001948 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001949 int nName;
drh5969da42013-10-21 02:14:45 +00001950 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001951 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00001952 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00001953 }
drh1bd10f82008-12-10 21:19:56 +00001954 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001955 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001956 }
1957#endif
drh17e9e292003-02-01 13:53:28 +00001958 }
drh75897232000-05-29 14:26:00 +00001959}
1960
drhb7f91642004-10-31 02:22:47 +00001961#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001962/*
drha76b5df2002-02-23 02:32:10 +00001963** The parser calls this routine in order to create a new VIEW
1964*/
danielk19774adee202004-05-08 08:23:19 +00001965void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001966 Parse *pParse, /* The parsing context */
1967 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001968 Token *pName1, /* The token that holds the name of the view */
1969 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001970 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001971 int isTemp, /* TRUE for a TEMPORARY view */
1972 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001973){
drha76b5df2002-02-23 02:32:10 +00001974 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001975 int n;
drhb7916a72009-05-27 10:31:29 +00001976 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001977 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001978 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00001979 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00001980 int iDb;
drh17435752007-08-16 04:30:38 +00001981 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001982
drh7c3d64f2005-06-06 15:32:08 +00001983 if( pParse->nVar>0 ){
1984 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001985 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001986 return;
1987 }
drhfdd48a72006-09-11 23:45:48 +00001988 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001989 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001990 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001991 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001992 return;
1993 }
danielk1977ef2cb632004-05-29 02:37:19 +00001994 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001995 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00001996 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
1997 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00001998 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001999 return;
2000 }
drh174b6192002-12-03 02:22:52 +00002001
drh4b59ab52002-08-24 18:24:51 +00002002 /* Make a copy of the entire SELECT statement that defines the view.
2003 ** This will force all the Expr.token.z values to be dynamically
2004 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002005 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002006 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002007 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002008 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002009 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002010 return;
2011 }
drh17435752007-08-16 04:30:38 +00002012 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002013 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002014 }
drh4b59ab52002-08-24 18:24:51 +00002015
2016 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2017 ** the end.
2018 */
drha76b5df2002-02-23 02:32:10 +00002019 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002020 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002021 sEnd.z += sEnd.n;
2022 }
2023 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002024 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002025 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002026 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002027 sEnd.z = &z[n-1];
2028 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002029
danielk19774adee202004-05-08 08:23:19 +00002030 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002031 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002032 return;
drh417be792002-03-03 18:59:40 +00002033}
drhb7f91642004-10-31 02:22:47 +00002034#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002035
danielk1977fe3fcbe22006-06-12 12:08:45 +00002036#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002037/*
2038** The Table structure pTable is really a VIEW. Fill in the names of
2039** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002040** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002041*/
danielk19774adee202004-05-08 08:23:19 +00002042int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002043 Table *pSelTab; /* A fake table from which we get the result set */
2044 Select *pSel; /* Copy of the SELECT that implements the view */
2045 int nErr = 0; /* Number of errors encountered */
2046 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002047 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00002048 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00002049
2050 assert( pTable );
2051
danielk1977fe3fcbe22006-06-12 12:08:45 +00002052#ifndef SQLITE_OMIT_VIRTUALTABLE
2053 if( sqlite3VtabCallConnect(pParse, pTable) ){
2054 return SQLITE_ERROR;
2055 }
drh4cbdda92006-06-14 19:00:20 +00002056 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002057#endif
2058
2059#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002060 /* A positive nCol means the columns names for this view are
2061 ** already known.
2062 */
2063 if( pTable->nCol>0 ) return 0;
2064
2065 /* A negative nCol is a special marker meaning that we are currently
2066 ** trying to compute the column names. If we enter this routine with
2067 ** a negative nCol, it means two or more views form a loop, like this:
2068 **
2069 ** CREATE VIEW one AS SELECT * FROM two;
2070 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002071 **
drh768578e2009-05-12 00:40:12 +00002072 ** Actually, the error above is now caught prior to reaching this point.
2073 ** But the following test is still important as it does come up
2074 ** in the following:
2075 **
2076 ** CREATE TABLE main.ex1(a);
2077 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2078 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002079 */
2080 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002081 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002082 return 1;
2083 }
drh85c23c62005-08-20 03:03:04 +00002084 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002085
2086 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002087 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2088 ** "*" elements in the results set of the view and will assign cursors
2089 ** to the elements of the FROM clause. But we do not want these changes
2090 ** to be permanent. So the computation is done on a copy of the SELECT
2091 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002092 */
drh9b3187e2005-01-18 14:45:47 +00002093 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002094 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002095 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002096 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002097 n = pParse->nTab;
2098 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2099 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002100 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002101#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002102 xAuth = db->xAuth;
2103 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002104 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002105 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002106#else
drh7d10d5a2008-08-20 16:35:10 +00002107 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002108#endif
drhd9da78a2009-03-24 15:08:09 +00002109 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002110 pParse->nTab = n;
2111 if( pSelTab ){
2112 assert( pTable->aCol==0 );
2113 pTable->nCol = pSelTab->nCol;
2114 pTable->aCol = pSelTab->aCol;
2115 pSelTab->nCol = 0;
2116 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002117 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002118 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002119 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002120 }else{
2121 pTable->nCol = 0;
2122 nErr++;
2123 }
drh633e6d52008-07-28 19:34:53 +00002124 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002125 } else {
drh417be792002-03-03 18:59:40 +00002126 nErr++;
2127 }
drhb7f91642004-10-31 02:22:47 +00002128#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002129 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002130}
2131#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002132
drhb7f91642004-10-31 02:22:47 +00002133#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002134/*
drh8bf8dc92003-05-17 17:35:10 +00002135** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002136*/
drh9bb575f2004-09-06 17:24:11 +00002137static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002138 HashElem *i;
drh21206082011-04-04 18:22:02 +00002139 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002140 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002141 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002142 Table *pTab = sqliteHashData(i);
2143 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002144 sqliteDeleteColumnNames(db, pTab);
2145 pTab->aCol = 0;
2146 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002147 }
2148 }
drh8bf8dc92003-05-17 17:35:10 +00002149 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002150}
drhb7f91642004-10-31 02:22:47 +00002151#else
2152# define sqliteViewResetAll(A,B)
2153#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002154
drh75897232000-05-29 14:26:00 +00002155/*
danielk1977a0bf2652004-11-04 14:30:04 +00002156** This function is called by the VDBE to adjust the internal schema
2157** used by SQLite when the btree layer moves a table root page. The
2158** root-page of a table or index in database iDb has changed from iFrom
2159** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002160**
2161** Ticket #1728: The symbol table might still contain information
2162** on tables and/or indices that are the process of being deleted.
2163** If you are unlucky, one of those deleted indices or tables might
2164** have the same rootpage number as the real table or index that is
2165** being moved. So we cannot stop searching after the first match
2166** because the first match might be for one of the deleted indices
2167** or tables and not the table/index that is actually being moved.
2168** We must continue looping until all tables and indices with
2169** rootpage==iFrom have been converted to have a rootpage of iTo
2170** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002171*/
2172#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002173void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002174 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002175 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002176 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002177
drhcdf011d2011-04-04 21:25:28 +00002178 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2179 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002180 pHash = &pDb->pSchema->tblHash;
2181 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002182 Table *pTab = sqliteHashData(pElem);
2183 if( pTab->tnum==iFrom ){
2184 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002185 }
2186 }
danielk1977da184232006-01-05 11:34:32 +00002187 pHash = &pDb->pSchema->idxHash;
2188 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002189 Index *pIdx = sqliteHashData(pElem);
2190 if( pIdx->tnum==iFrom ){
2191 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002192 }
2193 }
danielk1977a0bf2652004-11-04 14:30:04 +00002194}
2195#endif
2196
2197/*
2198** Write code to erase the table with root-page iTable from database iDb.
2199** Also write code to modify the sqlite_master table and internal schema
2200** if a root-page of another table is moved by the btree-layer whilst
2201** erasing iTable (this can happen with an auto-vacuum database).
2202*/
drh4e0cff62004-11-05 05:10:28 +00002203static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2204 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002205 int r1 = sqlite3GetTempReg(pParse);
2206 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002207 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002208#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002209 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002210 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002211 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002212 ** reflect this.
2213 **
drh0fa991b2009-03-21 16:19:26 +00002214 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002215 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2216 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002217 */
danielk197763e3e9f2004-11-05 09:19:27 +00002218 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002219 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2220 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002221#endif
drhb7654112008-01-12 12:48:07 +00002222 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002223}
2224
2225/*
2226** Write VDBE code to erase table pTab and all associated indices on disk.
2227** Code to update the sqlite_master tables and internal schema definitions
2228** in case a root-page belonging to another table is moved by the btree layer
2229** is also added (this can happen with an auto-vacuum database).
2230*/
drh4e0cff62004-11-05 05:10:28 +00002231static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002232#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002233 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002234 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2235 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002236 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002237 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002238 }
2239#else
2240 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2241 ** is not defined), then it is important to call OP_Destroy on the
2242 ** table and index root-pages in order, starting with the numerically
2243 ** largest root-page number. This guarantees that none of the root-pages
2244 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2245 ** following were coded:
2246 **
2247 ** OP_Destroy 4 0
2248 ** ...
2249 ** OP_Destroy 5 0
2250 **
2251 ** and root page 5 happened to be the largest root-page number in the
2252 ** database, then root page 5 would be moved to page 4 by the
2253 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2254 ** a free-list page.
2255 */
2256 int iTab = pTab->tnum;
2257 int iDestroyed = 0;
2258
2259 while( 1 ){
2260 Index *pIdx;
2261 int iLargest = 0;
2262
2263 if( iDestroyed==0 || iTab<iDestroyed ){
2264 iLargest = iTab;
2265 }
2266 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2267 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002268 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002269 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2270 iLargest = iIdx;
2271 }
2272 }
danielk1977da184232006-01-05 11:34:32 +00002273 if( iLargest==0 ){
2274 return;
2275 }else{
2276 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002277 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002278 destroyRootPage(pParse, iLargest, iDb);
2279 iDestroyed = iLargest;
2280 }
danielk1977a0bf2652004-11-04 14:30:04 +00002281 }
2282#endif
2283}
2284
2285/*
drh74e7c8f2011-10-21 19:06:32 +00002286** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002287** after a DROP INDEX or DROP TABLE command.
2288*/
2289static void sqlite3ClearStatTables(
2290 Parse *pParse, /* The parsing context */
2291 int iDb, /* The database number */
2292 const char *zType, /* "idx" or "tbl" */
2293 const char *zName /* Name of index or table */
2294){
drha5ae4c32011-08-07 01:31:52 +00002295 int i;
2296 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002297 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002298 char zTab[24];
2299 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2300 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002301 sqlite3NestedParse(pParse,
2302 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002303 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002304 );
2305 }
2306 }
2307}
2308
2309/*
drhfaacf172011-08-12 01:51:45 +00002310** Generate code to drop a table.
2311*/
2312void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2313 Vdbe *v;
2314 sqlite3 *db = pParse->db;
2315 Trigger *pTrigger;
2316 Db *pDb = &db->aDb[iDb];
2317
2318 v = sqlite3GetVdbe(pParse);
2319 assert( v!=0 );
2320 sqlite3BeginWriteOperation(pParse, 1, iDb);
2321
2322#ifndef SQLITE_OMIT_VIRTUALTABLE
2323 if( IsVirtual(pTab) ){
2324 sqlite3VdbeAddOp0(v, OP_VBegin);
2325 }
2326#endif
2327
2328 /* Drop all triggers associated with the table being dropped. Code
2329 ** is generated to remove entries from sqlite_master and/or
2330 ** sqlite_temp_master if required.
2331 */
2332 pTrigger = sqlite3TriggerList(pParse, pTab);
2333 while( pTrigger ){
2334 assert( pTrigger->pSchema==pTab->pSchema ||
2335 pTrigger->pSchema==db->aDb[1].pSchema );
2336 sqlite3DropTriggerPtr(pParse, pTrigger);
2337 pTrigger = pTrigger->pNext;
2338 }
2339
2340#ifndef SQLITE_OMIT_AUTOINCREMENT
2341 /* Remove any entries of the sqlite_sequence table associated with
2342 ** the table being dropped. This is done before the table is dropped
2343 ** at the btree level, in case the sqlite_sequence table needs to
2344 ** move as a result of the drop (can happen in auto-vacuum mode).
2345 */
2346 if( pTab->tabFlags & TF_Autoincrement ){
2347 sqlite3NestedParse(pParse,
2348 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2349 pDb->zName, pTab->zName
2350 );
2351 }
2352#endif
2353
2354 /* Drop all SQLITE_MASTER table and index entries that refer to the
2355 ** table. The program name loops through the master table and deletes
2356 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002357 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002358 ** created in the temp database that refers to a table in another
2359 ** database.
2360 */
2361 sqlite3NestedParse(pParse,
2362 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2363 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002364 if( !isView && !IsVirtual(pTab) ){
2365 destroyTable(pParse, pTab);
2366 }
2367
2368 /* Remove the table entry from SQLite's internal schema and modify
2369 ** the schema cookie.
2370 */
2371 if( IsVirtual(pTab) ){
2372 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2373 }
2374 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2375 sqlite3ChangeCookie(pParse, iDb);
2376 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002377}
2378
2379/*
drh75897232000-05-29 14:26:00 +00002380** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002381** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002382*/
drha0733842005-12-29 01:11:36 +00002383void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002384 Table *pTab;
drh75897232000-05-29 14:26:00 +00002385 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002386 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002387 int iDb;
drh75897232000-05-29 14:26:00 +00002388
drh8af73d42009-05-13 22:58:28 +00002389 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002390 goto exit_drop_table;
2391 }
drh8af73d42009-05-13 22:58:28 +00002392 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002393 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002394 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002395 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002396 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002397
drha0733842005-12-29 01:11:36 +00002398 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002399 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002400 goto exit_drop_table;
2401 }
danielk1977da184232006-01-05 11:34:32 +00002402 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002403 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002404
2405 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2406 ** it is initialized.
2407 */
2408 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2409 goto exit_drop_table;
2410 }
drhe5f9c642003-01-13 23:27:31 +00002411#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002412 {
2413 int code;
danielk1977da184232006-01-05 11:34:32 +00002414 const char *zTab = SCHEMA_TABLE(iDb);
2415 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002416 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002417 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002418 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002419 }
drhe5f9c642003-01-13 23:27:31 +00002420 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002421 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002422 code = SQLITE_DROP_TEMP_VIEW;
2423 }else{
2424 code = SQLITE_DROP_VIEW;
2425 }
danielk19774b2688a2006-06-20 11:01:07 +00002426#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002427 }else if( IsVirtual(pTab) ){
2428 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002429 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002430#endif
drhe5f9c642003-01-13 23:27:31 +00002431 }else{
danielk197753c0f742005-03-29 03:10:59 +00002432 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002433 code = SQLITE_DROP_TEMP_TABLE;
2434 }else{
2435 code = SQLITE_DROP_TABLE;
2436 }
2437 }
danielk1977f1a381e2006-06-16 08:01:02 +00002438 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002439 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002440 }
danielk1977a8858102004-05-28 12:11:21 +00002441 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2442 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002443 }
drhe5f9c642003-01-13 23:27:31 +00002444 }
2445#endif
drh08ccfaa2011-10-07 23:52:25 +00002446 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2447 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002448 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002449 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002450 }
danielk1977576ec6b2005-01-21 11:55:25 +00002451
2452#ifndef SQLITE_OMIT_VIEW
2453 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2454 ** on a table.
2455 */
danielk1977a8858102004-05-28 12:11:21 +00002456 if( isView && pTab->pSelect==0 ){
2457 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2458 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002459 }
danielk1977a8858102004-05-28 12:11:21 +00002460 if( !isView && pTab->pSelect ){
2461 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2462 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002463 }
danielk1977576ec6b2005-01-21 11:55:25 +00002464#endif
drh75897232000-05-29 14:26:00 +00002465
drh1ccde152000-06-17 13:12:39 +00002466 /* Generate code to remove the table from the master table
2467 ** on disk.
2468 */
danielk19774adee202004-05-08 08:23:19 +00002469 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002470 if( v ){
drh77658e22007-12-04 16:54:52 +00002471 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002472 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002473 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002474 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002475 }
danielk1977a8858102004-05-28 12:11:21 +00002476
2477exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002478 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002479}
2480
2481/*
drhc2eef3b2002-08-31 18:53:06 +00002482** This routine is called to create a new foreign key on the table
2483** currently under construction. pFromCol determines which columns
2484** in the current table point to the foreign key. If pFromCol==0 then
2485** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002486** the table referred to (a.k.a the "parent" table). pToCol is a list
2487** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002488** information about the conflict resolution algorithms specified
2489** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2490**
2491** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002492** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002493**
2494** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002495** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002496*/
danielk19774adee202004-05-08 08:23:19 +00002497void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002498 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002499 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002500 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002501 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002502 int flags /* Conflict resolution algorithms. */
2503){
danielk197718576932008-08-06 13:47:40 +00002504 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002505#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002506 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002507 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002508 Table *p = pParse->pNewTable;
2509 int nByte;
2510 int i;
2511 int nCol;
2512 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002513
2514 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002515 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002516 if( pFromCol==0 ){
2517 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002518 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002519 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002520 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002521 " should reference only one column of table %T",
2522 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002523 goto fk_end;
2524 }
2525 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002526 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002527 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002528 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002529 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002530 goto fk_end;
2531 }else{
danielk19770202b292004-06-09 09:55:16 +00002532 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002533 }
drhe61922a2009-05-02 13:29:37 +00002534 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002535 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002536 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002537 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002538 }
2539 }
drh633e6d52008-07-28 19:34:53 +00002540 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002541 if( pFKey==0 ){
2542 goto fk_end;
2543 }
drhc2eef3b2002-08-31 18:53:06 +00002544 pFKey->pFrom = p;
2545 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002546 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002547 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002548 memcpy(z, pTo->z, pTo->n);
2549 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002550 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002551 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002552 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002553 if( pFromCol==0 ){
2554 pFKey->aCol[0].iFrom = p->nCol-1;
2555 }else{
2556 for(i=0; i<nCol; i++){
2557 int j;
2558 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002559 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002560 pFKey->aCol[i].iFrom = j;
2561 break;
2562 }
2563 }
2564 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002565 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002566 "unknown column \"%s\" in foreign key definition",
2567 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002568 goto fk_end;
2569 }
2570 }
2571 }
2572 if( pToCol ){
2573 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002574 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002575 pFKey->aCol[i].zCol = z;
2576 memcpy(z, pToCol->a[i].zName, n);
2577 z[n] = 0;
2578 z += n+1;
2579 }
2580 }
2581 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002582 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2583 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002584
drh21206082011-04-04 18:22:02 +00002585 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002586 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2587 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2588 );
danf59c5ca2009-09-22 16:55:38 +00002589 if( pNextTo==pFKey ){
2590 db->mallocFailed = 1;
2591 goto fk_end;
2592 }
dan1da40a32009-09-19 17:00:31 +00002593 if( pNextTo ){
2594 assert( pNextTo->pPrevTo==0 );
2595 pFKey->pNextTo = pNextTo;
2596 pNextTo->pPrevTo = pFKey;
2597 }
2598
drhc2eef3b2002-08-31 18:53:06 +00002599 /* Link the foreign key to the table as the last step.
2600 */
2601 p->pFKey = pFKey;
2602 pFKey = 0;
2603
2604fk_end:
drh633e6d52008-07-28 19:34:53 +00002605 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002606#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002607 sqlite3ExprListDelete(db, pFromCol);
2608 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002609}
2610
2611/*
2612** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2613** clause is seen as part of a foreign key definition. The isDeferred
2614** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2615** The behavior of the most recently created foreign key is adjusted
2616** accordingly.
2617*/
danielk19774adee202004-05-08 08:23:19 +00002618void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002619#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002620 Table *pTab;
2621 FKey *pFKey;
2622 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002623 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002624 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002625#endif
drhc2eef3b2002-08-31 18:53:06 +00002626}
2627
2628/*
drh063336a2004-11-05 20:58:39 +00002629** Generate code that will erase and refill index *pIdx. This is
2630** used to initialize a newly created index or to recompute the
2631** content of an index in response to a REINDEX command.
2632**
2633** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002634** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002635** root page number of the index. If memRootPage is negative, then
2636** the index already exists and must be cleared before being refilled and
2637** the root page number of the index is taken from pIndex->tnum.
2638*/
2639static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2640 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002641 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2642 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002643 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002644 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002645 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002646 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002647 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002648 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002649 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002650 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002651 sqlite3 *db = pParse->db; /* The database connection */
2652 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002653
danielk19771d54df82004-11-23 15:41:16 +00002654#ifndef SQLITE_OMIT_AUTHORIZATION
2655 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002656 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002657 return;
2658 }
2659#endif
2660
danielk1977c00da102006-01-07 13:21:04 +00002661 /* Require a write-lock on the table to perform this operation */
2662 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2663
drh063336a2004-11-05 20:58:39 +00002664 v = sqlite3GetVdbe(pParse);
2665 if( v==0 ) return;
2666 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002667 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002668 }else{
2669 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002670 }
drh2ec2fb22013-11-06 19:59:23 +00002671 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002672
dan689ab892011-08-12 15:02:00 +00002673 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002674 iSorter = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00002675 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
2676 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002677
2678 /* Open the table. Loop through all rows of the table, inserting index
2679 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002680 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002681 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002682 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002683
drh1c2c0b72014-01-04 19:27:05 +00002684 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002685 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002686 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002687 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002688 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002689 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2690 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002691 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002692 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2693
drh688852a2014-02-17 22:40:43 +00002694 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002695 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
2696 if( pIndex->onError!=OE_None && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002697 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2698 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2699 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002700 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drh688852a2014-02-17 22:40:43 +00002701 pKey->nField - pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002702 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002703 }else{
2704 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002705 }
drhca892a72011-09-03 00:17:51 +00002706 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2707 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2708 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002709 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002710 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002711 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002712
drh66a51672008-01-03 00:01:23 +00002713 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2714 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002715 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002716}
2717
2718/*
drh77e57df2013-10-22 14:28:02 +00002719** Allocate heap space to hold an Index object with nCol columns.
2720**
2721** Increase the allocation size to provide an extra nExtra bytes
2722** of 8-byte aligned space after the Index object and return a
2723** pointer to this extra space in *ppExtra.
2724*/
2725Index *sqlite3AllocateIndexObject(
2726 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002727 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002728 int nExtra, /* Number of bytes of extra space to alloc */
2729 char **ppExtra /* Pointer to the "extra" space */
2730){
2731 Index *p; /* Allocated index object */
2732 int nByte; /* Bytes of space for Index object + arrays */
2733
2734 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2735 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002736 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002737 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002738 sizeof(u8)*nCol); /* Index.aSortOrder */
2739 p = sqlite3DbMallocZero(db, nByte + nExtra);
2740 if( p ){
2741 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002742 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2743 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2744 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002745 p->aSortOrder = (u8*)pExtra;
2746 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002747 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002748 *ppExtra = ((char*)p) + nByte;
2749 }
2750 return p;
2751}
2752
2753/*
drh23bf66d2004-12-14 03:34:34 +00002754** Create a new index for an SQL table. pName1.pName2 is the name of the index
2755** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002756** be NULL for a primary key or an index that is created to satisfy a
2757** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002758** as the table to be indexed. pParse->pNewTable is a table that is
2759** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002760**
drh382c0242001-10-06 16:33:02 +00002761** pList is a list of columns to be indexed. pList will be NULL if this
2762** is a primary key or unique-constraint on the most recent column added
2763** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002764**
2765** If the index is created successfully, return a pointer to the new Index
2766** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2767** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002768*/
dan1da40a32009-09-19 17:00:31 +00002769Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002770 Parse *pParse, /* All information about this parse */
2771 Token *pName1, /* First part of index name. May be NULL */
2772 Token *pName2, /* Second part of index name. May be NULL */
2773 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002774 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002775 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002776 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002777 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002778 int sortOrder, /* Sort order of primary key when pList==NULL */
2779 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002780){
dan1da40a32009-09-19 17:00:31 +00002781 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002782 Table *pTab = 0; /* Table to be indexed */
2783 Index *pIndex = 0; /* The index to be created */
2784 char *zName = 0; /* Name of the index */
2785 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002786 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002787 DbFixer sFix; /* For assigning database names to pTable */
2788 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002789 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002790 Db *pDb; /* The specific table containing the indexed database */
2791 int iDb; /* Index of the database that is being written */
2792 Token *pName = 0; /* Unqualified name of the index to create */
2793 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002794 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002795 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002796 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002797 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002798 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002799
drh8af73d42009-05-13 22:58:28 +00002800 assert( pParse->nErr==0 ); /* Never called with prior errors */
2801 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002802 goto exit_create_index;
2803 }
2804 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002805 goto exit_create_index;
2806 }
drhdaffd0e2001-04-11 14:28:42 +00002807
drh75897232000-05-29 14:26:00 +00002808 /*
2809 ** Find the table that is to be indexed. Return early if not found.
2810 */
danielk1977cbb18d22004-05-28 11:37:27 +00002811 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002812
2813 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002814 ** to search for the table. 'Fix' the table name to this db
2815 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002816 */
2817 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002818 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002819 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002820 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002821
danielk197753c0f742005-03-29 03:10:59 +00002822#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002823 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002824 ** is a temp table. If so, set the database to 1. Do not do this
2825 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002826 */
danielk1977fe910332007-12-02 11:46:34 +00002827 if( !db->init.busy ){
2828 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002829 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002830 iDb = 1;
2831 }
danielk1977ef2cb632004-05-29 02:37:19 +00002832 }
danielk197753c0f742005-03-29 03:10:59 +00002833#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002834
drhd100f692013-10-03 15:39:44 +00002835 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2836 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002837 /* Because the parser constructs pTblName from a single identifier,
2838 ** sqlite3FixSrcList can never fail. */
2839 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002840 }
dan41fb5cd2012-10-04 19:33:00 +00002841 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002842 assert( db->mallocFailed==0 || pTab==0 );
2843 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002844 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2845 sqlite3ErrorMsg(pParse,
2846 "cannot create a TEMP index on non-TEMP table \"%s\"",
2847 pTab->zName);
2848 goto exit_create_index;
2849 }
drh44156282013-10-23 22:23:03 +00002850 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002851 }else{
drhe3c41372001-09-17 20:25:58 +00002852 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002853 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002854 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002855 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002856 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002857 }
drhfdd6e852005-12-16 01:06:16 +00002858 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002859
drhd3001712009-05-12 17:46:53 +00002860 assert( pTab!=0 );
2861 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002862 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh503a6862013-03-01 01:07:17 +00002863 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002864 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002865 goto exit_create_index;
2866 }
danielk1977576ec6b2005-01-21 11:55:25 +00002867#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002868 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002869 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002870 goto exit_create_index;
2871 }
danielk1977576ec6b2005-01-21 11:55:25 +00002872#endif
danielk19775ee9d692006-06-21 12:36:25 +00002873#ifndef SQLITE_OMIT_VIRTUALTABLE
2874 if( IsVirtual(pTab) ){
2875 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2876 goto exit_create_index;
2877 }
2878#endif
drh75897232000-05-29 14:26:00 +00002879
2880 /*
2881 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002882 ** index or table with the same name.
2883 **
2884 ** Exception: If we are reading the names of permanent indices from the
2885 ** sqlite_master table (because some other process changed the schema) and
2886 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002887 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002888 **
2889 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002890 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2891 ** own name.
drh75897232000-05-29 14:26:00 +00002892 */
danielk1977d8123362004-06-12 09:25:12 +00002893 if( pName ){
drh17435752007-08-16 04:30:38 +00002894 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002895 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002896 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002897 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002898 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002899 }
danielk1977d8123362004-06-12 09:25:12 +00002900 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002901 if( sqlite3FindTable(db, zName, 0)!=0 ){
2902 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2903 goto exit_create_index;
2904 }
2905 }
danielk197759a33f92007-03-17 10:26:59 +00002906 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2907 if( !ifNotExist ){
2908 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002909 }else{
2910 assert( !db->init.busy );
2911 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002912 }
danielk197759a33f92007-03-17 10:26:59 +00002913 goto exit_create_index;
2914 }
danielk1977a21c6b62005-01-24 10:25:59 +00002915 }else{
drhadbca9c2001-09-27 15:11:53 +00002916 int n;
2917 Index *pLoop;
2918 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002919 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002920 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002921 goto exit_create_index;
2922 }
drh75897232000-05-29 14:26:00 +00002923 }
2924
drhe5f9c642003-01-13 23:27:31 +00002925 /* Check for authorization to create an index.
2926 */
2927#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002928 {
drhfdd6e852005-12-16 01:06:16 +00002929 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002930 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002931 goto exit_create_index;
2932 }
2933 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002934 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002935 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002936 goto exit_create_index;
2937 }
drhe5f9c642003-01-13 23:27:31 +00002938 }
2939#endif
2940
drh75897232000-05-29 14:26:00 +00002941 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002942 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002943 ** So create a fake list to simulate this.
2944 */
2945 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002946 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002947 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002948 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2949 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00002950 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002951 }
2952
danielk1977b3bf5562006-01-10 17:58:23 +00002953 /* Figure out how many bytes of space are required to store explicitly
2954 ** specified collation sequence names.
2955 */
2956 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002957 Expr *pExpr = pList->a[i].pExpr;
2958 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00002959 assert( pExpr->op==TK_COLLATE );
2960 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00002961 }
2962 }
2963
drh75897232000-05-29 14:26:00 +00002964 /*
2965 ** Allocate the index structure.
2966 */
drhea678832008-12-10 19:26:22 +00002967 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00002968 nExtraCol = pPk ? pPk->nKeyCol : 1;
2969 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00002970 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00002971 if( db->mallocFailed ){
2972 goto exit_create_index;
2973 }
dancfc9df72014-04-25 15:01:01 +00002974 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00002975 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00002976 pIndex->zName = zExtra;
2977 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00002978 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002979 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00002980 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00002981 pIndex->uniqNotNull = onError!=OE_None;
drh1bd10f82008-12-10 21:19:56 +00002982 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002983 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00002984 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00002985 if( pPIWhere ){
2986 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
2987 pIndex->pPartIdxWhere = pPIWhere;
2988 pPIWhere = 0;
2989 }
drh21206082011-04-04 18:22:02 +00002990 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002991
drhfdd6e852005-12-16 01:06:16 +00002992 /* Check to see if we should honor DESC requests on index columns
2993 */
danielk1977da184232006-01-05 11:34:32 +00002994 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002995 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002996 }else{
2997 sortOrderMask = 0; /* Ignore DESC */
2998 }
2999
drh1ccde152000-06-17 13:12:39 +00003000 /* Scan the names of the columns of the table to be indexed and
3001 ** load the column indices into the Index structure. Report an error
3002 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003003 **
3004 ** TODO: Add a test to make sure that the same column is not named
3005 ** more than once within the same index. Only the first instance of
3006 ** the column will ever be used by the optimizer. Note that using the
3007 ** same column more than once cannot be an error because that would
3008 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003009 */
drhfdd6e852005-12-16 01:06:16 +00003010 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3011 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003012 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003013 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003014
drhfdd6e852005-12-16 01:06:16 +00003015 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3016 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003017 }
3018 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003019 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003020 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003021 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003022 goto exit_create_index;
3023 }
drhbbbdc832013-10-22 18:01:40 +00003024 assert( pTab->nCol<=0x7fff && j<=0x7fff );
3025 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003026 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003027 int nColl;
dan911ce412013-05-15 15:16:50 +00003028 assert( pListItem->pExpr->op==TK_COLLATE );
3029 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003030 nColl = sqlite3Strlen30(zColl) + 1;
3031 assert( nExtra>=nColl );
3032 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003033 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003034 zExtra += nColl;
3035 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003036 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003037 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003038 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003039 }
drhb7f24de2009-05-13 17:35:23 +00003040 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003041 goto exit_create_index;
3042 }
danielk1977b3bf5562006-01-10 17:58:23 +00003043 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003044 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003045 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003046 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003047 }
drh44156282013-10-23 22:23:03 +00003048 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003049 for(j=0; j<pPk->nKeyCol; j++){
3050 int x = pPk->aiColumn[j];
3051 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3052 pIndex->nColumn--;
3053 }else{
3054 pIndex->aiColumn[i] = x;
3055 pIndex->azColl[i] = pPk->azColl[j];
3056 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3057 i++;
3058 }
drh44156282013-10-23 22:23:03 +00003059 }
drh7913e412013-11-01 20:30:36 +00003060 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003061 }else{
3062 pIndex->aiColumn[i] = -1;
3063 pIndex->azColl[i] = "BINARY";
3064 }
drh51147ba2005-07-23 22:59:55 +00003065 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003066 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003067
danielk1977d8123362004-06-12 09:25:12 +00003068 if( pTab==pParse->pNewTable ){
3069 /* This routine has been called to create an automatic index as a
3070 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3071 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3072 ** i.e. one of:
3073 **
3074 ** CREATE TABLE t(x PRIMARY KEY, y);
3075 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3076 **
3077 ** Either way, check to see if the table already has such an index. If
3078 ** so, don't bother creating this one. This only applies to
3079 ** automatically created indices. Users can do as they wish with
3080 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003081 **
3082 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3083 ** (and thus suppressing the second one) even if they have different
3084 ** sort orders.
3085 **
3086 ** If there are different collating sequences or if the columns of
3087 ** the constraint occur in different orders, then the constraints are
3088 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003089 */
3090 Index *pIdx;
3091 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3092 int k;
3093 assert( pIdx->onError!=OE_None );
3094 assert( pIdx->autoIndex );
3095 assert( pIndex->onError!=OE_None );
3096
drhbbbdc832013-10-22 18:01:40 +00003097 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3098 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003099 const char *z1;
3100 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003101 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003102 z1 = pIdx->azColl[k];
3103 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003104 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003105 }
drhbbbdc832013-10-22 18:01:40 +00003106 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003107 if( pIdx->onError!=pIndex->onError ){
3108 /* This constraint creates the same index as a previous
3109 ** constraint specified somewhere in the CREATE TABLE statement.
3110 ** However the ON CONFLICT clauses are different. If both this
3111 ** constraint and the previous equivalent constraint have explicit
3112 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003113 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003114 */
3115 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3116 sqlite3ErrorMsg(pParse,
3117 "conflicting ON CONFLICT clauses specified", 0);
3118 }
3119 if( pIdx->onError==OE_Default ){
3120 pIdx->onError = pIndex->onError;
3121 }
3122 }
danielk1977d8123362004-06-12 09:25:12 +00003123 goto exit_create_index;
3124 }
3125 }
3126 }
3127
drh75897232000-05-29 14:26:00 +00003128 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003129 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003130 */
drh234c39d2004-07-24 03:30:47 +00003131 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003132 Index *p;
drh21206082011-04-04 18:22:02 +00003133 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003134 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00003135 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00003136 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003137 if( p ){
3138 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003139 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003140 goto exit_create_index;
3141 }
drh5e00f6c2001-09-13 13:46:56 +00003142 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003143 if( pTblName!=0 ){
3144 pIndex->tnum = db->init.newTnum;
3145 }
drhd78eeee2001-09-13 16:18:53 +00003146 }
3147
drh58383402013-11-04 17:00:50 +00003148 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3149 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3150 ** emit code to allocate the index rootpage on disk and make an entry for
3151 ** the index in the sqlite_master table and populate the index with
3152 ** content. But, do not do this if we are simply reading the sqlite_master
3153 ** table to parse the schema, or if this index is the PRIMARY KEY index
3154 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003155 **
drh58383402013-11-04 17:00:50 +00003156 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3157 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003158 ** has just been created, it contains no data and the index initialization
3159 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003160 */
drh58383402013-11-04 17:00:50 +00003161 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003162 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003163 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003164 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003165
danielk19774adee202004-05-08 08:23:19 +00003166 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003167 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003168
drhfdd6e852005-12-16 01:06:16 +00003169
drh063336a2004-11-05 20:58:39 +00003170 /* Create the rootpage for the index
3171 */
drhaee128d2005-02-14 20:48:18 +00003172 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003173 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003174
3175 /* Gather the complete text of the CREATE INDEX statement into
3176 ** the zStmt variable
3177 */
drhd3001712009-05-12 17:46:53 +00003178 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003179 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003180 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003181 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003182 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003183 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003184 }else{
3185 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003186 /* zStmt = sqlite3MPrintf(""); */
3187 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003188 }
drh063336a2004-11-05 20:58:39 +00003189
3190 /* Add an entry in sqlite_master for this index
3191 */
3192 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003193 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003194 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3195 pIndex->zName,
3196 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003197 iMem,
drh063336a2004-11-05 20:58:39 +00003198 zStmt
3199 );
drh633e6d52008-07-28 19:34:53 +00003200 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003201
danielk1977a21c6b62005-01-24 10:25:59 +00003202 /* Fill the index with data and reparse the schema. Code an OP_Expire
3203 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003204 */
danielk1977cbb18d22004-05-28 11:37:27 +00003205 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003206 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003207 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003208 sqlite3VdbeAddParseSchemaOp(v, iDb,
3209 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003210 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003211 }
drh75897232000-05-29 14:26:00 +00003212 }
3213
danielk1977d8123362004-06-12 09:25:12 +00003214 /* When adding an index to the list of indices for a table, make
3215 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003216 ** OE_Ignore. This is necessary for the correct constraint check
3217 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3218 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003219 */
drh234c39d2004-07-24 03:30:47 +00003220 if( db->init.busy || pTblName==0 ){
3221 if( onError!=OE_Replace || pTab->pIndex==0
3222 || pTab->pIndex->onError==OE_Replace){
3223 pIndex->pNext = pTab->pIndex;
3224 pTab->pIndex = pIndex;
3225 }else{
3226 Index *pOther = pTab->pIndex;
3227 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3228 pOther = pOther->pNext;
3229 }
3230 pIndex->pNext = pOther->pNext;
3231 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003232 }
dan1da40a32009-09-19 17:00:31 +00003233 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003234 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003235 }
danielk1977d8123362004-06-12 09:25:12 +00003236
drh75897232000-05-29 14:26:00 +00003237 /* Clean up before exiting */
3238exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003239 if( pIndex ) freeIndex(db, pIndex);
3240 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003241 sqlite3ExprListDelete(db, pList);
3242 sqlite3SrcListDelete(db, pTblName);
3243 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003244 return pRet;
drh75897232000-05-29 14:26:00 +00003245}
3246
3247/*
drh51147ba2005-07-23 22:59:55 +00003248** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003249** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003250**
3251** aiRowEst[0] is suppose to contain the number of elements in the index.
3252** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3253** number of rows in the table that match any particular value of the
3254** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003255** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003256** of the index. And so forth. It must always be the case that
3257*
3258** aiRowEst[N]<=aiRowEst[N-1]
3259** aiRowEst[N]>=1
3260**
3261** Apart from that, we have little to go on besides intuition as to
3262** how aiRowEst[] should be initialized. The numbers generated here
3263** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003264*/
3265void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003266 /* 10, 9, 8, 7, 6 */
3267 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003268 LogEst *a = pIdx->aiRowLogEst;
3269 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
dan264d2b92014-04-29 19:01:57 +00003270 int i;
dancfc9df72014-04-25 15:01:01 +00003271
dan264d2b92014-04-29 19:01:57 +00003272 /* Set the first entry (number of rows in the index) to the estimated
3273 ** number of rows in the table. Or 10, if the estimated number of rows
3274 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003275 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003276 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3277
3278 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3279 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003280 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003281 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3282 a[i] = 23; assert( 23==sqlite3LogEst(5) );
dancfc9df72014-04-25 15:01:01 +00003283 }
dan264d2b92014-04-29 19:01:57 +00003284
3285 assert( 0==sqlite3LogEst(1) );
3286 if( pIdx->onError!=OE_None ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003287}
3288
3289/*
drh74e24cd2002-01-09 03:19:59 +00003290** This routine will drop an existing named index. This routine
3291** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003292*/
drh4d91a702006-01-04 15:54:36 +00003293void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003294 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003295 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003296 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003297 int iDb;
drh75897232000-05-29 14:26:00 +00003298
drh8af73d42009-05-13 22:58:28 +00003299 assert( pParse->nErr==0 ); /* Never called with prior errors */
3300 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003301 goto exit_drop_index;
3302 }
drhd24cc422003-03-27 12:51:24 +00003303 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003304 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3305 goto exit_drop_index;
3306 }
danielk19774adee202004-05-08 08:23:19 +00003307 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003308 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003309 if( !ifExists ){
3310 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003311 }else{
3312 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003313 }
drha6ecd332004-06-10 00:29:09 +00003314 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003315 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003316 }
drh485b39b2002-07-13 03:11:52 +00003317 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00003318 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003319 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003320 goto exit_drop_index;
3321 }
danielk1977da184232006-01-05 11:34:32 +00003322 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003323#ifndef SQLITE_OMIT_AUTHORIZATION
3324 {
3325 int code = SQLITE_DROP_INDEX;
3326 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003327 const char *zDb = db->aDb[iDb].zName;
3328 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003329 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003330 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003331 }
danielk1977da184232006-01-05 11:34:32 +00003332 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003333 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003334 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003335 }
drhed6c8672003-01-12 18:02:16 +00003336 }
drhe5f9c642003-01-13 23:27:31 +00003337#endif
drh75897232000-05-29 14:26:00 +00003338
3339 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003340 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003341 if( v ){
drh77658e22007-12-04 16:54:52 +00003342 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003343 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003344 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003345 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003346 );
drha5ae4c32011-08-07 01:31:52 +00003347 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003348 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003349 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003350 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003351 }
3352
drhd24cc422003-03-27 12:51:24 +00003353exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003354 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003355}
3356
3357/*
dan9ace1122012-03-29 07:51:45 +00003358** pArray is a pointer to an array of objects. Each object in the
3359** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3360** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003361**
dan9ace1122012-03-29 07:51:45 +00003362** When this function is called, *pnEntry contains the current size of
3363** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3364** in total).
drh13449892005-09-07 21:22:45 +00003365**
dan9ace1122012-03-29 07:51:45 +00003366** If the realloc() is successful (i.e. if no OOM condition occurs), the
3367** space allocated for the new object is zeroed, *pnEntry updated to
3368** reflect the new size of the array and a pointer to the new allocation
3369** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003370**
dan9ace1122012-03-29 07:51:45 +00003371** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3372** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003373*/
drhcf643722007-03-27 13:36:37 +00003374void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003375 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003376 void *pArray, /* Array of objects. Might be reallocated */
3377 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003378 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003379 int *pIdx /* Write the index of a new slot here */
3380){
3381 char *z;
drh6c535152012-02-02 03:38:30 +00003382 int n = *pnEntry;
3383 if( (n & (n-1))==0 ){
3384 int sz = (n==0) ? 1 : 2*n;
3385 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003386 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003387 *pIdx = -1;
3388 return pArray;
drh13449892005-09-07 21:22:45 +00003389 }
drhcf643722007-03-27 13:36:37 +00003390 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003391 }
drhcf643722007-03-27 13:36:37 +00003392 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003393 memset(&z[n * szEntry], 0, szEntry);
3394 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003395 ++*pnEntry;
3396 return pArray;
drh13449892005-09-07 21:22:45 +00003397}
3398
3399/*
drh75897232000-05-29 14:26:00 +00003400** Append a new element to the given IdList. Create a new IdList if
3401** need be.
drhdaffd0e2001-04-11 14:28:42 +00003402**
3403** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003404*/
drh17435752007-08-16 04:30:38 +00003405IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003406 int i;
drh75897232000-05-29 14:26:00 +00003407 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003408 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003409 if( pList==0 ) return 0;
3410 }
drhcf643722007-03-27 13:36:37 +00003411 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003412 db,
drhcf643722007-03-27 13:36:37 +00003413 pList->a,
3414 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003415 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003416 &i
3417 );
drh13449892005-09-07 21:22:45 +00003418 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003419 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003420 return 0;
drh75897232000-05-29 14:26:00 +00003421 }
drh17435752007-08-16 04:30:38 +00003422 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003423 return pList;
3424}
3425
3426/*
drhfe05af82005-07-21 03:14:59 +00003427** Delete an IdList.
3428*/
drh633e6d52008-07-28 19:34:53 +00003429void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003430 int i;
3431 if( pList==0 ) return;
3432 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003433 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003434 }
drh633e6d52008-07-28 19:34:53 +00003435 sqlite3DbFree(db, pList->a);
3436 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003437}
3438
3439/*
3440** Return the index in pList of the identifier named zId. Return -1
3441** if not found.
3442*/
3443int sqlite3IdListIndex(IdList *pList, const char *zName){
3444 int i;
3445 if( pList==0 ) return -1;
3446 for(i=0; i<pList->nId; i++){
3447 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3448 }
3449 return -1;
3450}
3451
3452/*
drha78c22c2008-11-11 18:28:58 +00003453** Expand the space allocated for the given SrcList object by
3454** creating nExtra new slots beginning at iStart. iStart is zero based.
3455** New slots are zeroed.
3456**
3457** For example, suppose a SrcList initially contains two entries: A,B.
3458** To append 3 new entries onto the end, do this:
3459**
3460** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3461**
3462** After the call above it would contain: A, B, nil, nil, nil.
3463** If the iStart argument had been 1 instead of 2, then the result
3464** would have been: A, nil, nil, nil, B. To prepend the new slots,
3465** the iStart value would be 0. The result then would
3466** be: nil, nil, nil, A, B.
3467**
3468** If a memory allocation fails the SrcList is unchanged. The
3469** db->mallocFailed flag will be set to true.
3470*/
3471SrcList *sqlite3SrcListEnlarge(
3472 sqlite3 *db, /* Database connection to notify of OOM errors */
3473 SrcList *pSrc, /* The SrcList to be enlarged */
3474 int nExtra, /* Number of new slots to add to pSrc->a[] */
3475 int iStart /* Index in pSrc->a[] of first new slot */
3476){
3477 int i;
3478
3479 /* Sanity checking on calling parameters */
3480 assert( iStart>=0 );
3481 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003482 assert( pSrc!=0 );
3483 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003484
3485 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003486 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003487 SrcList *pNew;
3488 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003489 int nGot;
drha78c22c2008-11-11 18:28:58 +00003490 pNew = sqlite3DbRealloc(db, pSrc,
3491 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3492 if( pNew==0 ){
3493 assert( db->mallocFailed );
3494 return pSrc;
3495 }
3496 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003497 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003498 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003499 }
3500
3501 /* Move existing slots that come after the newly inserted slots
3502 ** out of the way */
3503 for(i=pSrc->nSrc-1; i>=iStart; i--){
3504 pSrc->a[i+nExtra] = pSrc->a[i];
3505 }
drh6d1626e2014-03-05 15:52:43 +00003506 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003507
3508 /* Zero the newly allocated slots */
3509 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3510 for(i=iStart; i<iStart+nExtra; i++){
3511 pSrc->a[i].iCursor = -1;
3512 }
3513
3514 /* Return a pointer to the enlarged SrcList */
3515 return pSrc;
3516}
3517
3518
3519/*
drhad3cab52002-05-24 02:04:32 +00003520** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003521** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003522**
drha78c22c2008-11-11 18:28:58 +00003523** A SrcList is returned, or NULL if there is an OOM error. The returned
3524** SrcList might be the same as the SrcList that was input or it might be
3525** a new one. If an OOM error does occurs, then the prior value of pList
3526** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003527**
3528** If pDatabase is not null, it means that the table has an optional
3529** database name prefix. Like this: "database.table". The pDatabase
3530** points to the table name and the pTable points to the database name.
3531** The SrcList.a[].zName field is filled with the table name which might
3532** come from pTable (if pDatabase is NULL) or from pDatabase.
3533** SrcList.a[].zDatabase is filled with the database name from pTable,
3534** or with NULL if no database is specified.
3535**
3536** In other words, if call like this:
3537**
drh17435752007-08-16 04:30:38 +00003538** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003539**
3540** Then B is a table name and the database name is unspecified. If called
3541** like this:
3542**
drh17435752007-08-16 04:30:38 +00003543** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003544**
drhd3001712009-05-12 17:46:53 +00003545** Then C is the table name and B is the database name. If C is defined
3546** then so is B. In other words, we never have a case where:
3547**
3548** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003549**
3550** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3551** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003552*/
drh17435752007-08-16 04:30:38 +00003553SrcList *sqlite3SrcListAppend(
3554 sqlite3 *db, /* Connection to notify of malloc failures */
3555 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3556 Token *pTable, /* Table to append */
3557 Token *pDatabase /* Database of the table */
3558){
drha99db3b2004-06-19 14:49:12 +00003559 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003560 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003561 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003562 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003563 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003564 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003565 }
drha78c22c2008-11-11 18:28:58 +00003566 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3567 if( db->mallocFailed ){
3568 sqlite3SrcListDelete(db, pList);
3569 return 0;
drhad3cab52002-05-24 02:04:32 +00003570 }
drha78c22c2008-11-11 18:28:58 +00003571 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003572 if( pDatabase && pDatabase->z==0 ){
3573 pDatabase = 0;
3574 }
drhd3001712009-05-12 17:46:53 +00003575 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003576 Token *pTemp = pDatabase;
3577 pDatabase = pTable;
3578 pTable = pTemp;
3579 }
drh17435752007-08-16 04:30:38 +00003580 pItem->zName = sqlite3NameFromToken(db, pTable);
3581 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003582 return pList;
3583}
3584
3585/*
drhdfe88ec2008-11-03 20:55:06 +00003586** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003587*/
danielk19774adee202004-05-08 08:23:19 +00003588void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003589 int i;
drh9b3187e2005-01-18 14:45:47 +00003590 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003591 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003592 if( pList ){
3593 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3594 if( pItem->iCursor>=0 ) break;
3595 pItem->iCursor = pParse->nTab++;
3596 if( pItem->pSelect ){
3597 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3598 }
drh63eb5f22003-04-29 16:20:44 +00003599 }
3600 }
3601}
3602
3603/*
drhad3cab52002-05-24 02:04:32 +00003604** Delete an entire SrcList including all its substructure.
3605*/
drh633e6d52008-07-28 19:34:53 +00003606void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003607 int i;
drhbe5c89a2004-07-26 00:31:09 +00003608 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003609 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003610 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003611 sqlite3DbFree(db, pItem->zDatabase);
3612 sqlite3DbFree(db, pItem->zName);
3613 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003614 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003615 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003616 sqlite3SelectDelete(db, pItem->pSelect);
3617 sqlite3ExprDelete(db, pItem->pOn);
3618 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003619 }
drh633e6d52008-07-28 19:34:53 +00003620 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003621}
3622
drh982cef72000-05-30 16:27:03 +00003623/*
drh61dfc312006-12-16 16:25:15 +00003624** This routine is called by the parser to add a new term to the
3625** end of a growing FROM clause. The "p" parameter is the part of
3626** the FROM clause that has already been constructed. "p" is NULL
3627** if this is the first term of the FROM clause. pTable and pDatabase
3628** are the name of the table and database named in the FROM clause term.
3629** pDatabase is NULL if the database name qualifier is missing - the
3630** usual case. If the term has a alias, then pAlias points to the
3631** alias token. If the term is a subquery, then pSubquery is the
3632** SELECT statement that the subquery encodes. The pTable and
3633** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3634** parameters are the content of the ON and USING clauses.
3635**
3636** Return a new SrcList which encodes is the FROM with the new
3637** term added.
3638*/
3639SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003640 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003641 SrcList *p, /* The left part of the FROM clause already seen */
3642 Token *pTable, /* Name of the table to add to the FROM clause */
3643 Token *pDatabase, /* Name of the database containing pTable */
3644 Token *pAlias, /* The right-hand side of the AS subexpression */
3645 Select *pSubquery, /* A subquery used in place of a table name */
3646 Expr *pOn, /* The ON clause of a join */
3647 IdList *pUsing /* The USING clause of a join */
3648){
3649 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003650 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003651 if( !p && (pOn || pUsing) ){
3652 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3653 (pOn ? "ON" : "USING")
3654 );
3655 goto append_from_error;
3656 }
drh17435752007-08-16 04:30:38 +00003657 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003658 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003659 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003660 }
3661 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003662 assert( pAlias!=0 );
3663 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003664 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003665 }
3666 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003667 pItem->pOn = pOn;
3668 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003669 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003670
3671 append_from_error:
3672 assert( p==0 );
3673 sqlite3ExprDelete(db, pOn);
3674 sqlite3IdListDelete(db, pUsing);
3675 sqlite3SelectDelete(db, pSubquery);
3676 return 0;
drh61dfc312006-12-16 16:25:15 +00003677}
3678
3679/*
danielk1977b1c685b2008-10-06 16:18:39 +00003680** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3681** element of the source-list passed as the second argument.
3682*/
3683void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003684 assert( pIndexedBy!=0 );
3685 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003686 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3687 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3688 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3689 /* A "NOT INDEXED" clause was supplied. See parse.y
3690 ** construct "indexed_opt" for details. */
3691 pItem->notIndexed = 1;
3692 }else{
3693 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3694 }
3695 }
3696}
3697
3698/*
drh61dfc312006-12-16 16:25:15 +00003699** When building up a FROM clause in the parser, the join operator
3700** is initially attached to the left operand. But the code generator
3701** expects the join operator to be on the right operand. This routine
3702** Shifts all join operators from left to right for an entire FROM
3703** clause.
3704**
3705** Example: Suppose the join is like this:
3706**
3707** A natural cross join B
3708**
3709** The operator is "natural cross join". The A and B operands are stored
3710** in p->a[0] and p->a[1], respectively. The parser initially stores the
3711** operator with A. This routine shifts that operator over to B.
3712*/
3713void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003714 if( p ){
drh61dfc312006-12-16 16:25:15 +00003715 int i;
drhd017ab92011-08-23 00:01:58 +00003716 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003717 for(i=p->nSrc-1; i>0; i--){
3718 p->a[i].jointype = p->a[i-1].jointype;
3719 }
3720 p->a[0].jointype = 0;
3721 }
3722}
3723
3724/*
drhc4a3c772001-04-04 11:48:57 +00003725** Begin a transaction
3726*/
drh684917c2004-10-05 02:41:42 +00003727void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003728 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003729 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003730 int i;
drh5e00f6c2001-09-13 13:46:56 +00003731
drhd3001712009-05-12 17:46:53 +00003732 assert( pParse!=0 );
3733 db = pParse->db;
3734 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003735/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003736 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3737 return;
3738 }
danielk19771d850a72004-05-31 08:26:49 +00003739 v = sqlite3GetVdbe(pParse);
3740 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003741 if( type!=TK_DEFERRED ){
3742 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003743 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003744 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003745 }
3746 }
drh66a51672008-01-03 00:01:23 +00003747 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003748}
3749
3750/*
3751** Commit a transaction
3752*/
danielk19774adee202004-05-08 08:23:19 +00003753void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003754 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003755
drhd3001712009-05-12 17:46:53 +00003756 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003757 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003758 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3759 return;
3760 }
danielk19771d850a72004-05-31 08:26:49 +00003761 v = sqlite3GetVdbe(pParse);
3762 if( v ){
drh66a51672008-01-03 00:01:23 +00003763 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003764 }
drhc4a3c772001-04-04 11:48:57 +00003765}
3766
3767/*
3768** Rollback a transaction
3769*/
danielk19774adee202004-05-08 08:23:19 +00003770void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003771 Vdbe *v;
3772
drhd3001712009-05-12 17:46:53 +00003773 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003774 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003775 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3776 return;
3777 }
danielk19774adee202004-05-08 08:23:19 +00003778 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003779 if( v ){
drh66a51672008-01-03 00:01:23 +00003780 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003781 }
drhc4a3c772001-04-04 11:48:57 +00003782}
drhf57b14a2001-09-14 18:54:08 +00003783
3784/*
danielk1977fd7f0452008-12-17 17:30:26 +00003785** This function is called by the parser when it parses a command to create,
3786** release or rollback an SQL savepoint.
3787*/
3788void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003789 char *zName = sqlite3NameFromToken(pParse->db, pName);
3790 if( zName ){
3791 Vdbe *v = sqlite3GetVdbe(pParse);
3792#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003793 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003794 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3795#endif
3796 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3797 sqlite3DbFree(pParse->db, zName);
3798 return;
3799 }
3800 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003801 }
3802}
3803
3804/*
drhdc3ff9c2004-08-18 02:10:15 +00003805** Make sure the TEMP database is open and available for use. Return
3806** the number of errors. Leave any error messages in the pParse structure.
3807*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003808int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003809 sqlite3 *db = pParse->db;
3810 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003811 int rc;
drh10a76c92010-01-26 01:25:26 +00003812 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003813 static const int flags =
3814 SQLITE_OPEN_READWRITE |
3815 SQLITE_OPEN_CREATE |
3816 SQLITE_OPEN_EXCLUSIVE |
3817 SQLITE_OPEN_DELETEONCLOSE |
3818 SQLITE_OPEN_TEMP_DB;
3819
dan3a6d8ae2011-04-23 15:54:54 +00003820 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003821 if( rc!=SQLITE_OK ){
3822 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3823 "file for storing temporary tables");
3824 pParse->rc = rc;
3825 return 1;
3826 }
drh10a76c92010-01-26 01:25:26 +00003827 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003828 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003829 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3830 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003831 return 1;
drh10a76c92010-01-26 01:25:26 +00003832 }
drhdc3ff9c2004-08-18 02:10:15 +00003833 }
3834 return 0;
3835}
3836
3837/*
drhaceb31b2014-02-08 01:40:27 +00003838** Record the fact that the schema cookie will need to be verified
3839** for database iDb. The code to actually verify the schema cookie
3840** will occur at the end of the top-level VDBE and will be generated
3841** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003842*/
danielk19774adee202004-05-08 08:23:19 +00003843void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003844 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003845 sqlite3 *db = pToplevel->db;
3846 yDbMask mask;
drh80242052004-06-09 00:48:12 +00003847
drhaceb31b2014-02-08 01:40:27 +00003848 assert( iDb>=0 && iDb<db->nDb );
3849 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3850 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3851 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3852 mask = ((yDbMask)1)<<iDb;
3853 if( (pToplevel->cookieMask & mask)==0 ){
3854 pToplevel->cookieMask |= mask;
3855 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3856 if( !OMIT_TEMPDB && iDb==1 ){
3857 sqlite3OpenTempDatabase(pToplevel);
3858 }
drh001bbcb2003-03-19 03:14:00 +00003859 }
drh001bbcb2003-03-19 03:14:00 +00003860}
3861
3862/*
dan57966752011-04-09 17:32:58 +00003863** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3864** attached database. Otherwise, invoke it for the database named zDb only.
3865*/
3866void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3867 sqlite3 *db = pParse->db;
3868 int i;
3869 for(i=0; i<db->nDb; i++){
3870 Db *pDb = &db->aDb[i];
3871 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3872 sqlite3CodeVerifySchema(pParse, i);
3873 }
3874 }
3875}
3876
3877/*
drh1c928532002-01-31 15:54:21 +00003878** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003879** might change the database.
3880**
3881** This routine starts a new transaction if we are not already within
3882** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003883** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003884** be set for operations that might fail (due to a constraint) part of
3885** the way through and which will need to undo some writes without having to
3886** rollback the whole transaction. For operations where all constraints
3887** can be checked before any changes are made to the database, it is never
3888** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003889*/
drh7f0f12e2004-05-21 13:39:50 +00003890void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003891 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003892 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003893 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003894 pToplevel->isMultiWrite |= setStatement;
3895}
3896
drhff738bc2009-09-24 00:09:58 +00003897/*
3898** Indicate that the statement currently under construction might write
3899** more than one entry (example: deleting one row then inserting another,
3900** inserting multiple rows in a table, or inserting a row and index entries.)
3901** If an abort occurs after some of these writes have completed, then it will
3902** be necessary to undo the completed writes.
3903*/
3904void sqlite3MultiWrite(Parse *pParse){
3905 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3906 pToplevel->isMultiWrite = 1;
3907}
3908
dane0af83a2009-09-08 19:15:01 +00003909/*
drhff738bc2009-09-24 00:09:58 +00003910** The code generator calls this routine if is discovers that it is
3911** possible to abort a statement prior to completion. In order to
3912** perform this abort without corrupting the database, we need to make
3913** sure that the statement is protected by a statement transaction.
3914**
3915** Technically, we only need to set the mayAbort flag if the
3916** isMultiWrite flag was previously set. There is a time dependency
3917** such that the abort must occur after the multiwrite. This makes
3918** some statements involving the REPLACE conflict resolution algorithm
3919** go a little faster. But taking advantage of this time dependency
3920** makes it more difficult to prove that the code is correct (in
3921** particular, it prevents us from writing an effective
3922** implementation of sqlite3AssertMayAbort()) and so we have chosen
3923** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003924*/
3925void sqlite3MayAbort(Parse *pParse){
3926 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3927 pToplevel->mayAbort = 1;
3928}
3929
3930/*
3931** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3932** error. The onError parameter determines which (if any) of the statement
3933** and/or current transaction is rolled back.
3934*/
drhd91c1a12013-02-09 13:58:25 +00003935void sqlite3HaltConstraint(
3936 Parse *pParse, /* Parsing context */
3937 int errCode, /* extended error code */
3938 int onError, /* Constraint type */
3939 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003940 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3941 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003942){
dane0af83a2009-09-08 19:15:01 +00003943 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003944 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003945 if( onError==OE_Abort ){
3946 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003947 }
drhd91c1a12013-02-09 13:58:25 +00003948 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003949 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3950}
3951
3952/*
3953** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3954*/
3955void sqlite3UniqueConstraint(
3956 Parse *pParse, /* Parsing context */
3957 int onError, /* Constraint type */
3958 Index *pIdx /* The index that triggers the constraint */
3959){
3960 char *zErr;
3961 int j;
3962 StrAccum errMsg;
3963 Table *pTab = pIdx->pTable;
3964
3965 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
3966 errMsg.db = pParse->db;
3967 for(j=0; j<pIdx->nKeyCol; j++){
3968 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
3969 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00003970 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00003971 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00003972 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00003973 }
3974 zErr = sqlite3StrAccumFinish(&errMsg);
3975 sqlite3HaltConstraint(pParse,
3976 (pIdx->autoIndex==2)?SQLITE_CONSTRAINT_PRIMARYKEY:SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00003977 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00003978}
3979
3980
3981/*
3982** Code an OP_Halt due to non-unique rowid.
3983*/
3984void sqlite3RowidConstraint(
3985 Parse *pParse, /* Parsing context */
3986 int onError, /* Conflict resolution algorithm */
3987 Table *pTab /* The table with the non-unique rowid */
3988){
3989 char *zMsg;
3990 int rc;
3991 if( pTab->iPKey>=0 ){
3992 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
3993 pTab->aCol[pTab->iPKey].zName);
3994 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
3995 }else{
3996 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
3997 rc = SQLITE_CONSTRAINT_ROWID;
3998 }
3999 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4000 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004001}
4002
drh4343fea2004-11-05 23:46:15 +00004003/*
4004** Check to see if pIndex uses the collating sequence pColl. Return
4005** true if it does and false if it does not.
4006*/
4007#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004008static int collationMatch(const char *zColl, Index *pIndex){
4009 int i;
drh04491712009-05-13 17:21:13 +00004010 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004011 for(i=0; i<pIndex->nColumn; i++){
4012 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004013 assert( z!=0 || pIndex->aiColumn[i]<0 );
4014 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004015 return 1;
4016 }
drh4343fea2004-11-05 23:46:15 +00004017 }
4018 return 0;
4019}
4020#endif
4021
4022/*
4023** Recompute all indices of pTab that use the collating sequence pColl.
4024** If pColl==0 then recompute all indices of pTab.
4025*/
4026#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004027static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004028 Index *pIndex; /* An index associated with pTab */
4029
4030 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004031 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004032 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4033 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004034 sqlite3RefillIndex(pParse, pIndex, -1);
4035 }
4036 }
4037}
4038#endif
4039
4040/*
4041** Recompute all indices of all tables in all databases where the
4042** indices use the collating sequence pColl. If pColl==0 then recompute
4043** all indices everywhere.
4044*/
4045#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004046static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004047 Db *pDb; /* A single database */
4048 int iDb; /* The database index number */
4049 sqlite3 *db = pParse->db; /* The database connection */
4050 HashElem *k; /* For looping over tables in pDb */
4051 Table *pTab; /* A table in the database */
4052
drh21206082011-04-04 18:22:02 +00004053 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004054 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004055 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004056 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004057 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004058 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004059 }
4060 }
4061}
4062#endif
4063
4064/*
drheee46cf2004-11-06 00:02:48 +00004065** Generate code for the REINDEX command.
4066**
4067** REINDEX -- 1
4068** REINDEX <collation> -- 2
4069** REINDEX ?<database>.?<tablename> -- 3
4070** REINDEX ?<database>.?<indexname> -- 4
4071**
4072** Form 1 causes all indices in all attached databases to be rebuilt.
4073** Form 2 rebuilds all indices in all databases that use the named
4074** collating function. Forms 3 and 4 rebuild the named index or all
4075** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004076*/
4077#ifndef SQLITE_OMIT_REINDEX
4078void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4079 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4080 char *z; /* Name of a table or index */
4081 const char *zDb; /* Name of the database */
4082 Table *pTab; /* A table in the database */
4083 Index *pIndex; /* An index associated with pTab */
4084 int iDb; /* The database index number */
4085 sqlite3 *db = pParse->db; /* The database connection */
4086 Token *pObjName; /* Name of the table or index to be reindexed */
4087
danielk197733a5edc2005-01-27 00:22:02 +00004088 /* Read the database schema. If an error occurs, leave an error message
4089 ** and code in pParse and return NULL. */
4090 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004091 return;
danielk197733a5edc2005-01-27 00:22:02 +00004092 }
4093
drh8af73d42009-05-13 22:58:28 +00004094 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004095 reindexDatabases(pParse, 0);
4096 return;
drhd3001712009-05-12 17:46:53 +00004097 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004098 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004099 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004100 zColl = sqlite3NameFromToken(pParse->db, pName1);
4101 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004102 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004103 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004104 reindexDatabases(pParse, zColl);
4105 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004106 return;
4107 }
drh633e6d52008-07-28 19:34:53 +00004108 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004109 }
4110 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4111 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004112 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004113 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004114 zDb = db->aDb[iDb].zName;
4115 pTab = sqlite3FindTable(db, z, zDb);
4116 if( pTab ){
4117 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004118 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004119 return;
4120 }
4121 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004122 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004123 if( pIndex ){
4124 sqlite3BeginWriteOperation(pParse, 0, iDb);
4125 sqlite3RefillIndex(pParse, pIndex, -1);
4126 return;
4127 }
4128 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4129}
4130#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004131
4132/*
drh2ec2fb22013-11-06 19:59:23 +00004133** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004134**
drh2ec2fb22013-11-06 19:59:23 +00004135** The KeyInfo structure for an index is cached in the Index object.
4136** So there might be multiple references to the returned pointer. The
4137** caller should not try to modify the KeyInfo object.
4138**
4139** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4140** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004141*/
drh2ec2fb22013-11-06 19:59:23 +00004142KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004143 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004144#ifndef SQLITE_OMIT_SHARED_CACHE
4145 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4146 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4147 pIdx->pKeyInfo = 0;
4148 }
4149#endif
drh2ec2fb22013-11-06 19:59:23 +00004150 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004151 int i;
4152 int nCol = pIdx->nColumn;
4153 int nKey = pIdx->nKeyCol;
4154 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004155 if( pIdx->uniqNotNull ){
4156 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4157 }else{
4158 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4159 }
4160 if( pKey ){
4161 assert( sqlite3KeyInfoIsWriteable(pKey) );
4162 for(i=0; i<nCol; i++){
4163 char *zColl = pIdx->azColl[i];
drhb8a9bb42013-12-06 22:45:31 +00004164 assert( zColl!=0 );
4165 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4166 sqlite3LocateCollSeq(pParse, zColl);
drh2ec2fb22013-11-06 19:59:23 +00004167 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4168 }
4169 if( pParse->nErr ){
4170 sqlite3KeyInfoUnref(pKey);
4171 }else{
4172 pIdx->pKeyInfo = pKey;
4173 }
danielk1977b3bf5562006-01-10 17:58:23 +00004174 }
danielk1977b3bf5562006-01-10 17:58:23 +00004175 }
drh2ec2fb22013-11-06 19:59:23 +00004176 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004177}
drh8b471862014-01-11 13:22:17 +00004178
4179#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004180/*
4181** This routine is invoked once per CTE by the parser while parsing a
4182** WITH clause.
drh8b471862014-01-11 13:22:17 +00004183*/
dan7d562db2014-01-11 19:19:36 +00004184With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004185 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004186 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004187 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004188 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004189 Select *pQuery /* Query used to initialize the table */
4190){
dan4e9119d2014-01-13 15:12:23 +00004191 sqlite3 *db = pParse->db;
4192 With *pNew;
4193 char *zName;
4194
4195 /* Check that the CTE name is unique within this WITH clause. If
4196 ** not, store an error in the Parse structure. */
4197 zName = sqlite3NameFromToken(pParse->db, pName);
4198 if( zName && pWith ){
4199 int i;
4200 for(i=0; i<pWith->nCte; i++){
4201 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004202 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004203 }
4204 }
4205 }
4206
4207 if( pWith ){
4208 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4209 pNew = sqlite3DbRealloc(db, pWith, nByte);
4210 }else{
4211 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4212 }
4213 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004214 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004215
4216 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004217 sqlite3ExprListDelete(db, pArglist);
4218 sqlite3SelectDelete(db, pQuery);
4219 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004220 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004221 }else{
4222 pNew->a[pNew->nCte].pSelect = pQuery;
4223 pNew->a[pNew->nCte].pCols = pArglist;
4224 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004225 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004226 pNew->nCte++;
4227 }
4228
4229 return pNew;
drh8b471862014-01-11 13:22:17 +00004230}
4231
dan7d562db2014-01-11 19:19:36 +00004232/*
4233** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004234*/
dan7d562db2014-01-11 19:19:36 +00004235void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004236 if( pWith ){
4237 int i;
4238 for(i=0; i<pWith->nCte; i++){
4239 struct Cte *pCte = &pWith->a[i];
4240 sqlite3ExprListDelete(db, pCte->pCols);
4241 sqlite3SelectDelete(db, pCte->pSelect);
4242 sqlite3DbFree(db, pCte->zName);
4243 }
4244 sqlite3DbFree(db, pWith);
4245 }
drh8b471862014-01-11 13:22:17 +00004246}
4247#endif /* !defined(SQLITE_OMIT_CTE) */