blob: 99bba67dd2deac7bd8b3ff3d9f07e6ab9f611c13 [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;
drh186ad8c2013-10-08 18:40:37 +0000908 pTable->nRowEst = 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);
drhb7654112008-01-12 12:48:07 +0000951 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
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;
danielk1977c7d54102006-06-15 07:29:00 +00001309 if( pTab && !IN_DECLARE_VTAB ){
drh2938f922012-03-07 19:13:29 +00001310 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1311 if( pParse->constraintName.n ){
1312 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1313 }
drh33e619f2009-05-28 01:00:55 +00001314 }else
drhffe07b22005-11-03 00:41:17 +00001315#endif
drh33e619f2009-05-28 01:00:55 +00001316 {
drh2938f922012-03-07 19:13:29 +00001317 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001318 }
drhffe07b22005-11-03 00:41:17 +00001319}
1320
1321/*
drhd3d39e92004-05-20 22:16:29 +00001322** Set the collation function of the most recently parsed table column
1323** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001324*/
danielk197739002502007-11-12 09:50:26 +00001325void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001326 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001327 int i;
danielk197739002502007-11-12 09:50:26 +00001328 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001329 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001330
danielk1977b8cbb872006-06-19 05:33:45 +00001331 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001332 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001333 db = pParse->db;
1334 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001335 if( !zColl ) return;
1336
drhc4a64fa2009-05-11 20:53:28 +00001337 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001338 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001339 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001340 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001341
1342 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1343 ** then an index may have been created on this column before the
1344 ** collation type was added. Correct this if it is the case.
1345 */
1346 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001347 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001348 if( pIdx->aiColumn[0]==i ){
1349 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001350 }
1351 }
danielk197739002502007-11-12 09:50:26 +00001352 }else{
drh633e6d52008-07-28 19:34:53 +00001353 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001354 }
danielk19777cedc8d2004-06-10 10:50:08 +00001355}
1356
danielk1977466be562004-06-10 02:16:01 +00001357/*
1358** This function returns the collation sequence for database native text
1359** encoding identified by the string zName, length nName.
1360**
1361** If the requested collation sequence is not available, or not available
1362** in the database native encoding, the collation factory is invoked to
1363** request it. If the collation factory does not supply such a sequence,
1364** and the sequence is available in another text encoding, then that is
1365** returned instead.
1366**
1367** If no versions of the requested collations sequence are available, or
1368** another error occurs, NULL is returned and an error message written into
1369** pParse.
drha34001c2007-02-02 12:44:37 +00001370**
1371** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1372** invokes the collation factory if the named collation cannot be found
1373** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001374**
1375** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001376*/
drhc4a64fa2009-05-11 20:53:28 +00001377CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001378 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001379 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001380 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001381 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001382
drhc4a64fa2009-05-11 20:53:28 +00001383 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001384 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001385 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001386 }
1387
danielk19770202b292004-06-09 09:55:16 +00001388 return pColl;
1389}
1390
1391
drh8e2ca022002-06-17 17:07:19 +00001392/*
drh3f7d4e42004-07-24 14:35:58 +00001393** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001394**
1395** The schema cookie is used to determine when the schema for the
1396** database changes. After each schema change, the cookie value
1397** changes. When a process first reads the schema it records the
1398** cookie. Thereafter, whenever it goes to access the database,
1399** it checks the cookie to make sure the schema has not changed
1400** since it was last read.
1401**
1402** This plan is not completely bullet-proof. It is possible for
1403** the schema to change multiple times and for the cookie to be
1404** set back to prior value. But schema changes are infrequent
1405** and the probability of hitting the same cookie value is only
1406** 1 chance in 2^32. So we're safe enough.
1407*/
drh9cbf3422008-01-17 16:22:13 +00001408void sqlite3ChangeCookie(Parse *pParse, int iDb){
1409 int r1 = sqlite3GetTempReg(pParse);
1410 sqlite3 *db = pParse->db;
1411 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001412 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001413 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001414 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001415 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001416}
1417
1418/*
drh969fa7c2002-02-18 18:30:32 +00001419** Measure the number of characters needed to output the given
1420** identifier. The number returned includes any quotes used
1421** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001422**
1423** The estimate is conservative. It might be larger that what is
1424** really needed.
drh969fa7c2002-02-18 18:30:32 +00001425*/
1426static int identLength(const char *z){
1427 int n;
drh17f71932002-02-21 12:01:27 +00001428 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001429 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001430 }
drh234c39d2004-07-24 03:30:47 +00001431 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001432}
1433
1434/*
danielk19771b870de2009-03-14 08:37:23 +00001435** The first parameter is a pointer to an output buffer. The second
1436** parameter is a pointer to an integer that contains the offset at
1437** which to write into the output buffer. This function copies the
1438** nul-terminated string pointed to by the third parameter, zSignedIdent,
1439** to the specified offset in the buffer and updates *pIdx to refer
1440** to the first byte after the last byte written before returning.
1441**
1442** If the string zSignedIdent consists entirely of alpha-numeric
1443** characters, does not begin with a digit and is not an SQL keyword,
1444** then it is copied to the output buffer exactly as it is. Otherwise,
1445** it is quoted using double-quotes.
1446*/
drhc4a64fa2009-05-11 20:53:28 +00001447static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001448 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001449 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001450 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001451
drh17f71932002-02-21 12:01:27 +00001452 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001453 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001454 }
drhc7407522014-01-10 20:38:12 +00001455 needQuote = sqlite3Isdigit(zIdent[0])
1456 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1457 || zIdent[j]!=0
1458 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001459
drh234c39d2004-07-24 03:30:47 +00001460 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001461 for(j=0; zIdent[j]; j++){
1462 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001463 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001464 }
drh234c39d2004-07-24 03:30:47 +00001465 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001466 z[i] = 0;
1467 *pIdx = i;
1468}
1469
1470/*
1471** Generate a CREATE TABLE statement appropriate for the given
1472** table. Memory to hold the text of the statement is obtained
1473** from sqliteMalloc() and must be freed by the calling function.
1474*/
drh1d34fde2009-02-03 15:50:33 +00001475static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001476 int i, k, n;
1477 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001478 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001479 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001480 n = 0;
drh234c39d2004-07-24 03:30:47 +00001481 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001482 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001483 }
1484 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001485 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001486 zSep = "";
1487 zSep2 = ",";
1488 zEnd = ")";
1489 }else{
1490 zSep = "\n ";
1491 zSep2 = ",\n ";
1492 zEnd = "\n)";
1493 }
drhe0bc4042002-06-25 01:09:11 +00001494 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001495 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001496 if( zStmt==0 ){
1497 db->mallocFailed = 1;
1498 return 0;
1499 }
drhbdb339f2009-02-02 18:03:21 +00001500 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001501 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001502 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001503 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001504 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001505 static const char * const azType[] = {
1506 /* SQLITE_AFF_TEXT */ " TEXT",
1507 /* SQLITE_AFF_NONE */ "",
1508 /* SQLITE_AFF_NUMERIC */ " NUM",
1509 /* SQLITE_AFF_INTEGER */ " INT",
1510 /* SQLITE_AFF_REAL */ " REAL"
1511 };
1512 int len;
1513 const char *zType;
1514
drh5bb3eb92007-05-04 13:15:55 +00001515 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001516 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001517 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001518 identPut(zStmt, &k, pCol->zName);
1519 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001520 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001521 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1522 testcase( pCol->affinity==SQLITE_AFF_NONE );
1523 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1524 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1525 testcase( pCol->affinity==SQLITE_AFF_REAL );
1526
1527 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1528 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001529 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001530 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001531 memcpy(&zStmt[k], zType, len);
1532 k += len;
1533 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001534 }
drh5bb3eb92007-05-04 13:15:55 +00001535 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001536 return zStmt;
1537}
1538
1539/*
drh7f9c5db2013-10-23 00:32:58 +00001540** Resize an Index object to hold N columns total. Return SQLITE_OK
1541** on success and SQLITE_NOMEM on an OOM error.
1542*/
1543static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1544 char *zExtra;
1545 int nByte;
1546 if( pIdx->nColumn>=N ) return SQLITE_OK;
1547 assert( pIdx->isResized==0 );
1548 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1549 zExtra = sqlite3DbMallocZero(db, nByte);
1550 if( zExtra==0 ) return SQLITE_NOMEM;
1551 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1552 pIdx->azColl = (char**)zExtra;
1553 zExtra += sizeof(char*)*N;
1554 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1555 pIdx->aiColumn = (i16*)zExtra;
1556 zExtra += sizeof(i16)*N;
1557 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1558 pIdx->aSortOrder = (u8*)zExtra;
1559 pIdx->nColumn = N;
1560 pIdx->isResized = 1;
1561 return SQLITE_OK;
1562}
1563
1564/*
drhfdaac672013-10-04 15:30:21 +00001565** Estimate the total row width for a table.
1566*/
drhe13e9f52013-10-05 19:18:00 +00001567static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001568 unsigned wTable = 0;
1569 const Column *pTabCol;
1570 int i;
1571 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1572 wTable += pTabCol->szEst;
1573 }
1574 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001575 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001576}
1577
1578/*
drhe13e9f52013-10-05 19:18:00 +00001579** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001580*/
drhe13e9f52013-10-05 19:18:00 +00001581static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001582 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001583 int i;
1584 const Column *aCol = pIdx->pTable->aCol;
1585 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001586 i16 x = pIdx->aiColumn[i];
1587 assert( x<pIdx->pTable->nCol );
1588 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001589 }
drhe13e9f52013-10-05 19:18:00 +00001590 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001591}
1592
drh7f9c5db2013-10-23 00:32:58 +00001593/* Return true if value x is found any of the first nCol entries of aiCol[]
1594*/
1595static int hasColumn(const i16 *aiCol, int nCol, int x){
1596 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1597 return 0;
1598}
1599
1600/*
drhc6bd4e42013-11-02 14:37:18 +00001601** This routine runs at the end of parsing a CREATE TABLE statement that
1602** has a WITHOUT ROWID clause. The job of this routine is to convert both
1603** internal schema data structures and the generated VDBE code so that they
1604** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1605** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001606**
drhc6bd4e42013-11-02 14:37:18 +00001607** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1608** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1609** data storage is a covering index btree.
1610** (2) Bypass the creation of the sqlite_master table entry
1611** for the PRIMARY KEY as the the primary key index is now
1612** identified by the sqlite_master table entry of the table itself.
1613** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1614** schema to the rootpage from the main table.
1615** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1616** (5) Add all table columns to the PRIMARY KEY Index object
1617** so that the PRIMARY KEY is a covering index. The surplus
1618** columns are part of KeyInfo.nXField and are not used for
1619** sorting or lookup or uniqueness checks.
1620** (6) Replace the rowid tail on all automatically generated UNIQUE
1621** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001622*/
1623static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1624 Index *pIdx;
1625 Index *pPk;
1626 int nPk;
1627 int i, j;
1628 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001629 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001630
1631 /* Convert the OP_CreateTable opcode that would normally create the
drhc6bd4e42013-11-02 14:37:18 +00001632 ** root-page for the table into a OP_CreateIndex opcode. The index
1633 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001634 */
1635 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001636 assert( v );
1637 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1638 }
1639
1640 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1641 ** table entry.
1642 */
1643 if( pParse->addrSkipPK ){
1644 assert( v );
1645 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001646 }
1647
1648 /* Locate the PRIMARY KEY index. Or, if this table was originally
1649 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1650 */
1651 if( pTab->iPKey>=0 ){
1652 ExprList *pList;
1653 pList = sqlite3ExprListAppend(pParse, 0, 0);
1654 if( pList==0 ) return;
1655 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1656 pTab->aCol[pTab->iPKey].zName);
1657 pList->a[0].sortOrder = pParse->iPkSortOrder;
1658 assert( pParse->pNewTable==pTab );
1659 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1660 if( pPk==0 ) return;
drh63f0eed2013-11-02 22:09:48 +00001661 pPk->autoIndex = 2;
drh7f9c5db2013-10-23 00:32:58 +00001662 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001663 }else{
1664 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001665 }
drh12826092013-11-05 22:39:17 +00001666 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001667 assert( pPk!=0 );
1668 nPk = pPk->nKeyCol;
1669
drhec95c442013-10-23 01:57:32 +00001670 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1671 for(i=0; i<nPk; i++){
1672 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1673 }
drh9eade082013-10-24 14:16:10 +00001674 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001675
drhc6bd4e42013-11-02 14:37:18 +00001676 /* The root page of the PRIMARY KEY is the table root page */
1677 pPk->tnum = pTab->tnum;
1678
drh7f9c5db2013-10-23 00:32:58 +00001679 /* Update the in-memory representation of all UNIQUE indices by converting
1680 ** the final rowid column into one or more columns of the PRIMARY KEY.
1681 */
1682 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1683 int n;
1684 if( pIdx->autoIndex==2 ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001685 for(i=n=0; i<nPk; i++){
1686 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1687 }
drh5a9a37b2013-11-05 17:30:04 +00001688 if( n==0 ){
1689 /* This index is a superset of the primary key */
1690 pIdx->nColumn = pIdx->nKeyCol;
1691 continue;
1692 }
drh7f9c5db2013-10-23 00:32:58 +00001693 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1694 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001695 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001696 pIdx->aiColumn[j] = pPk->aiColumn[i];
1697 pIdx->azColl[j] = pPk->azColl[i];
1698 j++;
1699 }
1700 }
drh00012df2013-11-05 01:59:07 +00001701 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1702 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001703 }
1704
1705 /* Add all table columns to the PRIMARY KEY index
1706 */
1707 if( nPk<pTab->nCol ){
1708 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1709 for(i=0, j=nPk; i<pTab->nCol; i++){
1710 if( !hasColumn(pPk->aiColumn, j, i) ){
1711 assert( j<pPk->nColumn );
1712 pPk->aiColumn[j] = i;
1713 pPk->azColl[j] = "BINARY";
1714 j++;
1715 }
1716 }
1717 assert( pPk->nColumn==j );
1718 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001719 }else{
1720 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001721 }
1722}
1723
drhfdaac672013-10-04 15:30:21 +00001724/*
drh75897232000-05-29 14:26:00 +00001725** This routine is called to report the final ")" that terminates
1726** a CREATE TABLE statement.
1727**
drhf57b3392001-10-08 13:22:32 +00001728** The table structure that other action routines have been building
1729** is added to the internal hash tables, assuming no errors have
1730** occurred.
drh75897232000-05-29 14:26:00 +00001731**
drh1d85d932004-02-14 23:05:52 +00001732** An entry for the table is made in the master table on disk, unless
1733** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001734** it means we are reading the sqlite_master table because we just
1735** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001736** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001737** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001738**
1739** If the pSelect argument is not NULL, it means that this routine
1740** was called to create a table generated from a
1741** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1742** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001743*/
danielk197719a8e7e2005-03-17 05:03:38 +00001744void sqlite3EndTable(
1745 Parse *pParse, /* Parse context */
1746 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001747 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1748 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001749 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1750){
drhfdaac672013-10-04 15:30:21 +00001751 Table *p; /* The new table */
1752 sqlite3 *db = pParse->db; /* The database connection */
1753 int iDb; /* Database in which the table lives */
1754 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001755
drh5969da42013-10-21 02:14:45 +00001756 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1757 return;
danielk1977261919c2005-12-06 12:52:59 +00001758 }
drh28037572000-08-02 13:47:41 +00001759 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001760 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001761
danielk1977517eb642004-06-07 10:00:31 +00001762 assert( !db->init.busy || !pSelect );
1763
drhc6bd4e42013-11-02 14:37:18 +00001764 /* If the db->init.busy is 1 it means we are reading the SQL off the
1765 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1766 ** So do not write to the disk again. Extract the root page number
1767 ** for the table from the db->init.newTnum field. (The page number
1768 ** should have been put there by the sqliteOpenCb routine.)
1769 */
1770 if( db->init.busy ){
1771 p->tnum = db->init.newTnum;
1772 }
1773
1774 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001775 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001776 if( (p->tabFlags & TF_Autoincrement) ){
1777 sqlite3ErrorMsg(pParse,
1778 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1779 return;
1780 }
drh5969da42013-10-21 02:14:45 +00001781 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001782 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001783 }else{
1784 p->tabFlags |= TF_WithoutRowid;
1785 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001786 }
1787 }
1788
drhb9bb7c12006-06-11 23:41:55 +00001789 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001790
drhffe07b22005-11-03 00:41:17 +00001791#ifndef SQLITE_OMIT_CHECK
1792 /* Resolve names in all CHECK constraint expressions.
1793 */
1794 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001795 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001796 }
1797#endif /* !defined(SQLITE_OMIT_CHECK) */
1798
drhe13e9f52013-10-05 19:18:00 +00001799 /* Estimate the average row size for the table and for all implied indices */
1800 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001801 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001802 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001803 }
1804
drhe3c41372001-09-17 20:25:58 +00001805 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001806 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001807 **
drhe0bc4042002-06-25 01:09:11 +00001808 ** If this is a TEMPORARY table, write the entry into the auxiliary
1809 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001810 */
drh1d85d932004-02-14 23:05:52 +00001811 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001812 int n;
drhd8bc7082000-06-07 23:51:50 +00001813 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001814 char *zType; /* "view" or "table" */
1815 char *zType2; /* "VIEW" or "TABLE" */
1816 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001817
danielk19774adee202004-05-08 08:23:19 +00001818 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001819 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001820
drh66a51672008-01-03 00:01:23 +00001821 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001822
drh0fa991b2009-03-21 16:19:26 +00001823 /*
1824 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001825 */
drh4ff6dfa2002-03-03 23:06:00 +00001826 if( p->pSelect==0 ){
1827 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001828 zType = "table";
1829 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001830#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001831 }else{
1832 /* A view */
drh4794f732004-11-05 17:17:50 +00001833 zType = "view";
1834 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001835#endif
drh4ff6dfa2002-03-03 23:06:00 +00001836 }
danielk1977517eb642004-06-07 10:00:31 +00001837
danielk1977517eb642004-06-07 10:00:31 +00001838 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1839 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001840 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001841 **
1842 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1843 ** suitable state to query for the column names and types to be used
1844 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001845 **
1846 ** A shared-cache write-lock is not required to write to the new table,
1847 ** as a schema-lock must have already been obtained to create it. Since
1848 ** a schema-lock excludes all other database users, the write-lock would
1849 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001850 */
1851 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001852 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001853 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001854
danielk19776ab3a2e2009-02-19 14:39:25 +00001855 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001856 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001857 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001858 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001859 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001860 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001861 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001862 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001863 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001864 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001865 assert( p->aCol==0 );
1866 p->nCol = pSelTab->nCol;
1867 p->aCol = pSelTab->aCol;
1868 pSelTab->nCol = 0;
1869 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001870 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001871 }
1872 }
drh4794f732004-11-05 17:17:50 +00001873
drh4794f732004-11-05 17:17:50 +00001874 /* Compute the complete text of the CREATE statement */
1875 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001876 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001877 }else{
drh8ea30bf2013-10-22 01:18:17 +00001878 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1879 n = (int)(pEnd2->z - pParse->sNameToken.z);
1880 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001881 zStmt = sqlite3MPrintf(db,
1882 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1883 );
drh4794f732004-11-05 17:17:50 +00001884 }
1885
1886 /* A slot for the record has already been allocated in the
1887 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001888 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001889 */
1890 sqlite3NestedParse(pParse,
1891 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001892 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1893 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001894 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001895 zType,
1896 p->zName,
1897 p->zName,
drhb7654112008-01-12 12:48:07 +00001898 pParse->regRoot,
1899 zStmt,
1900 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001901 );
drh633e6d52008-07-28 19:34:53 +00001902 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001903 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001904
1905#ifndef SQLITE_OMIT_AUTOINCREMENT
1906 /* Check to see if we need to create an sqlite_sequence table for
1907 ** keeping track of autoincrement keys.
1908 */
drh7d10d5a2008-08-20 16:35:10 +00001909 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001910 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001911 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001912 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001913 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001914 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1915 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001916 );
1917 }
1918 }
1919#endif
drh4794f732004-11-05 17:17:50 +00001920
1921 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001922 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001923 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001924 }
drh17e9e292003-02-01 13:53:28 +00001925
drh2958a4e2004-11-12 03:56:15 +00001926
drh17e9e292003-02-01 13:53:28 +00001927 /* Add the table to the in-memory representation of the database.
1928 */
drh8af73d42009-05-13 22:58:28 +00001929 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001930 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001931 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001932 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001933 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001934 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001935 if( pOld ){
1936 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001937 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001938 return;
drh17e9e292003-02-01 13:53:28 +00001939 }
drh17e9e292003-02-01 13:53:28 +00001940 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001941 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001942
1943#ifndef SQLITE_OMIT_ALTERTABLE
1944 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001945 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001946 int nName;
drh5969da42013-10-21 02:14:45 +00001947 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001948 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00001949 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00001950 }
drh1bd10f82008-12-10 21:19:56 +00001951 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001952 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001953 }
1954#endif
drh17e9e292003-02-01 13:53:28 +00001955 }
drh75897232000-05-29 14:26:00 +00001956}
1957
drhb7f91642004-10-31 02:22:47 +00001958#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001959/*
drha76b5df2002-02-23 02:32:10 +00001960** The parser calls this routine in order to create a new VIEW
1961*/
danielk19774adee202004-05-08 08:23:19 +00001962void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001963 Parse *pParse, /* The parsing context */
1964 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001965 Token *pName1, /* The token that holds the name of the view */
1966 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001967 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001968 int isTemp, /* TRUE for a TEMPORARY view */
1969 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001970){
drha76b5df2002-02-23 02:32:10 +00001971 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001972 int n;
drhb7916a72009-05-27 10:31:29 +00001973 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001974 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001975 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00001976 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00001977 int iDb;
drh17435752007-08-16 04:30:38 +00001978 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001979
drh7c3d64f2005-06-06 15:32:08 +00001980 if( pParse->nVar>0 ){
1981 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001982 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001983 return;
1984 }
drhfdd48a72006-09-11 23:45:48 +00001985 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001986 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001987 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001988 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001989 return;
1990 }
danielk1977ef2cb632004-05-29 02:37:19 +00001991 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001992 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00001993 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
1994 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00001995 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001996 return;
1997 }
drh174b6192002-12-03 02:22:52 +00001998
drh4b59ab52002-08-24 18:24:51 +00001999 /* Make a copy of the entire SELECT statement that defines the view.
2000 ** This will force all the Expr.token.z values to be dynamically
2001 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002002 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002003 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002004 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002005 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002006 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002007 return;
2008 }
drh17435752007-08-16 04:30:38 +00002009 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002010 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002011 }
drh4b59ab52002-08-24 18:24:51 +00002012
2013 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2014 ** the end.
2015 */
drha76b5df2002-02-23 02:32:10 +00002016 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002017 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002018 sEnd.z += sEnd.n;
2019 }
2020 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002021 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002022 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002023 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002024 sEnd.z = &z[n-1];
2025 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002026
danielk19774adee202004-05-08 08:23:19 +00002027 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002028 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002029 return;
drh417be792002-03-03 18:59:40 +00002030}
drhb7f91642004-10-31 02:22:47 +00002031#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002032
danielk1977fe3fcbe22006-06-12 12:08:45 +00002033#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002034/*
2035** The Table structure pTable is really a VIEW. Fill in the names of
2036** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002037** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002038*/
danielk19774adee202004-05-08 08:23:19 +00002039int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002040 Table *pSelTab; /* A fake table from which we get the result set */
2041 Select *pSel; /* Copy of the SELECT that implements the view */
2042 int nErr = 0; /* Number of errors encountered */
2043 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002044 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00002045 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00002046
2047 assert( pTable );
2048
danielk1977fe3fcbe22006-06-12 12:08:45 +00002049#ifndef SQLITE_OMIT_VIRTUALTABLE
2050 if( sqlite3VtabCallConnect(pParse, pTable) ){
2051 return SQLITE_ERROR;
2052 }
drh4cbdda92006-06-14 19:00:20 +00002053 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002054#endif
2055
2056#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002057 /* A positive nCol means the columns names for this view are
2058 ** already known.
2059 */
2060 if( pTable->nCol>0 ) return 0;
2061
2062 /* A negative nCol is a special marker meaning that we are currently
2063 ** trying to compute the column names. If we enter this routine with
2064 ** a negative nCol, it means two or more views form a loop, like this:
2065 **
2066 ** CREATE VIEW one AS SELECT * FROM two;
2067 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002068 **
drh768578e2009-05-12 00:40:12 +00002069 ** Actually, the error above is now caught prior to reaching this point.
2070 ** But the following test is still important as it does come up
2071 ** in the following:
2072 **
2073 ** CREATE TABLE main.ex1(a);
2074 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2075 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002076 */
2077 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002078 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002079 return 1;
2080 }
drh85c23c62005-08-20 03:03:04 +00002081 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002082
2083 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002084 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2085 ** "*" elements in the results set of the view and will assign cursors
2086 ** to the elements of the FROM clause. But we do not want these changes
2087 ** to be permanent. So the computation is done on a copy of the SELECT
2088 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002089 */
drh9b3187e2005-01-18 14:45:47 +00002090 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002091 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002092 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002093 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002094 n = pParse->nTab;
2095 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2096 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002097 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002098#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002099 xAuth = db->xAuth;
2100 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002101 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002102 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002103#else
drh7d10d5a2008-08-20 16:35:10 +00002104 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002105#endif
drhd9da78a2009-03-24 15:08:09 +00002106 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002107 pParse->nTab = n;
2108 if( pSelTab ){
2109 assert( pTable->aCol==0 );
2110 pTable->nCol = pSelTab->nCol;
2111 pTable->aCol = pSelTab->aCol;
2112 pSelTab->nCol = 0;
2113 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002114 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002115 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002116 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002117 }else{
2118 pTable->nCol = 0;
2119 nErr++;
2120 }
drh633e6d52008-07-28 19:34:53 +00002121 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002122 } else {
drh417be792002-03-03 18:59:40 +00002123 nErr++;
2124 }
drhb7f91642004-10-31 02:22:47 +00002125#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002126 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002127}
2128#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002129
drhb7f91642004-10-31 02:22:47 +00002130#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002131/*
drh8bf8dc92003-05-17 17:35:10 +00002132** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002133*/
drh9bb575f2004-09-06 17:24:11 +00002134static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002135 HashElem *i;
drh21206082011-04-04 18:22:02 +00002136 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002137 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002138 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002139 Table *pTab = sqliteHashData(i);
2140 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002141 sqliteDeleteColumnNames(db, pTab);
2142 pTab->aCol = 0;
2143 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002144 }
2145 }
drh8bf8dc92003-05-17 17:35:10 +00002146 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002147}
drhb7f91642004-10-31 02:22:47 +00002148#else
2149# define sqliteViewResetAll(A,B)
2150#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002151
drh75897232000-05-29 14:26:00 +00002152/*
danielk1977a0bf2652004-11-04 14:30:04 +00002153** This function is called by the VDBE to adjust the internal schema
2154** used by SQLite when the btree layer moves a table root page. The
2155** root-page of a table or index in database iDb has changed from iFrom
2156** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002157**
2158** Ticket #1728: The symbol table might still contain information
2159** on tables and/or indices that are the process of being deleted.
2160** If you are unlucky, one of those deleted indices or tables might
2161** have the same rootpage number as the real table or index that is
2162** being moved. So we cannot stop searching after the first match
2163** because the first match might be for one of the deleted indices
2164** or tables and not the table/index that is actually being moved.
2165** We must continue looping until all tables and indices with
2166** rootpage==iFrom have been converted to have a rootpage of iTo
2167** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002168*/
2169#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002170void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002171 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002172 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002173 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002174
drhcdf011d2011-04-04 21:25:28 +00002175 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2176 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002177 pHash = &pDb->pSchema->tblHash;
2178 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002179 Table *pTab = sqliteHashData(pElem);
2180 if( pTab->tnum==iFrom ){
2181 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002182 }
2183 }
danielk1977da184232006-01-05 11:34:32 +00002184 pHash = &pDb->pSchema->idxHash;
2185 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002186 Index *pIdx = sqliteHashData(pElem);
2187 if( pIdx->tnum==iFrom ){
2188 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002189 }
2190 }
danielk1977a0bf2652004-11-04 14:30:04 +00002191}
2192#endif
2193
2194/*
2195** Write code to erase the table with root-page iTable from database iDb.
2196** Also write code to modify the sqlite_master table and internal schema
2197** if a root-page of another table is moved by the btree-layer whilst
2198** erasing iTable (this can happen with an auto-vacuum database).
2199*/
drh4e0cff62004-11-05 05:10:28 +00002200static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2201 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002202 int r1 = sqlite3GetTempReg(pParse);
2203 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002204 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002205#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002206 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002207 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002208 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002209 ** reflect this.
2210 **
drh0fa991b2009-03-21 16:19:26 +00002211 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002212 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2213 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002214 */
danielk197763e3e9f2004-11-05 09:19:27 +00002215 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002216 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2217 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002218#endif
drhb7654112008-01-12 12:48:07 +00002219 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002220}
2221
2222/*
2223** Write VDBE code to erase table pTab and all associated indices on disk.
2224** Code to update the sqlite_master tables and internal schema definitions
2225** in case a root-page belonging to another table is moved by the btree layer
2226** is also added (this can happen with an auto-vacuum database).
2227*/
drh4e0cff62004-11-05 05:10:28 +00002228static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002229#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002230 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002231 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2232 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002233 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002234 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002235 }
2236#else
2237 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2238 ** is not defined), then it is important to call OP_Destroy on the
2239 ** table and index root-pages in order, starting with the numerically
2240 ** largest root-page number. This guarantees that none of the root-pages
2241 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2242 ** following were coded:
2243 **
2244 ** OP_Destroy 4 0
2245 ** ...
2246 ** OP_Destroy 5 0
2247 **
2248 ** and root page 5 happened to be the largest root-page number in the
2249 ** database, then root page 5 would be moved to page 4 by the
2250 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2251 ** a free-list page.
2252 */
2253 int iTab = pTab->tnum;
2254 int iDestroyed = 0;
2255
2256 while( 1 ){
2257 Index *pIdx;
2258 int iLargest = 0;
2259
2260 if( iDestroyed==0 || iTab<iDestroyed ){
2261 iLargest = iTab;
2262 }
2263 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2264 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002265 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002266 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2267 iLargest = iIdx;
2268 }
2269 }
danielk1977da184232006-01-05 11:34:32 +00002270 if( iLargest==0 ){
2271 return;
2272 }else{
2273 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002274 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002275 destroyRootPage(pParse, iLargest, iDb);
2276 iDestroyed = iLargest;
2277 }
danielk1977a0bf2652004-11-04 14:30:04 +00002278 }
2279#endif
2280}
2281
2282/*
drh74e7c8f2011-10-21 19:06:32 +00002283** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002284** after a DROP INDEX or DROP TABLE command.
2285*/
2286static void sqlite3ClearStatTables(
2287 Parse *pParse, /* The parsing context */
2288 int iDb, /* The database number */
2289 const char *zType, /* "idx" or "tbl" */
2290 const char *zName /* Name of index or table */
2291){
drha5ae4c32011-08-07 01:31:52 +00002292 int i;
2293 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002294 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002295 char zTab[24];
2296 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2297 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002298 sqlite3NestedParse(pParse,
2299 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002300 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002301 );
2302 }
2303 }
2304}
2305
2306/*
drhfaacf172011-08-12 01:51:45 +00002307** Generate code to drop a table.
2308*/
2309void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2310 Vdbe *v;
2311 sqlite3 *db = pParse->db;
2312 Trigger *pTrigger;
2313 Db *pDb = &db->aDb[iDb];
2314
2315 v = sqlite3GetVdbe(pParse);
2316 assert( v!=0 );
2317 sqlite3BeginWriteOperation(pParse, 1, iDb);
2318
2319#ifndef SQLITE_OMIT_VIRTUALTABLE
2320 if( IsVirtual(pTab) ){
2321 sqlite3VdbeAddOp0(v, OP_VBegin);
2322 }
2323#endif
2324
2325 /* Drop all triggers associated with the table being dropped. Code
2326 ** is generated to remove entries from sqlite_master and/or
2327 ** sqlite_temp_master if required.
2328 */
2329 pTrigger = sqlite3TriggerList(pParse, pTab);
2330 while( pTrigger ){
2331 assert( pTrigger->pSchema==pTab->pSchema ||
2332 pTrigger->pSchema==db->aDb[1].pSchema );
2333 sqlite3DropTriggerPtr(pParse, pTrigger);
2334 pTrigger = pTrigger->pNext;
2335 }
2336
2337#ifndef SQLITE_OMIT_AUTOINCREMENT
2338 /* Remove any entries of the sqlite_sequence table associated with
2339 ** the table being dropped. This is done before the table is dropped
2340 ** at the btree level, in case the sqlite_sequence table needs to
2341 ** move as a result of the drop (can happen in auto-vacuum mode).
2342 */
2343 if( pTab->tabFlags & TF_Autoincrement ){
2344 sqlite3NestedParse(pParse,
2345 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2346 pDb->zName, pTab->zName
2347 );
2348 }
2349#endif
2350
2351 /* Drop all SQLITE_MASTER table and index entries that refer to the
2352 ** table. The program name loops through the master table and deletes
2353 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002354 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002355 ** created in the temp database that refers to a table in another
2356 ** database.
2357 */
2358 sqlite3NestedParse(pParse,
2359 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2360 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002361 if( !isView && !IsVirtual(pTab) ){
2362 destroyTable(pParse, pTab);
2363 }
2364
2365 /* Remove the table entry from SQLite's internal schema and modify
2366 ** the schema cookie.
2367 */
2368 if( IsVirtual(pTab) ){
2369 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2370 }
2371 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2372 sqlite3ChangeCookie(pParse, iDb);
2373 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002374}
2375
2376/*
drh75897232000-05-29 14:26:00 +00002377** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002378** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002379*/
drha0733842005-12-29 01:11:36 +00002380void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002381 Table *pTab;
drh75897232000-05-29 14:26:00 +00002382 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002383 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002384 int iDb;
drh75897232000-05-29 14:26:00 +00002385
drh8af73d42009-05-13 22:58:28 +00002386 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002387 goto exit_drop_table;
2388 }
drh8af73d42009-05-13 22:58:28 +00002389 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002390 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002391 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002392 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002393 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002394
drha0733842005-12-29 01:11:36 +00002395 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002396 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002397 goto exit_drop_table;
2398 }
danielk1977da184232006-01-05 11:34:32 +00002399 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002400 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002401
2402 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2403 ** it is initialized.
2404 */
2405 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2406 goto exit_drop_table;
2407 }
drhe5f9c642003-01-13 23:27:31 +00002408#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002409 {
2410 int code;
danielk1977da184232006-01-05 11:34:32 +00002411 const char *zTab = SCHEMA_TABLE(iDb);
2412 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002413 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002414 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002415 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002416 }
drhe5f9c642003-01-13 23:27:31 +00002417 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002418 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002419 code = SQLITE_DROP_TEMP_VIEW;
2420 }else{
2421 code = SQLITE_DROP_VIEW;
2422 }
danielk19774b2688a2006-06-20 11:01:07 +00002423#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002424 }else if( IsVirtual(pTab) ){
2425 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002426 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002427#endif
drhe5f9c642003-01-13 23:27:31 +00002428 }else{
danielk197753c0f742005-03-29 03:10:59 +00002429 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002430 code = SQLITE_DROP_TEMP_TABLE;
2431 }else{
2432 code = SQLITE_DROP_TABLE;
2433 }
2434 }
danielk1977f1a381e2006-06-16 08:01:02 +00002435 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002436 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002437 }
danielk1977a8858102004-05-28 12:11:21 +00002438 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2439 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002440 }
drhe5f9c642003-01-13 23:27:31 +00002441 }
2442#endif
drh08ccfaa2011-10-07 23:52:25 +00002443 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2444 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002445 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002446 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002447 }
danielk1977576ec6b2005-01-21 11:55:25 +00002448
2449#ifndef SQLITE_OMIT_VIEW
2450 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2451 ** on a table.
2452 */
danielk1977a8858102004-05-28 12:11:21 +00002453 if( isView && pTab->pSelect==0 ){
2454 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2455 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002456 }
danielk1977a8858102004-05-28 12:11:21 +00002457 if( !isView && pTab->pSelect ){
2458 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2459 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002460 }
danielk1977576ec6b2005-01-21 11:55:25 +00002461#endif
drh75897232000-05-29 14:26:00 +00002462
drh1ccde152000-06-17 13:12:39 +00002463 /* Generate code to remove the table from the master table
2464 ** on disk.
2465 */
danielk19774adee202004-05-08 08:23:19 +00002466 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002467 if( v ){
drh77658e22007-12-04 16:54:52 +00002468 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002469 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002470 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002471 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002472 }
danielk1977a8858102004-05-28 12:11:21 +00002473
2474exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002475 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002476}
2477
2478/*
drhc2eef3b2002-08-31 18:53:06 +00002479** This routine is called to create a new foreign key on the table
2480** currently under construction. pFromCol determines which columns
2481** in the current table point to the foreign key. If pFromCol==0 then
2482** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002483** the table referred to (a.k.a the "parent" table). pToCol is a list
2484** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002485** information about the conflict resolution algorithms specified
2486** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2487**
2488** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002489** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002490**
2491** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002492** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002493*/
danielk19774adee202004-05-08 08:23:19 +00002494void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002495 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002496 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002497 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002498 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002499 int flags /* Conflict resolution algorithms. */
2500){
danielk197718576932008-08-06 13:47:40 +00002501 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002502#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002503 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002504 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002505 Table *p = pParse->pNewTable;
2506 int nByte;
2507 int i;
2508 int nCol;
2509 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002510
2511 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002512 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002513 if( pFromCol==0 ){
2514 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002515 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002516 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002517 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002518 " should reference only one column of table %T",
2519 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002520 goto fk_end;
2521 }
2522 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002523 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002524 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002525 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002526 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002527 goto fk_end;
2528 }else{
danielk19770202b292004-06-09 09:55:16 +00002529 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002530 }
drhe61922a2009-05-02 13:29:37 +00002531 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002532 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002533 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002534 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002535 }
2536 }
drh633e6d52008-07-28 19:34:53 +00002537 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002538 if( pFKey==0 ){
2539 goto fk_end;
2540 }
drhc2eef3b2002-08-31 18:53:06 +00002541 pFKey->pFrom = p;
2542 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002543 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002544 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002545 memcpy(z, pTo->z, pTo->n);
2546 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002547 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002548 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002549 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002550 if( pFromCol==0 ){
2551 pFKey->aCol[0].iFrom = p->nCol-1;
2552 }else{
2553 for(i=0; i<nCol; i++){
2554 int j;
2555 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002556 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002557 pFKey->aCol[i].iFrom = j;
2558 break;
2559 }
2560 }
2561 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002562 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002563 "unknown column \"%s\" in foreign key definition",
2564 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002565 goto fk_end;
2566 }
2567 }
2568 }
2569 if( pToCol ){
2570 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002571 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002572 pFKey->aCol[i].zCol = z;
2573 memcpy(z, pToCol->a[i].zName, n);
2574 z[n] = 0;
2575 z += n+1;
2576 }
2577 }
2578 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002579 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2580 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002581
drh21206082011-04-04 18:22:02 +00002582 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002583 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2584 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2585 );
danf59c5ca2009-09-22 16:55:38 +00002586 if( pNextTo==pFKey ){
2587 db->mallocFailed = 1;
2588 goto fk_end;
2589 }
dan1da40a32009-09-19 17:00:31 +00002590 if( pNextTo ){
2591 assert( pNextTo->pPrevTo==0 );
2592 pFKey->pNextTo = pNextTo;
2593 pNextTo->pPrevTo = pFKey;
2594 }
2595
drhc2eef3b2002-08-31 18:53:06 +00002596 /* Link the foreign key to the table as the last step.
2597 */
2598 p->pFKey = pFKey;
2599 pFKey = 0;
2600
2601fk_end:
drh633e6d52008-07-28 19:34:53 +00002602 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002603#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002604 sqlite3ExprListDelete(db, pFromCol);
2605 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002606}
2607
2608/*
2609** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2610** clause is seen as part of a foreign key definition. The isDeferred
2611** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2612** The behavior of the most recently created foreign key is adjusted
2613** accordingly.
2614*/
danielk19774adee202004-05-08 08:23:19 +00002615void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002616#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002617 Table *pTab;
2618 FKey *pFKey;
2619 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002620 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002621 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002622#endif
drhc2eef3b2002-08-31 18:53:06 +00002623}
2624
2625/*
drh063336a2004-11-05 20:58:39 +00002626** Generate code that will erase and refill index *pIdx. This is
2627** used to initialize a newly created index or to recompute the
2628** content of an index in response to a REINDEX command.
2629**
2630** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002631** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002632** root page number of the index. If memRootPage is negative, then
2633** the index already exists and must be cleared before being refilled and
2634** the root page number of the index is taken from pIndex->tnum.
2635*/
2636static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2637 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002638 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2639 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002640 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002641 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002642 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002643 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002644 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002645 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002646 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002647 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002648 sqlite3 *db = pParse->db; /* The database connection */
2649 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002650
danielk19771d54df82004-11-23 15:41:16 +00002651#ifndef SQLITE_OMIT_AUTHORIZATION
2652 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002653 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002654 return;
2655 }
2656#endif
2657
danielk1977c00da102006-01-07 13:21:04 +00002658 /* Require a write-lock on the table to perform this operation */
2659 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2660
drh063336a2004-11-05 20:58:39 +00002661 v = sqlite3GetVdbe(pParse);
2662 if( v==0 ) return;
2663 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002664 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002665 }else{
2666 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002667 }
drh2ec2fb22013-11-06 19:59:23 +00002668 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002669
dan689ab892011-08-12 15:02:00 +00002670 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002671 iSorter = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00002672 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
2673 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002674
2675 /* Open the table. Loop through all rows of the table, inserting index
2676 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002677 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002678 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002679 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002680
drh1c2c0b72014-01-04 19:27:05 +00002681 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002682 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drhb2b9d3d2013-08-01 01:14:43 +00002683 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
drhca892a72011-09-03 00:17:51 +00002684 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2685 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002686 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2687 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002688 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002689 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2690
drhca892a72011-09-03 00:17:51 +00002691 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
drh1153c7b2013-11-01 22:02:56 +00002692 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
2693 if( pIndex->onError!=OE_None && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002694 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2695 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2696 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002697 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
2698 pKey->nField - pIndex->nKeyCol);
drhf9c8ce32013-11-05 13:33:55 +00002699 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002700 }else{
2701 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002702 }
drhca892a72011-09-03 00:17:51 +00002703 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2704 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2705 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002706 sqlite3ReleaseTempReg(pParse, regRecord);
drhca892a72011-09-03 00:17:51 +00002707 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
drhd654be82005-09-20 17:42:23 +00002708 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002709
drh66a51672008-01-03 00:01:23 +00002710 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2711 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002712 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002713}
2714
2715/*
drh77e57df2013-10-22 14:28:02 +00002716** Allocate heap space to hold an Index object with nCol columns.
2717**
2718** Increase the allocation size to provide an extra nExtra bytes
2719** of 8-byte aligned space after the Index object and return a
2720** pointer to this extra space in *ppExtra.
2721*/
2722Index *sqlite3AllocateIndexObject(
2723 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002724 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002725 int nExtra, /* Number of bytes of extra space to alloc */
2726 char **ppExtra /* Pointer to the "extra" space */
2727){
2728 Index *p; /* Allocated index object */
2729 int nByte; /* Bytes of space for Index object + arrays */
2730
2731 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2732 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
2733 ROUND8(sizeof(tRowcnt)*(nCol+1) + /* Index.aiRowEst */
drhbbbdc832013-10-22 18:01:40 +00002734 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002735 sizeof(u8)*nCol); /* Index.aSortOrder */
2736 p = sqlite3DbMallocZero(db, nByte + nExtra);
2737 if( p ){
2738 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
2739 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2740 p->aiRowEst = (tRowcnt*)pExtra; pExtra += sizeof(tRowcnt)*(nCol+1);
drhbbbdc832013-10-22 18:01:40 +00002741 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002742 p->aSortOrder = (u8*)pExtra;
2743 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002744 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002745 *ppExtra = ((char*)p) + nByte;
2746 }
2747 return p;
2748}
2749
2750/*
drh23bf66d2004-12-14 03:34:34 +00002751** Create a new index for an SQL table. pName1.pName2 is the name of the index
2752** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002753** be NULL for a primary key or an index that is created to satisfy a
2754** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002755** as the table to be indexed. pParse->pNewTable is a table that is
2756** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002757**
drh382c0242001-10-06 16:33:02 +00002758** pList is a list of columns to be indexed. pList will be NULL if this
2759** is a primary key or unique-constraint on the most recent column added
2760** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002761**
2762** If the index is created successfully, return a pointer to the new Index
2763** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2764** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002765*/
dan1da40a32009-09-19 17:00:31 +00002766Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002767 Parse *pParse, /* All information about this parse */
2768 Token *pName1, /* First part of index name. May be NULL */
2769 Token *pName2, /* Second part of index name. May be NULL */
2770 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002771 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002772 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002773 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002774 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002775 int sortOrder, /* Sort order of primary key when pList==NULL */
2776 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002777){
dan1da40a32009-09-19 17:00:31 +00002778 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002779 Table *pTab = 0; /* Table to be indexed */
2780 Index *pIndex = 0; /* The index to be created */
2781 char *zName = 0; /* Name of the index */
2782 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002783 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002784 DbFixer sFix; /* For assigning database names to pTable */
2785 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002786 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002787 Db *pDb; /* The specific table containing the indexed database */
2788 int iDb; /* Index of the database that is being written */
2789 Token *pName = 0; /* Unqualified name of the index to create */
2790 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002791 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002792 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002793 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002794 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002795 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002796
drh8af73d42009-05-13 22:58:28 +00002797 assert( pParse->nErr==0 ); /* Never called with prior errors */
2798 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002799 goto exit_create_index;
2800 }
2801 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002802 goto exit_create_index;
2803 }
drhdaffd0e2001-04-11 14:28:42 +00002804
drh75897232000-05-29 14:26:00 +00002805 /*
2806 ** Find the table that is to be indexed. Return early if not found.
2807 */
danielk1977cbb18d22004-05-28 11:37:27 +00002808 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002809
2810 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002811 ** to search for the table. 'Fix' the table name to this db
2812 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002813 */
2814 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002815 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002816 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002817 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002818
danielk197753c0f742005-03-29 03:10:59 +00002819#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002820 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002821 ** is a temp table. If so, set the database to 1. Do not do this
2822 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002823 */
danielk1977fe910332007-12-02 11:46:34 +00002824 if( !db->init.busy ){
2825 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002826 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002827 iDb = 1;
2828 }
danielk1977ef2cb632004-05-29 02:37:19 +00002829 }
danielk197753c0f742005-03-29 03:10:59 +00002830#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002831
drhd100f692013-10-03 15:39:44 +00002832 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2833 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002834 /* Because the parser constructs pTblName from a single identifier,
2835 ** sqlite3FixSrcList can never fail. */
2836 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002837 }
dan41fb5cd2012-10-04 19:33:00 +00002838 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002839 assert( db->mallocFailed==0 || pTab==0 );
2840 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002841 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2842 sqlite3ErrorMsg(pParse,
2843 "cannot create a TEMP index on non-TEMP table \"%s\"",
2844 pTab->zName);
2845 goto exit_create_index;
2846 }
drh44156282013-10-23 22:23:03 +00002847 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002848 }else{
drhe3c41372001-09-17 20:25:58 +00002849 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002850 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002851 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002852 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002853 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002854 }
drhfdd6e852005-12-16 01:06:16 +00002855 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002856
drhd3001712009-05-12 17:46:53 +00002857 assert( pTab!=0 );
2858 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002859 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh503a6862013-03-01 01:07:17 +00002860 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002861 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002862 goto exit_create_index;
2863 }
danielk1977576ec6b2005-01-21 11:55:25 +00002864#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002865 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002866 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002867 goto exit_create_index;
2868 }
danielk1977576ec6b2005-01-21 11:55:25 +00002869#endif
danielk19775ee9d692006-06-21 12:36:25 +00002870#ifndef SQLITE_OMIT_VIRTUALTABLE
2871 if( IsVirtual(pTab) ){
2872 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2873 goto exit_create_index;
2874 }
2875#endif
drh75897232000-05-29 14:26:00 +00002876
2877 /*
2878 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002879 ** index or table with the same name.
2880 **
2881 ** Exception: If we are reading the names of permanent indices from the
2882 ** sqlite_master table (because some other process changed the schema) and
2883 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002884 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002885 **
2886 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002887 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2888 ** own name.
drh75897232000-05-29 14:26:00 +00002889 */
danielk1977d8123362004-06-12 09:25:12 +00002890 if( pName ){
drh17435752007-08-16 04:30:38 +00002891 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002892 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002893 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002894 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002895 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002896 }
danielk1977d8123362004-06-12 09:25:12 +00002897 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002898 if( sqlite3FindTable(db, zName, 0)!=0 ){
2899 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2900 goto exit_create_index;
2901 }
2902 }
danielk197759a33f92007-03-17 10:26:59 +00002903 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2904 if( !ifNotExist ){
2905 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002906 }else{
2907 assert( !db->init.busy );
2908 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002909 }
danielk197759a33f92007-03-17 10:26:59 +00002910 goto exit_create_index;
2911 }
danielk1977a21c6b62005-01-24 10:25:59 +00002912 }else{
drhadbca9c2001-09-27 15:11:53 +00002913 int n;
2914 Index *pLoop;
2915 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002916 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002917 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002918 goto exit_create_index;
2919 }
drh75897232000-05-29 14:26:00 +00002920 }
2921
drhe5f9c642003-01-13 23:27:31 +00002922 /* Check for authorization to create an index.
2923 */
2924#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002925 {
drhfdd6e852005-12-16 01:06:16 +00002926 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002927 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002928 goto exit_create_index;
2929 }
2930 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002931 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002932 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002933 goto exit_create_index;
2934 }
drhe5f9c642003-01-13 23:27:31 +00002935 }
2936#endif
2937
drh75897232000-05-29 14:26:00 +00002938 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002939 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002940 ** So create a fake list to simulate this.
2941 */
2942 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002943 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002944 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002945 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2946 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00002947 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002948 }
2949
danielk1977b3bf5562006-01-10 17:58:23 +00002950 /* Figure out how many bytes of space are required to store explicitly
2951 ** specified collation sequence names.
2952 */
2953 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002954 Expr *pExpr = pList->a[i].pExpr;
2955 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00002956 assert( pExpr->op==TK_COLLATE );
2957 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00002958 }
2959 }
2960
drh75897232000-05-29 14:26:00 +00002961 /*
2962 ** Allocate the index structure.
2963 */
drhea678832008-12-10 19:26:22 +00002964 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00002965 nExtraCol = pPk ? pPk->nKeyCol : 1;
2966 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00002967 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00002968 if( db->mallocFailed ){
2969 goto exit_create_index;
2970 }
drhe09b84c2011-11-14 02:53:54 +00002971 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
2972 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00002973 pIndex->zName = zExtra;
2974 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00002975 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002976 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00002977 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00002978 pIndex->uniqNotNull = onError!=OE_None;
drh1bd10f82008-12-10 21:19:56 +00002979 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002980 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00002981 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00002982 if( pPIWhere ){
2983 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
2984 pIndex->pPartIdxWhere = pPIWhere;
2985 pPIWhere = 0;
2986 }
drh21206082011-04-04 18:22:02 +00002987 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002988
drhfdd6e852005-12-16 01:06:16 +00002989 /* Check to see if we should honor DESC requests on index columns
2990 */
danielk1977da184232006-01-05 11:34:32 +00002991 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002992 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002993 }else{
2994 sortOrderMask = 0; /* Ignore DESC */
2995 }
2996
drh1ccde152000-06-17 13:12:39 +00002997 /* Scan the names of the columns of the table to be indexed and
2998 ** load the column indices into the Index structure. Report an error
2999 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003000 **
3001 ** TODO: Add a test to make sure that the same column is not named
3002 ** more than once within the same index. Only the first instance of
3003 ** the column will ever be used by the optimizer. Note that using the
3004 ** same column more than once cannot be an error because that would
3005 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003006 */
drhfdd6e852005-12-16 01:06:16 +00003007 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3008 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003009 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003010 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003011
drhfdd6e852005-12-16 01:06:16 +00003012 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3013 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003014 }
3015 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003016 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003017 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003018 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003019 goto exit_create_index;
3020 }
drhbbbdc832013-10-22 18:01:40 +00003021 assert( pTab->nCol<=0x7fff && j<=0x7fff );
3022 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003023 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003024 int nColl;
dan911ce412013-05-15 15:16:50 +00003025 assert( pListItem->pExpr->op==TK_COLLATE );
3026 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003027 nColl = sqlite3Strlen30(zColl) + 1;
3028 assert( nExtra>=nColl );
3029 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003030 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003031 zExtra += nColl;
3032 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003033 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003034 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003035 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003036 }
drhb7f24de2009-05-13 17:35:23 +00003037 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003038 goto exit_create_index;
3039 }
danielk1977b3bf5562006-01-10 17:58:23 +00003040 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003041 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003042 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003043 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003044 }
drh44156282013-10-23 22:23:03 +00003045 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003046 for(j=0; j<pPk->nKeyCol; j++){
3047 int x = pPk->aiColumn[j];
3048 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3049 pIndex->nColumn--;
3050 }else{
3051 pIndex->aiColumn[i] = x;
3052 pIndex->azColl[i] = pPk->azColl[j];
3053 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3054 i++;
3055 }
drh44156282013-10-23 22:23:03 +00003056 }
drh7913e412013-11-01 20:30:36 +00003057 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003058 }else{
3059 pIndex->aiColumn[i] = -1;
3060 pIndex->azColl[i] = "BINARY";
3061 }
drh51147ba2005-07-23 22:59:55 +00003062 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003063 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003064
danielk1977d8123362004-06-12 09:25:12 +00003065 if( pTab==pParse->pNewTable ){
3066 /* This routine has been called to create an automatic index as a
3067 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3068 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3069 ** i.e. one of:
3070 **
3071 ** CREATE TABLE t(x PRIMARY KEY, y);
3072 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3073 **
3074 ** Either way, check to see if the table already has such an index. If
3075 ** so, don't bother creating this one. This only applies to
3076 ** automatically created indices. Users can do as they wish with
3077 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003078 **
3079 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3080 ** (and thus suppressing the second one) even if they have different
3081 ** sort orders.
3082 **
3083 ** If there are different collating sequences or if the columns of
3084 ** the constraint occur in different orders, then the constraints are
3085 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003086 */
3087 Index *pIdx;
3088 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3089 int k;
3090 assert( pIdx->onError!=OE_None );
3091 assert( pIdx->autoIndex );
3092 assert( pIndex->onError!=OE_None );
3093
drhbbbdc832013-10-22 18:01:40 +00003094 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3095 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003096 const char *z1;
3097 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003098 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003099 z1 = pIdx->azColl[k];
3100 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003101 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003102 }
drhbbbdc832013-10-22 18:01:40 +00003103 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003104 if( pIdx->onError!=pIndex->onError ){
3105 /* This constraint creates the same index as a previous
3106 ** constraint specified somewhere in the CREATE TABLE statement.
3107 ** However the ON CONFLICT clauses are different. If both this
3108 ** constraint and the previous equivalent constraint have explicit
3109 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003110 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003111 */
3112 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3113 sqlite3ErrorMsg(pParse,
3114 "conflicting ON CONFLICT clauses specified", 0);
3115 }
3116 if( pIdx->onError==OE_Default ){
3117 pIdx->onError = pIndex->onError;
3118 }
3119 }
danielk1977d8123362004-06-12 09:25:12 +00003120 goto exit_create_index;
3121 }
3122 }
3123 }
3124
drh75897232000-05-29 14:26:00 +00003125 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003126 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003127 */
drh234c39d2004-07-24 03:30:47 +00003128 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003129 Index *p;
drh21206082011-04-04 18:22:02 +00003130 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003131 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00003132 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00003133 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003134 if( p ){
3135 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003136 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003137 goto exit_create_index;
3138 }
drh5e00f6c2001-09-13 13:46:56 +00003139 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003140 if( pTblName!=0 ){
3141 pIndex->tnum = db->init.newTnum;
3142 }
drhd78eeee2001-09-13 16:18:53 +00003143 }
3144
drh58383402013-11-04 17:00:50 +00003145 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3146 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3147 ** emit code to allocate the index rootpage on disk and make an entry for
3148 ** the index in the sqlite_master table and populate the index with
3149 ** content. But, do not do this if we are simply reading the sqlite_master
3150 ** table to parse the schema, or if this index is the PRIMARY KEY index
3151 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003152 **
drh58383402013-11-04 17:00:50 +00003153 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3154 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003155 ** has just been created, it contains no data and the index initialization
3156 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003157 */
drh58383402013-11-04 17:00:50 +00003158 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003159 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003160 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003161 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003162
danielk19774adee202004-05-08 08:23:19 +00003163 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003164 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003165
drhfdd6e852005-12-16 01:06:16 +00003166
drh063336a2004-11-05 20:58:39 +00003167 /* Create the rootpage for the index
3168 */
drhaee128d2005-02-14 20:48:18 +00003169 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003170 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003171
3172 /* Gather the complete text of the CREATE INDEX statement into
3173 ** the zStmt variable
3174 */
drhd3001712009-05-12 17:46:53 +00003175 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003176 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003177 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003178 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003179 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003180 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003181 }else{
3182 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003183 /* zStmt = sqlite3MPrintf(""); */
3184 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003185 }
drh063336a2004-11-05 20:58:39 +00003186
3187 /* Add an entry in sqlite_master for this index
3188 */
3189 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003190 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003191 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3192 pIndex->zName,
3193 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003194 iMem,
drh063336a2004-11-05 20:58:39 +00003195 zStmt
3196 );
drh633e6d52008-07-28 19:34:53 +00003197 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003198
danielk1977a21c6b62005-01-24 10:25:59 +00003199 /* Fill the index with data and reparse the schema. Code an OP_Expire
3200 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003201 */
danielk1977cbb18d22004-05-28 11:37:27 +00003202 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003203 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003204 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003205 sqlite3VdbeAddParseSchemaOp(v, iDb,
3206 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003207 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003208 }
drh75897232000-05-29 14:26:00 +00003209 }
3210
danielk1977d8123362004-06-12 09:25:12 +00003211 /* When adding an index to the list of indices for a table, make
3212 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003213 ** OE_Ignore. This is necessary for the correct constraint check
3214 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3215 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003216 */
drh234c39d2004-07-24 03:30:47 +00003217 if( db->init.busy || pTblName==0 ){
3218 if( onError!=OE_Replace || pTab->pIndex==0
3219 || pTab->pIndex->onError==OE_Replace){
3220 pIndex->pNext = pTab->pIndex;
3221 pTab->pIndex = pIndex;
3222 }else{
3223 Index *pOther = pTab->pIndex;
3224 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3225 pOther = pOther->pNext;
3226 }
3227 pIndex->pNext = pOther->pNext;
3228 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003229 }
dan1da40a32009-09-19 17:00:31 +00003230 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003231 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003232 }
danielk1977d8123362004-06-12 09:25:12 +00003233
drh75897232000-05-29 14:26:00 +00003234 /* Clean up before exiting */
3235exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003236 if( pIndex ) freeIndex(db, pIndex);
3237 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003238 sqlite3ExprListDelete(db, pList);
3239 sqlite3SrcListDelete(db, pTblName);
3240 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003241 return pRet;
drh75897232000-05-29 14:26:00 +00003242}
3243
3244/*
drh51147ba2005-07-23 22:59:55 +00003245** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003246** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003247**
3248** aiRowEst[0] is suppose to contain the number of elements in the index.
3249** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3250** number of rows in the table that match any particular value of the
3251** first column of the index. aiRowEst[2] is an estimate of the number
3252** of rows that match any particular combiniation of the first 2 columns
3253** of the index. And so forth. It must always be the case that
3254*
3255** aiRowEst[N]<=aiRowEst[N-1]
3256** aiRowEst[N]>=1
3257**
3258** Apart from that, we have little to go on besides intuition as to
3259** how aiRowEst[] should be initialized. The numbers generated here
3260** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003261*/
3262void sqlite3DefaultRowEst(Index *pIdx){
drhfaacf172011-08-12 01:51:45 +00003263 tRowcnt *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00003264 int i;
drhfaacf172011-08-12 01:51:45 +00003265 tRowcnt n;
drh28c4cf42005-07-27 20:41:43 +00003266 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00003267 a[0] = pIdx->pTable->nRowEst;
3268 if( a[0]<10 ) a[0] = 10;
3269 n = 10;
drhbbbdc832013-10-22 18:01:40 +00003270 for(i=1; i<=pIdx->nKeyCol; i++){
drh15564052010-09-25 22:32:56 +00003271 a[i] = n;
3272 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00003273 }
3274 if( pIdx->onError!=OE_None ){
drhbbbdc832013-10-22 18:01:40 +00003275 a[pIdx->nKeyCol] = 1;
drh51147ba2005-07-23 22:59:55 +00003276 }
3277}
3278
3279/*
drh74e24cd2002-01-09 03:19:59 +00003280** This routine will drop an existing named index. This routine
3281** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003282*/
drh4d91a702006-01-04 15:54:36 +00003283void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003284 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003285 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003286 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003287 int iDb;
drh75897232000-05-29 14:26:00 +00003288
drh8af73d42009-05-13 22:58:28 +00003289 assert( pParse->nErr==0 ); /* Never called with prior errors */
3290 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003291 goto exit_drop_index;
3292 }
drhd24cc422003-03-27 12:51:24 +00003293 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003294 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3295 goto exit_drop_index;
3296 }
danielk19774adee202004-05-08 08:23:19 +00003297 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003298 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003299 if( !ifExists ){
3300 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003301 }else{
3302 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003303 }
drha6ecd332004-06-10 00:29:09 +00003304 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003305 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003306 }
drh485b39b2002-07-13 03:11:52 +00003307 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00003308 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003309 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003310 goto exit_drop_index;
3311 }
danielk1977da184232006-01-05 11:34:32 +00003312 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003313#ifndef SQLITE_OMIT_AUTHORIZATION
3314 {
3315 int code = SQLITE_DROP_INDEX;
3316 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003317 const char *zDb = db->aDb[iDb].zName;
3318 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003319 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003320 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003321 }
danielk1977da184232006-01-05 11:34:32 +00003322 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003323 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003324 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003325 }
drhed6c8672003-01-12 18:02:16 +00003326 }
drhe5f9c642003-01-13 23:27:31 +00003327#endif
drh75897232000-05-29 14:26:00 +00003328
3329 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003330 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003331 if( v ){
drh77658e22007-12-04 16:54:52 +00003332 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003333 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003334 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003335 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003336 );
drha5ae4c32011-08-07 01:31:52 +00003337 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003338 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003339 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003340 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003341 }
3342
drhd24cc422003-03-27 12:51:24 +00003343exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003344 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003345}
3346
3347/*
dan9ace1122012-03-29 07:51:45 +00003348** pArray is a pointer to an array of objects. Each object in the
3349** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3350** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003351**
dan9ace1122012-03-29 07:51:45 +00003352** When this function is called, *pnEntry contains the current size of
3353** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3354** in total).
drh13449892005-09-07 21:22:45 +00003355**
dan9ace1122012-03-29 07:51:45 +00003356** If the realloc() is successful (i.e. if no OOM condition occurs), the
3357** space allocated for the new object is zeroed, *pnEntry updated to
3358** reflect the new size of the array and a pointer to the new allocation
3359** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003360**
dan9ace1122012-03-29 07:51:45 +00003361** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3362** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003363*/
drhcf643722007-03-27 13:36:37 +00003364void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003365 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003366 void *pArray, /* Array of objects. Might be reallocated */
3367 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003368 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003369 int *pIdx /* Write the index of a new slot here */
3370){
3371 char *z;
drh6c535152012-02-02 03:38:30 +00003372 int n = *pnEntry;
3373 if( (n & (n-1))==0 ){
3374 int sz = (n==0) ? 1 : 2*n;
3375 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003376 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003377 *pIdx = -1;
3378 return pArray;
drh13449892005-09-07 21:22:45 +00003379 }
drhcf643722007-03-27 13:36:37 +00003380 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003381 }
drhcf643722007-03-27 13:36:37 +00003382 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003383 memset(&z[n * szEntry], 0, szEntry);
3384 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003385 ++*pnEntry;
3386 return pArray;
drh13449892005-09-07 21:22:45 +00003387}
3388
3389/*
drh75897232000-05-29 14:26:00 +00003390** Append a new element to the given IdList. Create a new IdList if
3391** need be.
drhdaffd0e2001-04-11 14:28:42 +00003392**
3393** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003394*/
drh17435752007-08-16 04:30:38 +00003395IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003396 int i;
drh75897232000-05-29 14:26:00 +00003397 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003398 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003399 if( pList==0 ) return 0;
3400 }
drhcf643722007-03-27 13:36:37 +00003401 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003402 db,
drhcf643722007-03-27 13:36:37 +00003403 pList->a,
3404 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003405 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003406 &i
3407 );
drh13449892005-09-07 21:22:45 +00003408 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003409 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003410 return 0;
drh75897232000-05-29 14:26:00 +00003411 }
drh17435752007-08-16 04:30:38 +00003412 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003413 return pList;
3414}
3415
3416/*
drhfe05af82005-07-21 03:14:59 +00003417** Delete an IdList.
3418*/
drh633e6d52008-07-28 19:34:53 +00003419void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003420 int i;
3421 if( pList==0 ) return;
3422 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003423 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003424 }
drh633e6d52008-07-28 19:34:53 +00003425 sqlite3DbFree(db, pList->a);
3426 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003427}
3428
3429/*
3430** Return the index in pList of the identifier named zId. Return -1
3431** if not found.
3432*/
3433int sqlite3IdListIndex(IdList *pList, const char *zName){
3434 int i;
3435 if( pList==0 ) return -1;
3436 for(i=0; i<pList->nId; i++){
3437 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3438 }
3439 return -1;
3440}
3441
3442/*
drha78c22c2008-11-11 18:28:58 +00003443** Expand the space allocated for the given SrcList object by
3444** creating nExtra new slots beginning at iStart. iStart is zero based.
3445** New slots are zeroed.
3446**
3447** For example, suppose a SrcList initially contains two entries: A,B.
3448** To append 3 new entries onto the end, do this:
3449**
3450** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3451**
3452** After the call above it would contain: A, B, nil, nil, nil.
3453** If the iStart argument had been 1 instead of 2, then the result
3454** would have been: A, nil, nil, nil, B. To prepend the new slots,
3455** the iStart value would be 0. The result then would
3456** be: nil, nil, nil, A, B.
3457**
3458** If a memory allocation fails the SrcList is unchanged. The
3459** db->mallocFailed flag will be set to true.
3460*/
3461SrcList *sqlite3SrcListEnlarge(
3462 sqlite3 *db, /* Database connection to notify of OOM errors */
3463 SrcList *pSrc, /* The SrcList to be enlarged */
3464 int nExtra, /* Number of new slots to add to pSrc->a[] */
3465 int iStart /* Index in pSrc->a[] of first new slot */
3466){
3467 int i;
3468
3469 /* Sanity checking on calling parameters */
3470 assert( iStart>=0 );
3471 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003472 assert( pSrc!=0 );
3473 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003474
3475 /* Allocate additional space if needed */
3476 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3477 SrcList *pNew;
3478 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003479 int nGot;
drha78c22c2008-11-11 18:28:58 +00003480 pNew = sqlite3DbRealloc(db, pSrc,
3481 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3482 if( pNew==0 ){
3483 assert( db->mallocFailed );
3484 return pSrc;
3485 }
3486 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003487 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drhad01d892013-06-19 13:59:49 +00003488 pSrc->nAlloc = (u8)nGot;
drha78c22c2008-11-11 18:28:58 +00003489 }
3490
3491 /* Move existing slots that come after the newly inserted slots
3492 ** out of the way */
3493 for(i=pSrc->nSrc-1; i>=iStart; i--){
3494 pSrc->a[i+nExtra] = pSrc->a[i];
3495 }
drhad01d892013-06-19 13:59:49 +00003496 pSrc->nSrc += (i8)nExtra;
drha78c22c2008-11-11 18:28:58 +00003497
3498 /* Zero the newly allocated slots */
3499 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3500 for(i=iStart; i<iStart+nExtra; i++){
3501 pSrc->a[i].iCursor = -1;
3502 }
3503
3504 /* Return a pointer to the enlarged SrcList */
3505 return pSrc;
3506}
3507
3508
3509/*
drhad3cab52002-05-24 02:04:32 +00003510** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003511** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003512**
drha78c22c2008-11-11 18:28:58 +00003513** A SrcList is returned, or NULL if there is an OOM error. The returned
3514** SrcList might be the same as the SrcList that was input or it might be
3515** a new one. If an OOM error does occurs, then the prior value of pList
3516** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003517**
3518** If pDatabase is not null, it means that the table has an optional
3519** database name prefix. Like this: "database.table". The pDatabase
3520** points to the table name and the pTable points to the database name.
3521** The SrcList.a[].zName field is filled with the table name which might
3522** come from pTable (if pDatabase is NULL) or from pDatabase.
3523** SrcList.a[].zDatabase is filled with the database name from pTable,
3524** or with NULL if no database is specified.
3525**
3526** In other words, if call like this:
3527**
drh17435752007-08-16 04:30:38 +00003528** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003529**
3530** Then B is a table name and the database name is unspecified. If called
3531** like this:
3532**
drh17435752007-08-16 04:30:38 +00003533** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003534**
drhd3001712009-05-12 17:46:53 +00003535** Then C is the table name and B is the database name. If C is defined
3536** then so is B. In other words, we never have a case where:
3537**
3538** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003539**
3540** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3541** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003542*/
drh17435752007-08-16 04:30:38 +00003543SrcList *sqlite3SrcListAppend(
3544 sqlite3 *db, /* Connection to notify of malloc failures */
3545 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3546 Token *pTable, /* Table to append */
3547 Token *pDatabase /* Database of the table */
3548){
drha99db3b2004-06-19 14:49:12 +00003549 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003550 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003551 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003552 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003553 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003554 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003555 }
drha78c22c2008-11-11 18:28:58 +00003556 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3557 if( db->mallocFailed ){
3558 sqlite3SrcListDelete(db, pList);
3559 return 0;
drhad3cab52002-05-24 02:04:32 +00003560 }
drha78c22c2008-11-11 18:28:58 +00003561 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003562 if( pDatabase && pDatabase->z==0 ){
3563 pDatabase = 0;
3564 }
drhd3001712009-05-12 17:46:53 +00003565 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003566 Token *pTemp = pDatabase;
3567 pDatabase = pTable;
3568 pTable = pTemp;
3569 }
drh17435752007-08-16 04:30:38 +00003570 pItem->zName = sqlite3NameFromToken(db, pTable);
3571 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003572 return pList;
3573}
3574
3575/*
drhdfe88ec2008-11-03 20:55:06 +00003576** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003577*/
danielk19774adee202004-05-08 08:23:19 +00003578void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003579 int i;
drh9b3187e2005-01-18 14:45:47 +00003580 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003581 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003582 if( pList ){
3583 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3584 if( pItem->iCursor>=0 ) break;
3585 pItem->iCursor = pParse->nTab++;
3586 if( pItem->pSelect ){
3587 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3588 }
drh63eb5f22003-04-29 16:20:44 +00003589 }
3590 }
3591}
3592
3593/*
drhad3cab52002-05-24 02:04:32 +00003594** Delete an entire SrcList including all its substructure.
3595*/
drh633e6d52008-07-28 19:34:53 +00003596void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003597 int i;
drhbe5c89a2004-07-26 00:31:09 +00003598 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003599 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003600 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003601 sqlite3DbFree(db, pItem->zDatabase);
3602 sqlite3DbFree(db, pItem->zName);
3603 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003604 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003605 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003606 sqlite3SelectDelete(db, pItem->pSelect);
3607 sqlite3ExprDelete(db, pItem->pOn);
3608 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003609 }
drh633e6d52008-07-28 19:34:53 +00003610 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003611}
3612
drh982cef72000-05-30 16:27:03 +00003613/*
drh61dfc312006-12-16 16:25:15 +00003614** This routine is called by the parser to add a new term to the
3615** end of a growing FROM clause. The "p" parameter is the part of
3616** the FROM clause that has already been constructed. "p" is NULL
3617** if this is the first term of the FROM clause. pTable and pDatabase
3618** are the name of the table and database named in the FROM clause term.
3619** pDatabase is NULL if the database name qualifier is missing - the
3620** usual case. If the term has a alias, then pAlias points to the
3621** alias token. If the term is a subquery, then pSubquery is the
3622** SELECT statement that the subquery encodes. The pTable and
3623** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3624** parameters are the content of the ON and USING clauses.
3625**
3626** Return a new SrcList which encodes is the FROM with the new
3627** term added.
3628*/
3629SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003630 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003631 SrcList *p, /* The left part of the FROM clause already seen */
3632 Token *pTable, /* Name of the table to add to the FROM clause */
3633 Token *pDatabase, /* Name of the database containing pTable */
3634 Token *pAlias, /* The right-hand side of the AS subexpression */
3635 Select *pSubquery, /* A subquery used in place of a table name */
3636 Expr *pOn, /* The ON clause of a join */
3637 IdList *pUsing /* The USING clause of a join */
3638){
3639 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003640 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003641 if( !p && (pOn || pUsing) ){
3642 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3643 (pOn ? "ON" : "USING")
3644 );
3645 goto append_from_error;
3646 }
drh17435752007-08-16 04:30:38 +00003647 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003648 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003649 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003650 }
3651 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003652 assert( pAlias!=0 );
3653 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003654 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003655 }
3656 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003657 pItem->pOn = pOn;
3658 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003659 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003660
3661 append_from_error:
3662 assert( p==0 );
3663 sqlite3ExprDelete(db, pOn);
3664 sqlite3IdListDelete(db, pUsing);
3665 sqlite3SelectDelete(db, pSubquery);
3666 return 0;
drh61dfc312006-12-16 16:25:15 +00003667}
3668
3669/*
danielk1977b1c685b2008-10-06 16:18:39 +00003670** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3671** element of the source-list passed as the second argument.
3672*/
3673void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003674 assert( pIndexedBy!=0 );
3675 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003676 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3677 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3678 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3679 /* A "NOT INDEXED" clause was supplied. See parse.y
3680 ** construct "indexed_opt" for details. */
3681 pItem->notIndexed = 1;
3682 }else{
3683 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3684 }
3685 }
3686}
3687
3688/*
drh61dfc312006-12-16 16:25:15 +00003689** When building up a FROM clause in the parser, the join operator
3690** is initially attached to the left operand. But the code generator
3691** expects the join operator to be on the right operand. This routine
3692** Shifts all join operators from left to right for an entire FROM
3693** clause.
3694**
3695** Example: Suppose the join is like this:
3696**
3697** A natural cross join B
3698**
3699** The operator is "natural cross join". The A and B operands are stored
3700** in p->a[0] and p->a[1], respectively. The parser initially stores the
3701** operator with A. This routine shifts that operator over to B.
3702*/
3703void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003704 if( p ){
drh61dfc312006-12-16 16:25:15 +00003705 int i;
drhd017ab92011-08-23 00:01:58 +00003706 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003707 for(i=p->nSrc-1; i>0; i--){
3708 p->a[i].jointype = p->a[i-1].jointype;
3709 }
3710 p->a[0].jointype = 0;
3711 }
3712}
3713
3714/*
drhc4a3c772001-04-04 11:48:57 +00003715** Begin a transaction
3716*/
drh684917c2004-10-05 02:41:42 +00003717void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003718 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003719 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003720 int i;
drh5e00f6c2001-09-13 13:46:56 +00003721
drhd3001712009-05-12 17:46:53 +00003722 assert( pParse!=0 );
3723 db = pParse->db;
3724 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003725/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003726 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3727 return;
3728 }
danielk19771d850a72004-05-31 08:26:49 +00003729 v = sqlite3GetVdbe(pParse);
3730 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003731 if( type!=TK_DEFERRED ){
3732 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003733 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003734 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003735 }
3736 }
drh66a51672008-01-03 00:01:23 +00003737 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003738}
3739
3740/*
3741** Commit a transaction
3742*/
danielk19774adee202004-05-08 08:23:19 +00003743void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003744 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003745
drhd3001712009-05-12 17:46:53 +00003746 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003747 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003748 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3749 return;
3750 }
danielk19771d850a72004-05-31 08:26:49 +00003751 v = sqlite3GetVdbe(pParse);
3752 if( v ){
drh66a51672008-01-03 00:01:23 +00003753 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003754 }
drhc4a3c772001-04-04 11:48:57 +00003755}
3756
3757/*
3758** Rollback a transaction
3759*/
danielk19774adee202004-05-08 08:23:19 +00003760void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003761 Vdbe *v;
3762
drhd3001712009-05-12 17:46:53 +00003763 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003764 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003765 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3766 return;
3767 }
danielk19774adee202004-05-08 08:23:19 +00003768 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003769 if( v ){
drh66a51672008-01-03 00:01:23 +00003770 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003771 }
drhc4a3c772001-04-04 11:48:57 +00003772}
drhf57b14a2001-09-14 18:54:08 +00003773
3774/*
danielk1977fd7f0452008-12-17 17:30:26 +00003775** This function is called by the parser when it parses a command to create,
3776** release or rollback an SQL savepoint.
3777*/
3778void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003779 char *zName = sqlite3NameFromToken(pParse->db, pName);
3780 if( zName ){
3781 Vdbe *v = sqlite3GetVdbe(pParse);
3782#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003783 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003784 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3785#endif
3786 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3787 sqlite3DbFree(pParse->db, zName);
3788 return;
3789 }
3790 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003791 }
3792}
3793
3794/*
drhdc3ff9c2004-08-18 02:10:15 +00003795** Make sure the TEMP database is open and available for use. Return
3796** the number of errors. Leave any error messages in the pParse structure.
3797*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003798int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003799 sqlite3 *db = pParse->db;
3800 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003801 int rc;
drh10a76c92010-01-26 01:25:26 +00003802 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003803 static const int flags =
3804 SQLITE_OPEN_READWRITE |
3805 SQLITE_OPEN_CREATE |
3806 SQLITE_OPEN_EXCLUSIVE |
3807 SQLITE_OPEN_DELETEONCLOSE |
3808 SQLITE_OPEN_TEMP_DB;
3809
dan3a6d8ae2011-04-23 15:54:54 +00003810 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003811 if( rc!=SQLITE_OK ){
3812 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3813 "file for storing temporary tables");
3814 pParse->rc = rc;
3815 return 1;
3816 }
drh10a76c92010-01-26 01:25:26 +00003817 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003818 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003819 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3820 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003821 return 1;
drh10a76c92010-01-26 01:25:26 +00003822 }
drhdc3ff9c2004-08-18 02:10:15 +00003823 }
3824 return 0;
3825}
3826
3827/*
drhaceb31b2014-02-08 01:40:27 +00003828** Record the fact that the schema cookie will need to be verified
3829** for database iDb. The code to actually verify the schema cookie
3830** will occur at the end of the top-level VDBE and will be generated
3831** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003832*/
danielk19774adee202004-05-08 08:23:19 +00003833void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003834 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003835 sqlite3 *db = pToplevel->db;
3836 yDbMask mask;
drh80242052004-06-09 00:48:12 +00003837
drhaceb31b2014-02-08 01:40:27 +00003838 assert( iDb>=0 && iDb<db->nDb );
3839 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3840 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3841 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3842 mask = ((yDbMask)1)<<iDb;
3843 if( (pToplevel->cookieMask & mask)==0 ){
3844 pToplevel->cookieMask |= mask;
3845 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3846 if( !OMIT_TEMPDB && iDb==1 ){
3847 sqlite3OpenTempDatabase(pToplevel);
3848 }
drh001bbcb2003-03-19 03:14:00 +00003849 }
drh001bbcb2003-03-19 03:14:00 +00003850}
3851
3852/*
dan57966752011-04-09 17:32:58 +00003853** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3854** attached database. Otherwise, invoke it for the database named zDb only.
3855*/
3856void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3857 sqlite3 *db = pParse->db;
3858 int i;
3859 for(i=0; i<db->nDb; i++){
3860 Db *pDb = &db->aDb[i];
3861 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3862 sqlite3CodeVerifySchema(pParse, i);
3863 }
3864 }
3865}
3866
3867/*
drh1c928532002-01-31 15:54:21 +00003868** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003869** might change the database.
3870**
3871** This routine starts a new transaction if we are not already within
3872** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003873** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003874** be set for operations that might fail (due to a constraint) part of
3875** the way through and which will need to undo some writes without having to
3876** rollback the whole transaction. For operations where all constraints
3877** can be checked before any changes are made to the database, it is never
3878** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003879*/
drh7f0f12e2004-05-21 13:39:50 +00003880void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003881 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003882 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003883 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003884 pToplevel->isMultiWrite |= setStatement;
3885}
3886
drhff738bc2009-09-24 00:09:58 +00003887/*
3888** Indicate that the statement currently under construction might write
3889** more than one entry (example: deleting one row then inserting another,
3890** inserting multiple rows in a table, or inserting a row and index entries.)
3891** If an abort occurs after some of these writes have completed, then it will
3892** be necessary to undo the completed writes.
3893*/
3894void sqlite3MultiWrite(Parse *pParse){
3895 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3896 pToplevel->isMultiWrite = 1;
3897}
3898
dane0af83a2009-09-08 19:15:01 +00003899/*
drhff738bc2009-09-24 00:09:58 +00003900** The code generator calls this routine if is discovers that it is
3901** possible to abort a statement prior to completion. In order to
3902** perform this abort without corrupting the database, we need to make
3903** sure that the statement is protected by a statement transaction.
3904**
3905** Technically, we only need to set the mayAbort flag if the
3906** isMultiWrite flag was previously set. There is a time dependency
3907** such that the abort must occur after the multiwrite. This makes
3908** some statements involving the REPLACE conflict resolution algorithm
3909** go a little faster. But taking advantage of this time dependency
3910** makes it more difficult to prove that the code is correct (in
3911** particular, it prevents us from writing an effective
3912** implementation of sqlite3AssertMayAbort()) and so we have chosen
3913** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003914*/
3915void sqlite3MayAbort(Parse *pParse){
3916 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3917 pToplevel->mayAbort = 1;
3918}
3919
3920/*
3921** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3922** error. The onError parameter determines which (if any) of the statement
3923** and/or current transaction is rolled back.
3924*/
drhd91c1a12013-02-09 13:58:25 +00003925void sqlite3HaltConstraint(
3926 Parse *pParse, /* Parsing context */
3927 int errCode, /* extended error code */
3928 int onError, /* Constraint type */
3929 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003930 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3931 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003932){
dane0af83a2009-09-08 19:15:01 +00003933 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003934 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003935 if( onError==OE_Abort ){
3936 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003937 }
drhd91c1a12013-02-09 13:58:25 +00003938 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003939 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3940}
3941
3942/*
3943** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3944*/
3945void sqlite3UniqueConstraint(
3946 Parse *pParse, /* Parsing context */
3947 int onError, /* Constraint type */
3948 Index *pIdx /* The index that triggers the constraint */
3949){
3950 char *zErr;
3951 int j;
3952 StrAccum errMsg;
3953 Table *pTab = pIdx->pTable;
3954
3955 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
3956 errMsg.db = pParse->db;
3957 for(j=0; j<pIdx->nKeyCol; j++){
3958 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
3959 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00003960 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00003961 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00003962 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00003963 }
3964 zErr = sqlite3StrAccumFinish(&errMsg);
3965 sqlite3HaltConstraint(pParse,
3966 (pIdx->autoIndex==2)?SQLITE_CONSTRAINT_PRIMARYKEY:SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00003967 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00003968}
3969
3970
3971/*
3972** Code an OP_Halt due to non-unique rowid.
3973*/
3974void sqlite3RowidConstraint(
3975 Parse *pParse, /* Parsing context */
3976 int onError, /* Conflict resolution algorithm */
3977 Table *pTab /* The table with the non-unique rowid */
3978){
3979 char *zMsg;
3980 int rc;
3981 if( pTab->iPKey>=0 ){
3982 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
3983 pTab->aCol[pTab->iPKey].zName);
3984 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
3985 }else{
3986 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
3987 rc = SQLITE_CONSTRAINT_ROWID;
3988 }
3989 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
3990 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00003991}
3992
drh4343fea2004-11-05 23:46:15 +00003993/*
3994** Check to see if pIndex uses the collating sequence pColl. Return
3995** true if it does and false if it does not.
3996*/
3997#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003998static int collationMatch(const char *zColl, Index *pIndex){
3999 int i;
drh04491712009-05-13 17:21:13 +00004000 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004001 for(i=0; i<pIndex->nColumn; i++){
4002 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004003 assert( z!=0 || pIndex->aiColumn[i]<0 );
4004 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004005 return 1;
4006 }
drh4343fea2004-11-05 23:46:15 +00004007 }
4008 return 0;
4009}
4010#endif
4011
4012/*
4013** Recompute all indices of pTab that use the collating sequence pColl.
4014** If pColl==0 then recompute all indices of pTab.
4015*/
4016#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004017static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004018 Index *pIndex; /* An index associated with pTab */
4019
4020 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004021 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004022 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4023 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004024 sqlite3RefillIndex(pParse, pIndex, -1);
4025 }
4026 }
4027}
4028#endif
4029
4030/*
4031** Recompute all indices of all tables in all databases where the
4032** indices use the collating sequence pColl. If pColl==0 then recompute
4033** all indices everywhere.
4034*/
4035#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004036static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004037 Db *pDb; /* A single database */
4038 int iDb; /* The database index number */
4039 sqlite3 *db = pParse->db; /* The database connection */
4040 HashElem *k; /* For looping over tables in pDb */
4041 Table *pTab; /* A table in the database */
4042
drh21206082011-04-04 18:22:02 +00004043 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004044 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004045 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004046 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004047 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004048 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004049 }
4050 }
4051}
4052#endif
4053
4054/*
drheee46cf2004-11-06 00:02:48 +00004055** Generate code for the REINDEX command.
4056**
4057** REINDEX -- 1
4058** REINDEX <collation> -- 2
4059** REINDEX ?<database>.?<tablename> -- 3
4060** REINDEX ?<database>.?<indexname> -- 4
4061**
4062** Form 1 causes all indices in all attached databases to be rebuilt.
4063** Form 2 rebuilds all indices in all databases that use the named
4064** collating function. Forms 3 and 4 rebuild the named index or all
4065** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004066*/
4067#ifndef SQLITE_OMIT_REINDEX
4068void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4069 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4070 char *z; /* Name of a table or index */
4071 const char *zDb; /* Name of the database */
4072 Table *pTab; /* A table in the database */
4073 Index *pIndex; /* An index associated with pTab */
4074 int iDb; /* The database index number */
4075 sqlite3 *db = pParse->db; /* The database connection */
4076 Token *pObjName; /* Name of the table or index to be reindexed */
4077
danielk197733a5edc2005-01-27 00:22:02 +00004078 /* Read the database schema. If an error occurs, leave an error message
4079 ** and code in pParse and return NULL. */
4080 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004081 return;
danielk197733a5edc2005-01-27 00:22:02 +00004082 }
4083
drh8af73d42009-05-13 22:58:28 +00004084 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004085 reindexDatabases(pParse, 0);
4086 return;
drhd3001712009-05-12 17:46:53 +00004087 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004088 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004089 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004090 zColl = sqlite3NameFromToken(pParse->db, pName1);
4091 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004092 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004093 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004094 reindexDatabases(pParse, zColl);
4095 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004096 return;
4097 }
drh633e6d52008-07-28 19:34:53 +00004098 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004099 }
4100 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4101 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004102 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004103 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004104 zDb = db->aDb[iDb].zName;
4105 pTab = sqlite3FindTable(db, z, zDb);
4106 if( pTab ){
4107 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004108 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004109 return;
4110 }
4111 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004112 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004113 if( pIndex ){
4114 sqlite3BeginWriteOperation(pParse, 0, iDb);
4115 sqlite3RefillIndex(pParse, pIndex, -1);
4116 return;
4117 }
4118 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4119}
4120#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004121
4122/*
drh2ec2fb22013-11-06 19:59:23 +00004123** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004124**
drh2ec2fb22013-11-06 19:59:23 +00004125** The KeyInfo structure for an index is cached in the Index object.
4126** So there might be multiple references to the returned pointer. The
4127** caller should not try to modify the KeyInfo object.
4128**
4129** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4130** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004131*/
drh2ec2fb22013-11-06 19:59:23 +00004132KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004133 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004134#ifndef SQLITE_OMIT_SHARED_CACHE
4135 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4136 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4137 pIdx->pKeyInfo = 0;
4138 }
4139#endif
drh2ec2fb22013-11-06 19:59:23 +00004140 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004141 int i;
4142 int nCol = pIdx->nColumn;
4143 int nKey = pIdx->nKeyCol;
4144 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004145 if( pIdx->uniqNotNull ){
4146 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4147 }else{
4148 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4149 }
4150 if( pKey ){
4151 assert( sqlite3KeyInfoIsWriteable(pKey) );
4152 for(i=0; i<nCol; i++){
4153 char *zColl = pIdx->azColl[i];
drhb8a9bb42013-12-06 22:45:31 +00004154 assert( zColl!=0 );
4155 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4156 sqlite3LocateCollSeq(pParse, zColl);
drh2ec2fb22013-11-06 19:59:23 +00004157 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4158 }
4159 if( pParse->nErr ){
4160 sqlite3KeyInfoUnref(pKey);
4161 }else{
4162 pIdx->pKeyInfo = pKey;
4163 }
danielk1977b3bf5562006-01-10 17:58:23 +00004164 }
danielk1977b3bf5562006-01-10 17:58:23 +00004165 }
drh2ec2fb22013-11-06 19:59:23 +00004166 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004167}
drh8b471862014-01-11 13:22:17 +00004168
4169#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004170/*
4171** This routine is invoked once per CTE by the parser while parsing a
4172** WITH clause.
drh8b471862014-01-11 13:22:17 +00004173*/
dan7d562db2014-01-11 19:19:36 +00004174With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004175 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004176 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004177 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004178 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004179 Select *pQuery /* Query used to initialize the table */
4180){
dan4e9119d2014-01-13 15:12:23 +00004181 sqlite3 *db = pParse->db;
4182 With *pNew;
4183 char *zName;
4184
4185 /* Check that the CTE name is unique within this WITH clause. If
4186 ** not, store an error in the Parse structure. */
4187 zName = sqlite3NameFromToken(pParse->db, pName);
4188 if( zName && pWith ){
4189 int i;
4190 for(i=0; i<pWith->nCte; i++){
4191 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004192 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004193 }
4194 }
4195 }
4196
4197 if( pWith ){
4198 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4199 pNew = sqlite3DbRealloc(db, pWith, nByte);
4200 }else{
4201 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4202 }
4203 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004204 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004205
4206 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004207 sqlite3ExprListDelete(db, pArglist);
4208 sqlite3SelectDelete(db, pQuery);
4209 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004210 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004211 }else{
4212 pNew->a[pNew->nCte].pSelect = pQuery;
4213 pNew->a[pNew->nCte].pCols = pArglist;
4214 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004215 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004216 pNew->nCte++;
4217 }
4218
4219 return pNew;
drh8b471862014-01-11 13:22:17 +00004220}
4221
dan7d562db2014-01-11 19:19:36 +00004222/*
4223** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004224*/
dan7d562db2014-01-11 19:19:36 +00004225void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004226 if( pWith ){
4227 int i;
4228 for(i=0; i<pWith->nCte; i++){
4229 struct Cte *pCte = &pWith->a[i];
4230 sqlite3ExprListDelete(db, pCte->pCols);
4231 sqlite3SelectDelete(db, pCte->pSelect);
4232 sqlite3DbFree(db, pCte->zName);
4233 }
4234 sqlite3DbFree(db, pWith);
4235 }
drh8b471862014-01-11 13:22:17 +00004236}
4237#endif /* !defined(SQLITE_OMIT_CTE) */