blob: 4c45a9272789259ef063592e59dec554229f2f6a [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
drh17435752007-08-16 04:30:38 +0000130 db = pParse->db;
131 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000132 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000133 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000134
drh80242052004-06-09 00:48:12 +0000135 /* Begin by generating some termination code at the end of the
136 ** vdbe program
137 */
drh80242052004-06-09 00:48:12 +0000138 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000139 assert( !pParse->isMultiWrite
140 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000141 if( v ){
drh66a51672008-01-03 00:01:23 +0000142 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000143
144 /* The cookie mask contains one bit for each database file open.
145 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
146 ** set for each database that is used. Generate code to start a
147 ** transaction on each used database and to verify the schema cookie
148 ** on each used database.
149 */
drhc275b4e2004-07-19 17:25:24 +0000150 if( pParse->cookieGoto>0 ){
drh64123582011-04-02 20:01:02 +0000151 yDbMask mask;
drh26e4a8b2008-05-01 17:16:52 +0000152 int iDb;
drhd654be82005-09-20 17:42:23 +0000153 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000154 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
155 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000156 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000157 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drh8a939192009-04-20 17:43:03 +0000158 if( db->init.busy==0 ){
drh21206082011-04-04 18:22:02 +0000159 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhc2a75552011-03-18 21:55:46 +0000160 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
161 iDb, pParse->cookieValue[iDb],
162 db->aDb[iDb].pSchema->iGeneration);
drh8a939192009-04-20 17:43:03 +0000163 }
drh80242052004-06-09 00:48:12 +0000164 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000165#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000166 {
167 int i;
168 for(i=0; i<pParse->nVtabLock; i++){
danielk1977595a5232009-07-24 17:58:53 +0000169 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
drh26e4a8b2008-05-01 17:16:52 +0000170 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
171 }
172 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000173 }
174#endif
danielk1977c00da102006-01-07 13:21:04 +0000175
176 /* Once all the cookies have been verified and transactions opened,
177 ** obtain the required table-locks. This is a no-op unless the
178 ** shared-cache feature is enabled.
179 */
180 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000181
182 /* Initialize any AUTOINCREMENT data structures required.
183 */
184 sqlite3AutoincrementBegin(pParse);
185
186 /* Finally, jump back to the beginning of the executable code. */
drh66a51672008-01-03 00:01:23 +0000187 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000188 }
drh71c697e2004-08-08 23:39:19 +0000189 }
190
drh3f7d4e42004-07-24 14:35:58 +0000191
drh80242052004-06-09 00:48:12 +0000192 /* Get the VDBE program ready for execution
193 */
drh04491712009-05-13 17:21:13 +0000194 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000195#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000196 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000197 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000198#endif
drhceea3322009-04-23 13:22:42 +0000199 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000200 /* A minimum of one cursor is required if autoincrement is used
201 * See ticket [a696379c1f08866] */
202 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000203 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000204 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000205 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000206 }else{
drh483750b2003-01-29 18:46:51 +0000207 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000208 }
drha226d052002-09-25 19:04:07 +0000209 pParse->nTab = 0;
210 pParse->nMem = 0;
211 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000212 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000213 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000214 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000215}
216
217/*
drh205f48e2004-11-05 00:43:11 +0000218** Run the parser and code generator recursively in order to generate
219** code for the SQL statement given onto the end of the pParse context
220** currently under construction. When the parser is run recursively
221** this way, the final OP_Halt is not appended and other initialization
222** and finalization steps are omitted because those are handling by the
223** outermost parser.
224**
225** Not everything is nestable. This facility is designed to permit
226** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000227** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000228*/
229void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
230 va_list ap;
231 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000232 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000233 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000234# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
235 char saveBuf[SAVE_SZ];
236
drh205f48e2004-11-05 00:43:11 +0000237 if( pParse->nErr ) return;
238 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
239 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000240 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000241 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000242 if( zSql==0 ){
243 return; /* A malloc must have failed */
244 }
drh205f48e2004-11-05 00:43:11 +0000245 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000246 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
247 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000248 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000249 sqlite3DbFree(db, zErrMsg);
250 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000251 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000252 pParse->nested--;
253}
254
255/*
danielk19778a414492004-06-29 08:59:35 +0000256** Locate the in-memory structure that describes a particular database
257** table given the name of that table and (optionally) the name of the
258** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000259**
danielk19778a414492004-06-29 08:59:35 +0000260** If zDatabase is 0, all databases are searched for the table and the
261** first matching table is returned. (No checking for duplicate table
262** names is done.) The search order is TEMP first, then MAIN, then any
263** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000264**
danielk19774adee202004-05-08 08:23:19 +0000265** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000266*/
drh9bb575f2004-09-06 17:24:11 +0000267Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000268 Table *p = 0;
269 int i;
drh0a687d12008-07-08 14:52:07 +0000270 int nName;
drh645f63e2004-06-22 13:22:40 +0000271 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000272 nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000273 /* All mutexes are required for schema access. Make sure we hold them. */
274 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000275 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000276 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000277 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000278 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh0a687d12008-07-08 14:52:07 +0000279 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000280 if( p ) break;
281 }
drh74e24cd2002-01-09 03:19:59 +0000282 return p;
drh75897232000-05-29 14:26:00 +0000283}
284
285/*
danielk19778a414492004-06-29 08:59:35 +0000286** Locate the in-memory structure that describes a particular database
287** table given the name of that table and (optionally) the name of the
288** database containing the table. Return NULL if not found. Also leave an
289** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000290**
danielk19778a414492004-06-29 08:59:35 +0000291** The difference between this routine and sqlite3FindTable() is that this
292** routine leaves an error message in pParse->zErrMsg where
293** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000294*/
drhca424112008-01-25 15:04:48 +0000295Table *sqlite3LocateTable(
296 Parse *pParse, /* context in which to report errors */
297 int isView, /* True if looking for a VIEW rather than a TABLE */
298 const char *zName, /* Name of the table we are looking for */
299 const char *zDbase /* Name of the database. Might be NULL */
300){
drha69d9162003-04-17 22:57:53 +0000301 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000302
danielk19778a414492004-06-29 08:59:35 +0000303 /* Read the database schema. If an error occurs, leave an error message
304 ** and code in pParse and return NULL. */
305 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
306 return 0;
307 }
308
danielk19774adee202004-05-08 08:23:19 +0000309 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000310 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000311 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000312 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000313 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000314 }else{
drhca424112008-01-25 15:04:48 +0000315 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000316 }
drha6ecd332004-06-10 00:29:09 +0000317 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000318 }
319 return p;
320}
321
322/*
dan41fb5cd2012-10-04 19:33:00 +0000323** Locate the table identified by *p.
324**
325** This is a wrapper around sqlite3LocateTable(). The difference between
326** sqlite3LocateTable() and this function is that this function restricts
327** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
328** non-NULL if it is part of a view or trigger program definition. See
329** sqlite3FixSrcList() for details.
330*/
331Table *sqlite3LocateTableItem(
332 Parse *pParse,
333 int isView,
334 struct SrcList_item *p
335){
336 const char *zDb;
337 assert( p->pSchema==0 || p->zDatabase==0 );
338 if( p->pSchema ){
339 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
340 zDb = pParse->db->aDb[iDb].zName;
341 }else{
342 zDb = p->zDatabase;
343 }
344 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
345}
346
347/*
drha69d9162003-04-17 22:57:53 +0000348** Locate the in-memory structure that describes
349** a particular index given the name of that index
350** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000351** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000352**
353** If zDatabase is 0, all databases are searched for the
354** table and the first matching index is returned. (No checking
355** for duplicate index names is done.) The search order is
356** TEMP first, then MAIN, then any auxiliary databases added
357** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000358*/
drh9bb575f2004-09-06 17:24:11 +0000359Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000360 Index *p = 0;
361 int i;
drhdee0e402009-05-03 20:23:53 +0000362 int nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000363 /* All mutexes are required for schema access. Make sure we hold them. */
364 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000365 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000366 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000367 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000368 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000369 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000370 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh04491712009-05-13 17:21:13 +0000371 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000372 if( p ) break;
373 }
drh74e24cd2002-01-09 03:19:59 +0000374 return p;
drh75897232000-05-29 14:26:00 +0000375}
376
377/*
drh956bc922004-07-24 17:38:29 +0000378** Reclaim the memory used by an index
379*/
dan1feeaed2010-07-23 15:41:47 +0000380static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000381#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000382 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000383#endif
drh633e6d52008-07-28 19:34:53 +0000384 sqlite3DbFree(db, p->zColAff);
385 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000386}
387
388/*
drhc96d8532005-05-03 12:30:33 +0000389** For the index called zIdxName which is found in the database iDb,
390** unlike that index from its Table then remove the index from
391** the index hash table and free all memory structures associated
392** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000393*/
drh9bb575f2004-09-06 17:24:11 +0000394void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000395 Index *pIndex;
396 int len;
drh21206082011-04-04 18:22:02 +0000397 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000398
drh21206082011-04-04 18:22:02 +0000399 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
400 pHash = &db->aDb[iDb].pSchema->idxHash;
drhdee0e402009-05-03 20:23:53 +0000401 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000402 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh22645842011-03-24 01:34:03 +0000403 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000404 if( pIndex->pTable->pIndex==pIndex ){
405 pIndex->pTable->pIndex = pIndex->pNext;
406 }else{
407 Index *p;
drh04491712009-05-13 17:21:13 +0000408 /* Justification of ALWAYS(); The index must be on the list of
409 ** indices. */
410 p = pIndex->pTable->pIndex;
411 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
412 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000413 p->pNext = pIndex->pNext;
414 }
drh5e00f6c2001-09-13 13:46:56 +0000415 }
dan1feeaed2010-07-23 15:41:47 +0000416 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000417 }
drh956bc922004-07-24 17:38:29 +0000418 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000419}
420
421/*
drh81028a42012-05-15 18:28:27 +0000422** Look through the list of open database files in db->aDb[] and if
423** any have been closed, remove them from the list. Reallocate the
424** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000425**
drh81028a42012-05-15 18:28:27 +0000426** Entry 0 (the "main" database) and entry 1 (the "temp" database)
427** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000428*/
drh81028a42012-05-15 18:28:27 +0000429void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000430 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000431 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000432 struct Db *pDb = &db->aDb[i];
433 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000434 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000435 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000436 continue;
437 }
438 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000439 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000440 }
drh8bf8dc92003-05-17 17:35:10 +0000441 j++;
drh1c2d8412003-03-31 00:30:47 +0000442 }
443 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
444 db->nDb = j;
445 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
446 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000447 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000448 db->aDb = db->aDbStatic;
449 }
drhe0bc4042002-06-25 01:09:11 +0000450}
451
452/*
drh81028a42012-05-15 18:28:27 +0000453** Reset the schema for the database at index iDb. Also reset the
454** TEMP schema.
455*/
456void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000457 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000458 assert( iDb<db->nDb );
459
460 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000461 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000462 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
463 assert( pDb->pSchema!=0 );
464 sqlite3SchemaClear(pDb->pSchema);
465
466 /* If any database other than TEMP is reset, then also reset TEMP
467 ** since TEMP might be holding triggers that reference tables in the
468 ** other database.
469 */
470 if( iDb!=1 ){
471 pDb = &db->aDb[1];
472 assert( pDb->pSchema!=0 );
473 sqlite3SchemaClear(pDb->pSchema);
474 }
475 return;
476}
477
478/*
479** Erase all schema information from all attached databases (including
480** "main" and "temp") for a single database connection.
481*/
482void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
483 int i;
484 sqlite3BtreeEnterAll(db);
485 for(i=0; i<db->nDb; i++){
486 Db *pDb = &db->aDb[i];
487 if( pDb->pSchema ){
488 sqlite3SchemaClear(pDb->pSchema);
489 }
490 }
491 db->flags &= ~SQLITE_InternChanges;
492 sqlite3VtabUnlockList(db);
493 sqlite3BtreeLeaveAll(db);
494 sqlite3CollapseDatabaseArray(db);
495}
496
497/*
drhe0bc4042002-06-25 01:09:11 +0000498** This routine is called when a commit occurs.
499*/
drh9bb575f2004-09-06 17:24:11 +0000500void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000501 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000502}
503
504/*
dand46def72010-07-24 11:28:28 +0000505** Delete memory allocated for the column names of a table or view (the
506** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000507*/
dand46def72010-07-24 11:28:28 +0000508static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000509 int i;
510 Column *pCol;
511 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000512 if( (pCol = pTable->aCol)!=0 ){
513 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000514 sqlite3DbFree(db, pCol->zName);
515 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000516 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000517 sqlite3DbFree(db, pCol->zType);
518 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000519 }
drh633e6d52008-07-28 19:34:53 +0000520 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000521 }
drh956bc922004-07-24 17:38:29 +0000522}
523
524/*
drh75897232000-05-29 14:26:00 +0000525** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000526** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000527**
528** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000529** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000530** memory structures of the indices and foreign keys associated with
531** the table.
drh29ddd3a2012-05-15 12:49:32 +0000532**
533** The db parameter is optional. It is needed if the Table object
534** contains lookaside memory. (Table objects in the schema do not use
535** lookaside memory, but some ephemeral Table objects do.) Or the
536** db parameter can be used with db->pnBytesFreed to measure the memory
537** used by the Table object.
drh75897232000-05-29 14:26:00 +0000538*/
dan1feeaed2010-07-23 15:41:47 +0000539void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000540 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000541 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000542
dand46def72010-07-24 11:28:28 +0000543 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000544
drhed8a3bb2005-06-06 21:19:56 +0000545 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000546 if( !pTable ) return;
547 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000548
drh29ddd3a2012-05-15 12:49:32 +0000549 /* Record the number of outstanding lookaside allocations in schema Tables
550 ** prior to doing any free() operations. Since schema Tables do not use
551 ** lookaside, this number should not change. */
552 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
553 db->lookaside.nOut : 0 );
554
dand46def72010-07-24 11:28:28 +0000555 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000556 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
557 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000558 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000559 if( !db || db->pnBytesFreed==0 ){
560 char *zName = pIndex->zName;
561 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhf2f105d2012-08-20 15:53:54 +0000562 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
dand46def72010-07-24 11:28:28 +0000563 );
drh21206082011-04-04 18:22:02 +0000564 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000565 assert( pOld==pIndex || pOld==0 );
566 }
567 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000568 }
569
dan1da40a32009-09-19 17:00:31 +0000570 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000571 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000572
573 /* Delete the Table structure itself.
574 */
dand46def72010-07-24 11:28:28 +0000575 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000576 sqlite3DbFree(db, pTable->zName);
577 sqlite3DbFree(db, pTable->zColAff);
578 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000579#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000580 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000581#endif
drh078e4082010-07-28 19:17:51 +0000582#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000583 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000584#endif
drh633e6d52008-07-28 19:34:53 +0000585 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000586
587 /* Verify that no lookaside memory was used by schema tables */
588 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000589}
590
591/*
drh5edc3122001-09-13 21:53:09 +0000592** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000593** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000594*/
drh9bb575f2004-09-06 17:24:11 +0000595void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000596 Table *p;
drh956bc922004-07-24 17:38:29 +0000597 Db *pDb;
598
drhd229ca92002-01-09 13:30:41 +0000599 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000600 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000601 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000602 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000603 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000604 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000605 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000606 sqlite3Strlen30(zTabName),0);
dan1feeaed2010-07-23 15:41:47 +0000607 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000608 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000609}
610
611/*
drha99db3b2004-06-19 14:49:12 +0000612** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000613** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000614** is obtained from sqliteMalloc() and must be freed by the calling
615** function.
drh75897232000-05-29 14:26:00 +0000616**
drh24fb6272009-05-01 21:13:36 +0000617** Any quotation marks (ex: "name", 'name', [name], or `name`) that
618** surround the body of the token are removed.
619**
drhc96d8532005-05-03 12:30:33 +0000620** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000621** are not \000 terminated and are not persistent. The returned string
622** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000623*/
drh17435752007-08-16 04:30:38 +0000624char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000625 char *zName;
626 if( pName ){
drh17435752007-08-16 04:30:38 +0000627 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000628 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000629 }else{
630 zName = 0;
631 }
drh75897232000-05-29 14:26:00 +0000632 return zName;
633}
634
635/*
danielk1977cbb18d22004-05-28 11:37:27 +0000636** Open the sqlite_master table stored in database number iDb for
637** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000638*/
danielk1977c00da102006-01-07 13:21:04 +0000639void sqlite3OpenMasterTable(Parse *p, int iDb){
640 Vdbe *v = sqlite3GetVdbe(p);
641 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000642 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000643 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000644 if( p->nTab==0 ){
645 p->nTab = 1;
646 }
drhe0bc4042002-06-25 01:09:11 +0000647}
648
649/*
danielk197704103022009-02-03 16:51:24 +0000650** Parameter zName points to a nul-terminated buffer containing the name
651** of a database ("main", "temp" or the name of an attached db). This
652** function returns the index of the named database in db->aDb[], or
653** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000654*/
danielk197704103022009-02-03 16:51:24 +0000655int sqlite3FindDbName(sqlite3 *db, const char *zName){
656 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000657 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000658 Db *pDb;
659 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000660 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000661 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000662 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000663 break;
drh73c42a12004-11-20 18:13:10 +0000664 }
danielk1977cbb18d22004-05-28 11:37:27 +0000665 }
666 }
danielk1977576ec6b2005-01-21 11:55:25 +0000667 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000668}
669
danielk197704103022009-02-03 16:51:24 +0000670/*
671** The token *pName contains the name of a database (either "main" or
672** "temp" or the name of an attached db). This routine returns the
673** index of the named database in db->aDb[], or -1 if the named db
674** does not exist.
675*/
676int sqlite3FindDb(sqlite3 *db, Token *pName){
677 int i; /* Database number */
678 char *zName; /* Name we are searching for */
679 zName = sqlite3NameFromToken(db, pName);
680 i = sqlite3FindDbName(db, zName);
681 sqlite3DbFree(db, zName);
682 return i;
683}
684
drh0e3d7472004-06-19 17:33:07 +0000685/* The table or view or trigger name is passed to this routine via tokens
686** pName1 and pName2. If the table name was fully qualified, for example:
687**
688** CREATE TABLE xxx.yyy (...);
689**
690** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
691** the table name is not fully qualified, i.e.:
692**
693** CREATE TABLE yyy(...);
694**
695** Then pName1 is set to "yyy" and pName2 is "".
696**
697** This routine sets the *ppUnqual pointer to point at the token (pName1 or
698** pName2) that stores the unqualified table name. The index of the
699** database "xxx" is returned.
700*/
danielk1977ef2cb632004-05-29 02:37:19 +0000701int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000702 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000703 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000704 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
705 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000706){
drh0e3d7472004-06-19 17:33:07 +0000707 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000708 sqlite3 *db = pParse->db;
709
drhc4a64fa2009-05-11 20:53:28 +0000710 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000711 if( db->init.busy ) {
712 sqlite3ErrorMsg(pParse, "corrupt database");
713 pParse->nErr++;
714 return -1;
715 }
danielk1977cbb18d22004-05-28 11:37:27 +0000716 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000717 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000718 if( iDb<0 ){
719 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
720 pParse->nErr++;
721 return -1;
722 }
723 }else{
724 assert( db->init.iDb==0 || db->init.busy );
725 iDb = db->init.iDb;
726 *pUnqual = pName1;
727 }
728 return iDb;
729}
730
731/*
danielk1977d8123362004-06-12 09:25:12 +0000732** This routine is used to check if the UTF-8 string zName is a legal
733** unqualified name for a new schema object (table, index, view or
734** trigger). All names are legal except those that begin with the string
735** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
736** is reserved for internal use.
737*/
738int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000739 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000740 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000741 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000742 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
743 return SQLITE_ERROR;
744 }
745 return SQLITE_OK;
746}
747
748/*
drh75897232000-05-29 14:26:00 +0000749** Begin constructing a new table representation in memory. This is
750** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000751** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000752** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000753** flag is true if the table should be stored in the auxiliary database
754** file instead of in the main database file. This is normally the case
755** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000756** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000757**
drhf57b3392001-10-08 13:22:32 +0000758** The new table record is initialized and put in pParse->pNewTable.
759** As more of the CREATE TABLE statement is parsed, additional action
760** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000761** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000762** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000763*/
danielk19774adee202004-05-08 08:23:19 +0000764void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000765 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000766 Token *pName1, /* First part of the name of the table or view */
767 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000768 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000769 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000770 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000771 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000772){
drh75897232000-05-29 14:26:00 +0000773 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000774 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000775 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000776 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000777 int iDb; /* Database number to create the table in */
778 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000779
danielk1977cbb18d22004-05-28 11:37:27 +0000780 /* The table or view name to create is passed to this routine via tokens
781 ** pName1 and pName2. If the table name was fully qualified, for example:
782 **
783 ** CREATE TABLE xxx.yyy (...);
784 **
785 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
786 ** the table name is not fully qualified, i.e.:
787 **
788 ** CREATE TABLE yyy(...);
789 **
790 ** Then pName1 is set to "yyy" and pName2 is "".
791 **
792 ** The call below sets the pName pointer to point at the token (pName1 or
793 ** pName2) that stores the unqualified table name. The variable iDb is
794 ** set to the index of the database that the table or view is to be
795 ** created in.
796 */
danielk1977ef2cb632004-05-29 02:37:19 +0000797 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000798 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000799 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
800 /* If creating a temp table, the name may not be qualified. Unless
801 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000802 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000803 return;
804 }
danielk197753c0f742005-03-29 03:10:59 +0000805 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000806
807 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000808 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000809 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000810 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000811 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000812 }
drh1d85d932004-02-14 23:05:52 +0000813 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000814#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000815 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000816 {
817 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000818 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000819 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000820 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000821 }
drhe5f9c642003-01-13 23:27:31 +0000822 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000823 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000824 code = SQLITE_CREATE_TEMP_VIEW;
825 }else{
826 code = SQLITE_CREATE_VIEW;
827 }
828 }else{
danielk197753c0f742005-03-29 03:10:59 +0000829 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000830 code = SQLITE_CREATE_TEMP_TABLE;
831 }else{
832 code = SQLITE_CREATE_TABLE;
833 }
834 }
danielk1977f1a381e2006-06-16 08:01:02 +0000835 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000836 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000837 }
838 }
839#endif
drhf57b3392001-10-08 13:22:32 +0000840
drhf57b3392001-10-08 13:22:32 +0000841 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000842 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000843 ** it does. The exception is if the statement being parsed was passed
844 ** to an sqlite3_declare_vtab() call. In that case only the column names
845 ** and types will be used, so there is no need to test for namespace
846 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000847 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000848 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000849 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000850 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
851 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000852 }
dana16d1062010-09-28 17:37:28 +0000853 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000854 if( pTable ){
855 if( !noErr ){
856 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000857 }else{
858 assert( !db->init.busy );
859 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000860 }
861 goto begin_table_error;
862 }
drh8a8a0d12010-09-28 20:26:44 +0000863 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000864 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
865 goto begin_table_error;
866 }
drh75897232000-05-29 14:26:00 +0000867 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000868
danielk197726783a52007-08-29 14:06:22 +0000869 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000870 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000871 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000872 pParse->rc = SQLITE_NOMEM;
873 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000874 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000875 }
drh75897232000-05-29 14:26:00 +0000876 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000877 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000878 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000879 pTable->nRef = 1;
drh15564052010-09-25 22:32:56 +0000880 pTable->nRowEst = 1000000;
drhc4a64fa2009-05-11 20:53:28 +0000881 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000882 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000883
drh4794f732004-11-05 17:17:50 +0000884 /* If this is the magic sqlite_sequence table used by autoincrement,
885 ** then record a pointer to this table in the main database structure
886 ** so that INSERT can find the table easily.
887 */
888#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000889 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000890 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000891 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000892 }
893#endif
894
drh17f71932002-02-21 12:01:27 +0000895 /* Begin generating the code that will insert the table record into
896 ** the SQLITE_MASTER table. Note in particular that we must go ahead
897 ** and allocate the record number for the table entry now. Before any
898 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
899 ** indices to be created and the table record must come before the
900 ** indices. Hence, the record number for the table must be allocated
901 ** now.
902 */
danielk19774adee202004-05-08 08:23:19 +0000903 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000904 int j1;
drhe321c292006-01-12 01:56:43 +0000905 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000906 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000907 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000908
danielk197720b1eaf2006-07-26 16:22:14 +0000909#ifndef SQLITE_OMIT_VIRTUALTABLE
910 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000911 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000912 }
913#endif
914
danielk197736963fd2005-02-19 08:18:05 +0000915 /* If the file format and encoding in the database have not been set,
916 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000917 */
drhb7654112008-01-12 12:48:07 +0000918 reg1 = pParse->regRowid = ++pParse->nMem;
919 reg2 = pParse->regRoot = ++pParse->nMem;
920 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000921 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000922 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000923 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000924 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000925 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000926 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000927 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000928 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000929 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000930 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000931
drh4794f732004-11-05 17:17:50 +0000932 /* This just creates a place-holder record in the sqlite_master table.
933 ** The record created does not contain anything yet. It will be replaced
934 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000935 **
drh0fa991b2009-03-21 16:19:26 +0000936 ** The rowid for the new entry is left in register pParse->regRowid.
937 ** The root page number of the new table is left in reg pParse->regRoot.
938 ** The rowid and root page number values are needed by the code that
939 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000940 */
danielk1977f1a381e2006-06-16 08:01:02 +0000941#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
942 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000943 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000944 }else
945#endif
946 {
drhb7654112008-01-12 12:48:07 +0000947 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000948 }
danielk1977c00da102006-01-07 13:21:04 +0000949 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000950 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
951 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
952 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
953 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000954 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000955 }
drh23bf66d2004-12-14 03:34:34 +0000956
957 /* Normal (non-error) return. */
958 return;
959
960 /* If an error occurs, we jump here */
961begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000962 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000963 return;
drh75897232000-05-29 14:26:00 +0000964}
965
966/*
danielk1977c60e9b82005-01-31 12:42:29 +0000967** This macro is used to compare two strings in a case-insensitive manner.
968** It is slightly faster than calling sqlite3StrICmp() directly, but
969** produces larger code.
970**
971** WARNING: This macro is not compatible with the strcmp() family. It
972** returns true if the two strings are equal, otherwise false.
973*/
974#define STRICMP(x, y) (\
975sqlite3UpperToLower[*(unsigned char *)(x)]== \
976sqlite3UpperToLower[*(unsigned char *)(y)] \
977&& sqlite3StrICmp((x)+1,(y)+1)==0 )
978
979/*
drh75897232000-05-29 14:26:00 +0000980** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000981**
982** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000983** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000984** first to get things going. Then this routine is called for each
985** column.
drh75897232000-05-29 14:26:00 +0000986*/
danielk19774adee202004-05-08 08:23:19 +0000987void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000988 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000989 int i;
drha99db3b2004-06-19 14:49:12 +0000990 char *z;
drhc9b84a12002-06-20 11:36:48 +0000991 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000992 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000993 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000994#if SQLITE_MAX_COLUMN
995 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000996 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
997 return;
998 }
drhbb4957f2008-03-20 14:03:29 +0000999#endif
danielk1977ae74e032008-12-23 11:11:51 +00001000 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001001 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001002 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001003 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001004 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001005 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001006 return;
1007 }
1008 }
drh75897232000-05-29 14:26:00 +00001009 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001010 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001011 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001012 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001013 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001014 return;
1015 }
drh6d4abfb2001-10-22 02:58:08 +00001016 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001017 }
drhc9b84a12002-06-20 11:36:48 +00001018 pCol = &p->aCol[p->nCol];
1019 memset(pCol, 0, sizeof(p->aCol[0]));
1020 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001021
1022 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001023 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1024 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001025 */
danielk19774f057f92004-06-08 00:02:33 +00001026 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +00001027 p->nCol++;
drh75897232000-05-29 14:26:00 +00001028}
1029
1030/*
drh382c0242001-10-06 16:33:02 +00001031** This routine is called by the parser while in the middle of
1032** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1033** been seen on a column. This routine sets the notNull flag on
1034** the column currently under construction.
1035*/
danielk19774adee202004-05-08 08:23:19 +00001036void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001037 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001038 p = pParse->pNewTable;
1039 if( p==0 || NEVER(p->nCol<1) ) return;
1040 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001041}
1042
1043/*
danielk197752a83fb2005-01-31 12:56:44 +00001044** Scan the column type name zType (length nType) and return the
1045** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001046**
1047** This routine does a case-independent search of zType for the
1048** substrings in the following table. If one of the substrings is
1049** found, the corresponding affinity is returned. If zType contains
1050** more than one of the substrings, entries toward the top of
1051** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001052** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001053**
1054** Substring | Affinity
1055** --------------------------------
1056** 'INT' | SQLITE_AFF_INTEGER
1057** 'CHAR' | SQLITE_AFF_TEXT
1058** 'CLOB' | SQLITE_AFF_TEXT
1059** 'TEXT' | SQLITE_AFF_TEXT
1060** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001061** 'REAL' | SQLITE_AFF_REAL
1062** 'FLOA' | SQLITE_AFF_REAL
1063** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001064**
1065** If none of the substrings in the above table are found,
1066** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001067*/
drhb7916a72009-05-27 10:31:29 +00001068char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +00001069 u32 h = 0;
1070 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +00001071
drhb7916a72009-05-27 10:31:29 +00001072 if( zIn ) while( zIn[0] ){
1073 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001074 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001075 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1076 aff = SQLITE_AFF_TEXT;
1077 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1078 aff = SQLITE_AFF_TEXT;
1079 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1080 aff = SQLITE_AFF_TEXT;
1081 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001082 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001083 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001084#ifndef SQLITE_OMIT_FLOATING_POINT
1085 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1086 && aff==SQLITE_AFF_NUMERIC ){
1087 aff = SQLITE_AFF_REAL;
1088 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1089 && aff==SQLITE_AFF_NUMERIC ){
1090 aff = SQLITE_AFF_REAL;
1091 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1092 && aff==SQLITE_AFF_NUMERIC ){
1093 aff = SQLITE_AFF_REAL;
1094#endif
danielk1977201f7162005-02-01 02:13:29 +00001095 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001096 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001097 break;
danielk197752a83fb2005-01-31 12:56:44 +00001098 }
1099 }
danielk1977b3dff962005-02-01 01:21:55 +00001100
1101 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001102}
1103
1104/*
drh382c0242001-10-06 16:33:02 +00001105** This routine is called by the parser while in the middle of
1106** parsing a CREATE TABLE statement. The pFirst token is the first
1107** token in the sequence of tokens that describe the type of the
1108** column currently under construction. pLast is the last token
1109** in the sequence. Use this information to construct a string
1110** that contains the typename of the column and store that string
1111** in zType.
1112*/
drh487e2622005-06-25 18:42:14 +00001113void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001114 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001115 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001116
drhc4a64fa2009-05-11 20:53:28 +00001117 p = pParse->pNewTable;
1118 if( p==0 || NEVER(p->nCol<1) ) return;
1119 pCol = &p->aCol[p->nCol-1];
1120 assert( pCol->zType==0 );
1121 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001122 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001123}
1124
1125/*
danielk19777977a172004-11-09 12:44:37 +00001126** The expression is the default value for the most recently added column
1127** of the table currently under construction.
1128**
1129** Default value expressions must be constant. Raise an exception if this
1130** is not the case.
drhd9b02572001-04-15 00:37:09 +00001131**
1132** This routine is called by the parser while in the middle of
1133** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001134*/
drhb7916a72009-05-27 10:31:29 +00001135void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001136 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001137 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001138 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001139 p = pParse->pNewTable;
1140 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001141 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001142 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001143 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1144 pCol->zName);
1145 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001146 /* A copy of pExpr is used instead of the original, as pExpr contains
1147 ** tokens that point to volatile memory. The 'span' of the expression
1148 ** is required by pragma table_info.
1149 */
drh633e6d52008-07-28 19:34:53 +00001150 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001151 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1152 sqlite3DbFree(db, pCol->zDflt);
1153 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001154 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001155 }
danielk19777977a172004-11-09 12:44:37 +00001156 }
drhb7916a72009-05-27 10:31:29 +00001157 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001158}
1159
1160/*
drh4a324312001-12-21 14:30:42 +00001161** Designate the PRIMARY KEY for the table. pList is a list of names
1162** of columns that form the primary key. If pList is NULL, then the
1163** most recently added column of the table is the primary key.
1164**
1165** A table can have at most one primary key. If the table already has
1166** a primary key (and this is the second primary key) then create an
1167** error.
1168**
1169** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001170** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001171** field of the table under construction to be the index of the
1172** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1173** no INTEGER PRIMARY KEY.
1174**
1175** If the key is not an INTEGER PRIMARY KEY, then create a unique
1176** index for the key. No index is created for INTEGER PRIMARY KEYs.
1177*/
drh205f48e2004-11-05 00:43:11 +00001178void sqlite3AddPrimaryKey(
1179 Parse *pParse, /* Parsing context */
1180 ExprList *pList, /* List of field names to be indexed */
1181 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001182 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1183 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001184){
drh4a324312001-12-21 14:30:42 +00001185 Table *pTab = pParse->pNewTable;
1186 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001187 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001188 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001189 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001190 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001191 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001192 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001193 }
drh7d10d5a2008-08-20 16:35:10 +00001194 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001195 if( pList==0 ){
1196 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001197 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh78100cc2003-08-23 22:40:53 +00001198 }else{
danielk19770202b292004-06-09 09:55:16 +00001199 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001200 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001201 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1202 break;
1203 }
drh78100cc2003-08-23 22:40:53 +00001204 }
drh6e4fc2c2005-09-15 21:24:51 +00001205 if( iCol<pTab->nCol ){
drha371ace2012-09-13 14:22:47 +00001206 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh6e4fc2c2005-09-15 21:24:51 +00001207 }
drh4a324312001-12-21 14:30:42 +00001208 }
danielk19770202b292004-06-09 09:55:16 +00001209 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001210 }
1211 if( iCol>=0 && iCol<pTab->nCol ){
1212 zType = pTab->aCol[iCol].zType;
1213 }
drhfdd6e852005-12-16 01:06:16 +00001214 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1215 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001216 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001217 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001218 assert( autoInc==0 || autoInc==1 );
1219 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001220 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001221#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001222 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1223 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001224#endif
drh4a324312001-12-21 14:30:42 +00001225 }else{
dan1da40a32009-09-19 17:00:31 +00001226 Index *p;
1227 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1228 if( p ){
1229 p->autoIndex = 2;
1230 }
drhe0194f22003-02-26 13:52:51 +00001231 pList = 0;
drh4a324312001-12-21 14:30:42 +00001232 }
drhe0194f22003-02-26 13:52:51 +00001233
1234primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001235 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001236 return;
drh4a324312001-12-21 14:30:42 +00001237}
1238
1239/*
drhffe07b22005-11-03 00:41:17 +00001240** Add a new CHECK constraint to the table currently under construction.
1241*/
1242void sqlite3AddCheckConstraint(
1243 Parse *pParse, /* Parsing context */
1244 Expr *pCheckExpr /* The check expression */
1245){
1246#ifndef SQLITE_OMIT_CHECK
1247 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001248 if( pTab && !IN_DECLARE_VTAB ){
drh2938f922012-03-07 19:13:29 +00001249 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1250 if( pParse->constraintName.n ){
1251 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1252 }
drh33e619f2009-05-28 01:00:55 +00001253 }else
drhffe07b22005-11-03 00:41:17 +00001254#endif
drh33e619f2009-05-28 01:00:55 +00001255 {
drh2938f922012-03-07 19:13:29 +00001256 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001257 }
drhffe07b22005-11-03 00:41:17 +00001258}
1259
1260/*
drhd3d39e92004-05-20 22:16:29 +00001261** Set the collation function of the most recently parsed table column
1262** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001263*/
danielk197739002502007-11-12 09:50:26 +00001264void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001265 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001266 int i;
danielk197739002502007-11-12 09:50:26 +00001267 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001268 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001269
danielk1977b8cbb872006-06-19 05:33:45 +00001270 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001271 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001272 db = pParse->db;
1273 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001274 if( !zColl ) return;
1275
drhc4a64fa2009-05-11 20:53:28 +00001276 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001277 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001278 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001279
1280 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1281 ** then an index may have been created on this column before the
1282 ** collation type was added. Correct this if it is the case.
1283 */
1284 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1285 assert( pIdx->nColumn==1 );
1286 if( pIdx->aiColumn[0]==i ){
1287 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001288 }
1289 }
danielk197739002502007-11-12 09:50:26 +00001290 }else{
drh633e6d52008-07-28 19:34:53 +00001291 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001292 }
danielk19777cedc8d2004-06-10 10:50:08 +00001293}
1294
danielk1977466be562004-06-10 02:16:01 +00001295/*
1296** This function returns the collation sequence for database native text
1297** encoding identified by the string zName, length nName.
1298**
1299** If the requested collation sequence is not available, or not available
1300** in the database native encoding, the collation factory is invoked to
1301** request it. If the collation factory does not supply such a sequence,
1302** and the sequence is available in another text encoding, then that is
1303** returned instead.
1304**
1305** If no versions of the requested collations sequence are available, or
1306** another error occurs, NULL is returned and an error message written into
1307** pParse.
drha34001c2007-02-02 12:44:37 +00001308**
1309** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1310** invokes the collation factory if the named collation cannot be found
1311** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001312**
1313** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001314*/
drhc4a64fa2009-05-11 20:53:28 +00001315CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001316 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001317 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001318 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001319 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001320
drhc4a64fa2009-05-11 20:53:28 +00001321 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001322 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001323 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001324 }
1325
danielk19770202b292004-06-09 09:55:16 +00001326 return pColl;
1327}
1328
1329
drh8e2ca022002-06-17 17:07:19 +00001330/*
drh3f7d4e42004-07-24 14:35:58 +00001331** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001332**
1333** The schema cookie is used to determine when the schema for the
1334** database changes. After each schema change, the cookie value
1335** changes. When a process first reads the schema it records the
1336** cookie. Thereafter, whenever it goes to access the database,
1337** it checks the cookie to make sure the schema has not changed
1338** since it was last read.
1339**
1340** This plan is not completely bullet-proof. It is possible for
1341** the schema to change multiple times and for the cookie to be
1342** set back to prior value. But schema changes are infrequent
1343** and the probability of hitting the same cookie value is only
1344** 1 chance in 2^32. So we're safe enough.
1345*/
drh9cbf3422008-01-17 16:22:13 +00001346void sqlite3ChangeCookie(Parse *pParse, int iDb){
1347 int r1 = sqlite3GetTempReg(pParse);
1348 sqlite3 *db = pParse->db;
1349 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001350 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001351 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001352 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001353 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001354}
1355
1356/*
drh969fa7c2002-02-18 18:30:32 +00001357** Measure the number of characters needed to output the given
1358** identifier. The number returned includes any quotes used
1359** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001360**
1361** The estimate is conservative. It might be larger that what is
1362** really needed.
drh969fa7c2002-02-18 18:30:32 +00001363*/
1364static int identLength(const char *z){
1365 int n;
drh17f71932002-02-21 12:01:27 +00001366 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001367 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001368 }
drh234c39d2004-07-24 03:30:47 +00001369 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001370}
1371
1372/*
danielk19771b870de2009-03-14 08:37:23 +00001373** The first parameter is a pointer to an output buffer. The second
1374** parameter is a pointer to an integer that contains the offset at
1375** which to write into the output buffer. This function copies the
1376** nul-terminated string pointed to by the third parameter, zSignedIdent,
1377** to the specified offset in the buffer and updates *pIdx to refer
1378** to the first byte after the last byte written before returning.
1379**
1380** If the string zSignedIdent consists entirely of alpha-numeric
1381** characters, does not begin with a digit and is not an SQL keyword,
1382** then it is copied to the output buffer exactly as it is. Otherwise,
1383** it is quoted using double-quotes.
1384*/
drhc4a64fa2009-05-11 20:53:28 +00001385static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001386 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001387 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001388 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001389
drh17f71932002-02-21 12:01:27 +00001390 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001391 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001392 }
danielk19771b870de2009-03-14 08:37:23 +00001393 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1394 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001395 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001396 }
1397
drh234c39d2004-07-24 03:30:47 +00001398 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001399 for(j=0; zIdent[j]; j++){
1400 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001401 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001402 }
drh234c39d2004-07-24 03:30:47 +00001403 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001404 z[i] = 0;
1405 *pIdx = i;
1406}
1407
1408/*
1409** Generate a CREATE TABLE statement appropriate for the given
1410** table. Memory to hold the text of the statement is obtained
1411** from sqliteMalloc() and must be freed by the calling function.
1412*/
drh1d34fde2009-02-03 15:50:33 +00001413static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001414 int i, k, n;
1415 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001416 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001417 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001418 n = 0;
drh234c39d2004-07-24 03:30:47 +00001419 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001420 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001421 }
1422 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001423 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001424 zSep = "";
1425 zSep2 = ",";
1426 zEnd = ")";
1427 }else{
1428 zSep = "\n ";
1429 zSep2 = ",\n ";
1430 zEnd = "\n)";
1431 }
drhe0bc4042002-06-25 01:09:11 +00001432 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001433 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001434 if( zStmt==0 ){
1435 db->mallocFailed = 1;
1436 return 0;
1437 }
drhbdb339f2009-02-02 18:03:21 +00001438 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001439 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001440 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001441 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001442 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001443 static const char * const azType[] = {
1444 /* SQLITE_AFF_TEXT */ " TEXT",
1445 /* SQLITE_AFF_NONE */ "",
1446 /* SQLITE_AFF_NUMERIC */ " NUM",
1447 /* SQLITE_AFF_INTEGER */ " INT",
1448 /* SQLITE_AFF_REAL */ " REAL"
1449 };
1450 int len;
1451 const char *zType;
1452
drh5bb3eb92007-05-04 13:15:55 +00001453 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001454 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001455 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001456 identPut(zStmt, &k, pCol->zName);
1457 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001458 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001459 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1460 testcase( pCol->affinity==SQLITE_AFF_NONE );
1461 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1462 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1463 testcase( pCol->affinity==SQLITE_AFF_REAL );
1464
1465 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1466 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001467 assert( pCol->affinity==SQLITE_AFF_NONE
1468 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001469 memcpy(&zStmt[k], zType, len);
1470 k += len;
1471 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001472 }
drh5bb3eb92007-05-04 13:15:55 +00001473 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001474 return zStmt;
1475}
1476
1477/*
drh75897232000-05-29 14:26:00 +00001478** This routine is called to report the final ")" that terminates
1479** a CREATE TABLE statement.
1480**
drhf57b3392001-10-08 13:22:32 +00001481** The table structure that other action routines have been building
1482** is added to the internal hash tables, assuming no errors have
1483** occurred.
drh75897232000-05-29 14:26:00 +00001484**
drh1d85d932004-02-14 23:05:52 +00001485** An entry for the table is made in the master table on disk, unless
1486** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001487** it means we are reading the sqlite_master table because we just
1488** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001489** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001490** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001491**
1492** If the pSelect argument is not NULL, it means that this routine
1493** was called to create a table generated from a
1494** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1495** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001496*/
danielk197719a8e7e2005-03-17 05:03:38 +00001497void sqlite3EndTable(
1498 Parse *pParse, /* Parse context */
1499 Token *pCons, /* The ',' token after the last column defn. */
1500 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1501 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1502){
drh75897232000-05-29 14:26:00 +00001503 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001504 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001505 int iDb;
drh75897232000-05-29 14:26:00 +00001506
drh8af73d42009-05-13 22:58:28 +00001507 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001508 return;
1509 }
drh28037572000-08-02 13:47:41 +00001510 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001511 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001512
danielk1977517eb642004-06-07 10:00:31 +00001513 assert( !db->init.busy || !pSelect );
1514
drhb9bb7c12006-06-11 23:41:55 +00001515 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001516
drhffe07b22005-11-03 00:41:17 +00001517#ifndef SQLITE_OMIT_CHECK
1518 /* Resolve names in all CHECK constraint expressions.
1519 */
1520 if( p->pCheck ){
1521 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1522 NameContext sNC; /* Name context for pParse->pNewTable */
drh2938f922012-03-07 19:13:29 +00001523 ExprList *pList; /* List of all CHECK constraints */
1524 int i; /* Loop counter */
drhffe07b22005-11-03 00:41:17 +00001525
1526 memset(&sNC, 0, sizeof(sNC));
1527 memset(&sSrc, 0, sizeof(sSrc));
1528 sSrc.nSrc = 1;
1529 sSrc.a[0].zName = p->zName;
1530 sSrc.a[0].pTab = p;
1531 sSrc.a[0].iCursor = -1;
1532 sNC.pParse = pParse;
1533 sNC.pSrcList = &sSrc;
drha51009b2012-05-21 19:11:25 +00001534 sNC.ncFlags = NC_IsCheck;
drh2938f922012-03-07 19:13:29 +00001535 pList = p->pCheck;
1536 for(i=0; i<pList->nExpr; i++){
1537 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
1538 return;
1539 }
drhffe07b22005-11-03 00:41:17 +00001540 }
1541 }
1542#endif /* !defined(SQLITE_OMIT_CHECK) */
1543
drh1d85d932004-02-14 23:05:52 +00001544 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001545 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1546 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001547 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001548 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001549 */
drh1d85d932004-02-14 23:05:52 +00001550 if( db->init.busy ){
1551 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001552 }
1553
drhe3c41372001-09-17 20:25:58 +00001554 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001555 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001556 **
drhe0bc4042002-06-25 01:09:11 +00001557 ** If this is a TEMPORARY table, write the entry into the auxiliary
1558 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001559 */
drh1d85d932004-02-14 23:05:52 +00001560 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001561 int n;
drhd8bc7082000-06-07 23:51:50 +00001562 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001563 char *zType; /* "view" or "table" */
1564 char *zType2; /* "VIEW" or "TABLE" */
1565 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001566
danielk19774adee202004-05-08 08:23:19 +00001567 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001568 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001569
drh66a51672008-01-03 00:01:23 +00001570 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001571
drh0fa991b2009-03-21 16:19:26 +00001572 /*
1573 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001574 */
drh4ff6dfa2002-03-03 23:06:00 +00001575 if( p->pSelect==0 ){
1576 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001577 zType = "table";
1578 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001579#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001580 }else{
1581 /* A view */
drh4794f732004-11-05 17:17:50 +00001582 zType = "view";
1583 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001584#endif
drh4ff6dfa2002-03-03 23:06:00 +00001585 }
danielk1977517eb642004-06-07 10:00:31 +00001586
danielk1977517eb642004-06-07 10:00:31 +00001587 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1588 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001589 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001590 **
1591 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1592 ** suitable state to query for the column names and types to be used
1593 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001594 **
1595 ** A shared-cache write-lock is not required to write to the new table,
1596 ** as a schema-lock must have already been obtained to create it. Since
1597 ** a schema-lock excludes all other database users, the write-lock would
1598 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001599 */
1600 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001601 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001602 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001603
danielk19776ab3a2e2009-02-19 14:39:25 +00001604 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001605 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001606 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001607 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001608 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001609 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001610 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001611 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001612 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001613 if( pSelTab==0 ) return;
1614 assert( p->aCol==0 );
1615 p->nCol = pSelTab->nCol;
1616 p->aCol = pSelTab->aCol;
1617 pSelTab->nCol = 0;
1618 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001619 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001620 }
1621 }
drh4794f732004-11-05 17:17:50 +00001622
drh4794f732004-11-05 17:17:50 +00001623 /* Compute the complete text of the CREATE statement */
1624 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001625 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001626 }else{
drh1bd10f82008-12-10 21:19:56 +00001627 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001628 zStmt = sqlite3MPrintf(db,
1629 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1630 );
drh4794f732004-11-05 17:17:50 +00001631 }
1632
1633 /* A slot for the record has already been allocated in the
1634 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001635 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001636 */
1637 sqlite3NestedParse(pParse,
1638 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001639 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1640 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001641 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001642 zType,
1643 p->zName,
1644 p->zName,
drhb7654112008-01-12 12:48:07 +00001645 pParse->regRoot,
1646 zStmt,
1647 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001648 );
drh633e6d52008-07-28 19:34:53 +00001649 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001650 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001651
1652#ifndef SQLITE_OMIT_AUTOINCREMENT
1653 /* Check to see if we need to create an sqlite_sequence table for
1654 ** keeping track of autoincrement keys.
1655 */
drh7d10d5a2008-08-20 16:35:10 +00001656 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001657 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001658 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001659 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001660 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001661 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1662 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001663 );
1664 }
1665 }
1666#endif
drh4794f732004-11-05 17:17:50 +00001667
1668 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001669 sqlite3VdbeAddParseSchemaOp(v, iDb,
1670 sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
drh75897232000-05-29 14:26:00 +00001671 }
drh17e9e292003-02-01 13:53:28 +00001672
drh2958a4e2004-11-12 03:56:15 +00001673
drh17e9e292003-02-01 13:53:28 +00001674 /* Add the table to the in-memory representation of the database.
1675 */
drh8af73d42009-05-13 22:58:28 +00001676 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001677 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001678 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001679 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001680 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001681 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001682 if( pOld ){
1683 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001684 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001685 return;
1686 }
drh17e9e292003-02-01 13:53:28 +00001687 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001688 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001689
1690#ifndef SQLITE_OMIT_ALTERTABLE
1691 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001692 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001693 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001694 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001695 if( pCons->z==0 ){
1696 pCons = pEnd;
1697 }
drh1bd10f82008-12-10 21:19:56 +00001698 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001699 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001700 }
1701#endif
drh17e9e292003-02-01 13:53:28 +00001702 }
drh75897232000-05-29 14:26:00 +00001703}
1704
drhb7f91642004-10-31 02:22:47 +00001705#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001706/*
drha76b5df2002-02-23 02:32:10 +00001707** The parser calls this routine in order to create a new VIEW
1708*/
danielk19774adee202004-05-08 08:23:19 +00001709void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001710 Parse *pParse, /* The parsing context */
1711 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001712 Token *pName1, /* The token that holds the name of the view */
1713 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001714 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001715 int isTemp, /* TRUE for a TEMPORARY view */
1716 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001717){
drha76b5df2002-02-23 02:32:10 +00001718 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001719 int n;
drhb7916a72009-05-27 10:31:29 +00001720 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001721 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001722 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00001723 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00001724 int iDb;
drh17435752007-08-16 04:30:38 +00001725 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001726
drh7c3d64f2005-06-06 15:32:08 +00001727 if( pParse->nVar>0 ){
1728 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001729 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001730 return;
1731 }
drhfdd48a72006-09-11 23:45:48 +00001732 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001733 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001734 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001735 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001736 return;
1737 }
danielk1977ef2cb632004-05-29 02:37:19 +00001738 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001739 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001740 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001741 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001742 ){
drh633e6d52008-07-28 19:34:53 +00001743 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001744 return;
1745 }
drh174b6192002-12-03 02:22:52 +00001746
drh4b59ab52002-08-24 18:24:51 +00001747 /* Make a copy of the entire SELECT statement that defines the view.
1748 ** This will force all the Expr.token.z values to be dynamically
1749 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001750 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001751 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001752 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001753 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001754 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001755 return;
1756 }
drh17435752007-08-16 04:30:38 +00001757 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001758 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001759 }
drh4b59ab52002-08-24 18:24:51 +00001760
1761 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1762 ** the end.
1763 */
drha76b5df2002-02-23 02:32:10 +00001764 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001765 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001766 sEnd.z += sEnd.n;
1767 }
1768 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001769 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001770 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001771 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001772 sEnd.z = &z[n-1];
1773 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001774
danielk19774adee202004-05-08 08:23:19 +00001775 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001776 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001777 return;
drh417be792002-03-03 18:59:40 +00001778}
drhb7f91642004-10-31 02:22:47 +00001779#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001780
danielk1977fe3fcbe22006-06-12 12:08:45 +00001781#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001782/*
1783** The Table structure pTable is really a VIEW. Fill in the names of
1784** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001785** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001786*/
danielk19774adee202004-05-08 08:23:19 +00001787int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001788 Table *pSelTab; /* A fake table from which we get the result set */
1789 Select *pSel; /* Copy of the SELECT that implements the view */
1790 int nErr = 0; /* Number of errors encountered */
1791 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001792 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001793 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001794
1795 assert( pTable );
1796
danielk1977fe3fcbe22006-06-12 12:08:45 +00001797#ifndef SQLITE_OMIT_VIRTUALTABLE
1798 if( sqlite3VtabCallConnect(pParse, pTable) ){
1799 return SQLITE_ERROR;
1800 }
drh4cbdda92006-06-14 19:00:20 +00001801 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001802#endif
1803
1804#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001805 /* A positive nCol means the columns names for this view are
1806 ** already known.
1807 */
1808 if( pTable->nCol>0 ) return 0;
1809
1810 /* A negative nCol is a special marker meaning that we are currently
1811 ** trying to compute the column names. If we enter this routine with
1812 ** a negative nCol, it means two or more views form a loop, like this:
1813 **
1814 ** CREATE VIEW one AS SELECT * FROM two;
1815 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001816 **
drh768578e2009-05-12 00:40:12 +00001817 ** Actually, the error above is now caught prior to reaching this point.
1818 ** But the following test is still important as it does come up
1819 ** in the following:
1820 **
1821 ** CREATE TABLE main.ex1(a);
1822 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1823 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001824 */
1825 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001826 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001827 return 1;
1828 }
drh85c23c62005-08-20 03:03:04 +00001829 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001830
1831 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001832 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1833 ** "*" elements in the results set of the view and will assign cursors
1834 ** to the elements of the FROM clause. But we do not want these changes
1835 ** to be permanent. So the computation is done on a copy of the SELECT
1836 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001837 */
drh9b3187e2005-01-18 14:45:47 +00001838 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001839 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001840 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001841 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001842 n = pParse->nTab;
1843 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1844 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001845 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001846#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001847 xAuth = db->xAuth;
1848 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001849 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001850 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001851#else
drh7d10d5a2008-08-20 16:35:10 +00001852 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001853#endif
drhd9da78a2009-03-24 15:08:09 +00001854 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001855 pParse->nTab = n;
1856 if( pSelTab ){
1857 assert( pTable->aCol==0 );
1858 pTable->nCol = pSelTab->nCol;
1859 pTable->aCol = pSelTab->aCol;
1860 pSelTab->nCol = 0;
1861 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001862 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00001863 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00001864 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001865 }else{
1866 pTable->nCol = 0;
1867 nErr++;
1868 }
drh633e6d52008-07-28 19:34:53 +00001869 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001870 } else {
drh417be792002-03-03 18:59:40 +00001871 nErr++;
1872 }
drhb7f91642004-10-31 02:22:47 +00001873#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001874 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001875}
1876#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001877
drhb7f91642004-10-31 02:22:47 +00001878#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001879/*
drh8bf8dc92003-05-17 17:35:10 +00001880** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001881*/
drh9bb575f2004-09-06 17:24:11 +00001882static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001883 HashElem *i;
drh21206082011-04-04 18:22:02 +00001884 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00001885 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001886 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001887 Table *pTab = sqliteHashData(i);
1888 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00001889 sqliteDeleteColumnNames(db, pTab);
1890 pTab->aCol = 0;
1891 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00001892 }
1893 }
drh8bf8dc92003-05-17 17:35:10 +00001894 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001895}
drhb7f91642004-10-31 02:22:47 +00001896#else
1897# define sqliteViewResetAll(A,B)
1898#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001899
drh75897232000-05-29 14:26:00 +00001900/*
danielk1977a0bf2652004-11-04 14:30:04 +00001901** This function is called by the VDBE to adjust the internal schema
1902** used by SQLite when the btree layer moves a table root page. The
1903** root-page of a table or index in database iDb has changed from iFrom
1904** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001905**
1906** Ticket #1728: The symbol table might still contain information
1907** on tables and/or indices that are the process of being deleted.
1908** If you are unlucky, one of those deleted indices or tables might
1909** have the same rootpage number as the real table or index that is
1910** being moved. So we cannot stop searching after the first match
1911** because the first match might be for one of the deleted indices
1912** or tables and not the table/index that is actually being moved.
1913** We must continue looping until all tables and indices with
1914** rootpage==iFrom have been converted to have a rootpage of iTo
1915** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001916*/
1917#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00001918void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00001919 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001920 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00001921 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00001922
drhcdf011d2011-04-04 21:25:28 +00001923 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1924 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00001925 pHash = &pDb->pSchema->tblHash;
1926 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001927 Table *pTab = sqliteHashData(pElem);
1928 if( pTab->tnum==iFrom ){
1929 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001930 }
1931 }
danielk1977da184232006-01-05 11:34:32 +00001932 pHash = &pDb->pSchema->idxHash;
1933 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001934 Index *pIdx = sqliteHashData(pElem);
1935 if( pIdx->tnum==iFrom ){
1936 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001937 }
1938 }
danielk1977a0bf2652004-11-04 14:30:04 +00001939}
1940#endif
1941
1942/*
1943** Write code to erase the table with root-page iTable from database iDb.
1944** Also write code to modify the sqlite_master table and internal schema
1945** if a root-page of another table is moved by the btree-layer whilst
1946** erasing iTable (this can happen with an auto-vacuum database).
1947*/
drh4e0cff62004-11-05 05:10:28 +00001948static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1949 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001950 int r1 = sqlite3GetTempReg(pParse);
1951 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001952 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001953#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001954 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001955 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001956 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001957 ** reflect this.
1958 **
drh0fa991b2009-03-21 16:19:26 +00001959 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001960 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1961 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001962 */
danielk197763e3e9f2004-11-05 09:19:27 +00001963 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001964 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1965 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001966#endif
drhb7654112008-01-12 12:48:07 +00001967 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001968}
1969
1970/*
1971** Write VDBE code to erase table pTab and all associated indices on disk.
1972** Code to update the sqlite_master tables and internal schema definitions
1973** in case a root-page belonging to another table is moved by the btree layer
1974** is also added (this can happen with an auto-vacuum database).
1975*/
drh4e0cff62004-11-05 05:10:28 +00001976static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001977#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001978 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001979 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1980 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001981 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001982 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001983 }
1984#else
1985 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1986 ** is not defined), then it is important to call OP_Destroy on the
1987 ** table and index root-pages in order, starting with the numerically
1988 ** largest root-page number. This guarantees that none of the root-pages
1989 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1990 ** following were coded:
1991 **
1992 ** OP_Destroy 4 0
1993 ** ...
1994 ** OP_Destroy 5 0
1995 **
1996 ** and root page 5 happened to be the largest root-page number in the
1997 ** database, then root page 5 would be moved to page 4 by the
1998 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1999 ** a free-list page.
2000 */
2001 int iTab = pTab->tnum;
2002 int iDestroyed = 0;
2003
2004 while( 1 ){
2005 Index *pIdx;
2006 int iLargest = 0;
2007
2008 if( iDestroyed==0 || iTab<iDestroyed ){
2009 iLargest = iTab;
2010 }
2011 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2012 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002013 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002014 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2015 iLargest = iIdx;
2016 }
2017 }
danielk1977da184232006-01-05 11:34:32 +00002018 if( iLargest==0 ){
2019 return;
2020 }else{
2021 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002022 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002023 destroyRootPage(pParse, iLargest, iDb);
2024 iDestroyed = iLargest;
2025 }
danielk1977a0bf2652004-11-04 14:30:04 +00002026 }
2027#endif
2028}
2029
2030/*
drh74e7c8f2011-10-21 19:06:32 +00002031** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002032** after a DROP INDEX or DROP TABLE command.
2033*/
2034static void sqlite3ClearStatTables(
2035 Parse *pParse, /* The parsing context */
2036 int iDb, /* The database number */
2037 const char *zType, /* "idx" or "tbl" */
2038 const char *zName /* Name of index or table */
2039){
drha5ae4c32011-08-07 01:31:52 +00002040 int i;
2041 const char *zDbName = pParse->db->aDb[iDb].zName;
drh74e7c8f2011-10-21 19:06:32 +00002042 for(i=1; i<=3; i++){
2043 char zTab[24];
2044 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2045 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002046 sqlite3NestedParse(pParse,
2047 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002048 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002049 );
2050 }
2051 }
2052}
2053
2054/*
drhfaacf172011-08-12 01:51:45 +00002055** Generate code to drop a table.
2056*/
2057void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2058 Vdbe *v;
2059 sqlite3 *db = pParse->db;
2060 Trigger *pTrigger;
2061 Db *pDb = &db->aDb[iDb];
2062
2063 v = sqlite3GetVdbe(pParse);
2064 assert( v!=0 );
2065 sqlite3BeginWriteOperation(pParse, 1, iDb);
2066
2067#ifndef SQLITE_OMIT_VIRTUALTABLE
2068 if( IsVirtual(pTab) ){
2069 sqlite3VdbeAddOp0(v, OP_VBegin);
2070 }
2071#endif
2072
2073 /* Drop all triggers associated with the table being dropped. Code
2074 ** is generated to remove entries from sqlite_master and/or
2075 ** sqlite_temp_master if required.
2076 */
2077 pTrigger = sqlite3TriggerList(pParse, pTab);
2078 while( pTrigger ){
2079 assert( pTrigger->pSchema==pTab->pSchema ||
2080 pTrigger->pSchema==db->aDb[1].pSchema );
2081 sqlite3DropTriggerPtr(pParse, pTrigger);
2082 pTrigger = pTrigger->pNext;
2083 }
2084
2085#ifndef SQLITE_OMIT_AUTOINCREMENT
2086 /* Remove any entries of the sqlite_sequence table associated with
2087 ** the table being dropped. This is done before the table is dropped
2088 ** at the btree level, in case the sqlite_sequence table needs to
2089 ** move as a result of the drop (can happen in auto-vacuum mode).
2090 */
2091 if( pTab->tabFlags & TF_Autoincrement ){
2092 sqlite3NestedParse(pParse,
2093 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2094 pDb->zName, pTab->zName
2095 );
2096 }
2097#endif
2098
2099 /* Drop all SQLITE_MASTER table and index entries that refer to the
2100 ** table. The program name loops through the master table and deletes
2101 ** every row that refers to a table of the same name as the one being
2102 ** dropped. Triggers are handled seperately because a trigger can be
2103 ** created in the temp database that refers to a table in another
2104 ** database.
2105 */
2106 sqlite3NestedParse(pParse,
2107 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2108 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002109 if( !isView && !IsVirtual(pTab) ){
2110 destroyTable(pParse, pTab);
2111 }
2112
2113 /* Remove the table entry from SQLite's internal schema and modify
2114 ** the schema cookie.
2115 */
2116 if( IsVirtual(pTab) ){
2117 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2118 }
2119 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2120 sqlite3ChangeCookie(pParse, iDb);
2121 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002122}
2123
2124/*
drh75897232000-05-29 14:26:00 +00002125** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002126** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002127*/
drha0733842005-12-29 01:11:36 +00002128void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002129 Table *pTab;
drh75897232000-05-29 14:26:00 +00002130 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002131 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002132 int iDb;
drh75897232000-05-29 14:26:00 +00002133
drh8af73d42009-05-13 22:58:28 +00002134 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002135 goto exit_drop_table;
2136 }
drh8af73d42009-05-13 22:58:28 +00002137 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002138 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002139 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002140 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002141 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002142
drha0733842005-12-29 01:11:36 +00002143 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002144 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002145 goto exit_drop_table;
2146 }
danielk1977da184232006-01-05 11:34:32 +00002147 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002148 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002149
2150 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2151 ** it is initialized.
2152 */
2153 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2154 goto exit_drop_table;
2155 }
drhe5f9c642003-01-13 23:27:31 +00002156#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002157 {
2158 int code;
danielk1977da184232006-01-05 11:34:32 +00002159 const char *zTab = SCHEMA_TABLE(iDb);
2160 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002161 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002162 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002163 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002164 }
drhe5f9c642003-01-13 23:27:31 +00002165 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002166 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002167 code = SQLITE_DROP_TEMP_VIEW;
2168 }else{
2169 code = SQLITE_DROP_VIEW;
2170 }
danielk19774b2688a2006-06-20 11:01:07 +00002171#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002172 }else if( IsVirtual(pTab) ){
2173 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002174 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002175#endif
drhe5f9c642003-01-13 23:27:31 +00002176 }else{
danielk197753c0f742005-03-29 03:10:59 +00002177 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002178 code = SQLITE_DROP_TEMP_TABLE;
2179 }else{
2180 code = SQLITE_DROP_TABLE;
2181 }
2182 }
danielk1977f1a381e2006-06-16 08:01:02 +00002183 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002184 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002185 }
danielk1977a8858102004-05-28 12:11:21 +00002186 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2187 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002188 }
drhe5f9c642003-01-13 23:27:31 +00002189 }
2190#endif
drh08ccfaa2011-10-07 23:52:25 +00002191 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2192 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002193 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002194 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002195 }
danielk1977576ec6b2005-01-21 11:55:25 +00002196
2197#ifndef SQLITE_OMIT_VIEW
2198 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2199 ** on a table.
2200 */
danielk1977a8858102004-05-28 12:11:21 +00002201 if( isView && pTab->pSelect==0 ){
2202 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2203 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002204 }
danielk1977a8858102004-05-28 12:11:21 +00002205 if( !isView && pTab->pSelect ){
2206 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2207 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002208 }
danielk1977576ec6b2005-01-21 11:55:25 +00002209#endif
drh75897232000-05-29 14:26:00 +00002210
drh1ccde152000-06-17 13:12:39 +00002211 /* Generate code to remove the table from the master table
2212 ** on disk.
2213 */
danielk19774adee202004-05-08 08:23:19 +00002214 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002215 if( v ){
drh77658e22007-12-04 16:54:52 +00002216 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002217 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002218 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002219 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002220 }
danielk1977a8858102004-05-28 12:11:21 +00002221
2222exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002223 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002224}
2225
2226/*
drhc2eef3b2002-08-31 18:53:06 +00002227** This routine is called to create a new foreign key on the table
2228** currently under construction. pFromCol determines which columns
2229** in the current table point to the foreign key. If pFromCol==0 then
2230** connect the key to the last column inserted. pTo is the name of
2231** the table referred to. pToCol is a list of tables in the other
2232** pTo table that the foreign key points to. flags contains all
2233** information about the conflict resolution algorithms specified
2234** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2235**
2236** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002237** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002238**
2239** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002240** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002241*/
danielk19774adee202004-05-08 08:23:19 +00002242void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002243 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002244 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002245 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002246 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002247 int flags /* Conflict resolution algorithms. */
2248){
danielk197718576932008-08-06 13:47:40 +00002249 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002250#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002251 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002252 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002253 Table *p = pParse->pNewTable;
2254 int nByte;
2255 int i;
2256 int nCol;
2257 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002258
2259 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002260 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002261 if( pFromCol==0 ){
2262 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002263 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002264 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002265 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002266 " should reference only one column of table %T",
2267 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002268 goto fk_end;
2269 }
2270 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002271 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002272 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002273 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002274 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002275 goto fk_end;
2276 }else{
danielk19770202b292004-06-09 09:55:16 +00002277 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002278 }
drhe61922a2009-05-02 13:29:37 +00002279 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002280 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002281 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002282 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002283 }
2284 }
drh633e6d52008-07-28 19:34:53 +00002285 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002286 if( pFKey==0 ){
2287 goto fk_end;
2288 }
drhc2eef3b2002-08-31 18:53:06 +00002289 pFKey->pFrom = p;
2290 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002291 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002292 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002293 memcpy(z, pTo->z, pTo->n);
2294 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002295 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002296 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002297 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002298 if( pFromCol==0 ){
2299 pFKey->aCol[0].iFrom = p->nCol-1;
2300 }else{
2301 for(i=0; i<nCol; i++){
2302 int j;
2303 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002304 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002305 pFKey->aCol[i].iFrom = j;
2306 break;
2307 }
2308 }
2309 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002310 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002311 "unknown column \"%s\" in foreign key definition",
2312 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002313 goto fk_end;
2314 }
2315 }
2316 }
2317 if( pToCol ){
2318 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002319 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002320 pFKey->aCol[i].zCol = z;
2321 memcpy(z, pToCol->a[i].zName, n);
2322 z[n] = 0;
2323 z += n+1;
2324 }
2325 }
2326 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002327 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2328 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002329
drh21206082011-04-04 18:22:02 +00002330 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002331 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2332 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2333 );
danf59c5ca2009-09-22 16:55:38 +00002334 if( pNextTo==pFKey ){
2335 db->mallocFailed = 1;
2336 goto fk_end;
2337 }
dan1da40a32009-09-19 17:00:31 +00002338 if( pNextTo ){
2339 assert( pNextTo->pPrevTo==0 );
2340 pFKey->pNextTo = pNextTo;
2341 pNextTo->pPrevTo = pFKey;
2342 }
2343
drhc2eef3b2002-08-31 18:53:06 +00002344 /* Link the foreign key to the table as the last step.
2345 */
2346 p->pFKey = pFKey;
2347 pFKey = 0;
2348
2349fk_end:
drh633e6d52008-07-28 19:34:53 +00002350 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002351#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002352 sqlite3ExprListDelete(db, pFromCol);
2353 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002354}
2355
2356/*
2357** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2358** clause is seen as part of a foreign key definition. The isDeferred
2359** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2360** The behavior of the most recently created foreign key is adjusted
2361** accordingly.
2362*/
danielk19774adee202004-05-08 08:23:19 +00002363void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002364#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002365 Table *pTab;
2366 FKey *pFKey;
2367 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002368 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002369 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002370#endif
drhc2eef3b2002-08-31 18:53:06 +00002371}
2372
2373/*
drh063336a2004-11-05 20:58:39 +00002374** Generate code that will erase and refill index *pIdx. This is
2375** used to initialize a newly created index or to recompute the
2376** content of an index in response to a REINDEX command.
2377**
2378** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002379** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002380** root page number of the index. If memRootPage is negative, then
2381** the index already exists and must be cleared before being refilled and
2382** the root page number of the index is taken from pIndex->tnum.
2383*/
2384static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2385 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002386 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2387 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002388 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002389 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002390 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002391 int tnum; /* Root page of index */
2392 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002393 KeyInfo *pKey; /* KeyInfo for index */
drhb07028f2011-10-14 21:49:18 +00002394#ifdef SQLITE_OMIT_MERGE_SORT
drh2d401ab2008-01-10 23:50:11 +00002395 int regIdxKey; /* Registers containing the index key */
drhb07028f2011-10-14 21:49:18 +00002396#endif
drh2d401ab2008-01-10 23:50:11 +00002397 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002398 sqlite3 *db = pParse->db; /* The database connection */
2399 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002400
danielk19771d54df82004-11-23 15:41:16 +00002401#ifndef SQLITE_OMIT_AUTHORIZATION
2402 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002403 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002404 return;
2405 }
2406#endif
2407
danielk1977c00da102006-01-07 13:21:04 +00002408 /* Require a write-lock on the table to perform this operation */
2409 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2410
drh063336a2004-11-05 20:58:39 +00002411 v = sqlite3GetVdbe(pParse);
2412 if( v==0 ) return;
2413 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002414 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002415 }else{
2416 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002417 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002418 }
danielk1977b3bf5562006-01-10 17:58:23 +00002419 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002420 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002421 (char *)pKey, P4_KEYINFO_HANDOFF);
dan428c2182012-08-06 18:50:11 +00002422 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
dana20fde62011-07-12 14:28:05 +00002423
drhca892a72011-09-03 00:17:51 +00002424#ifndef SQLITE_OMIT_MERGE_SORT
dan689ab892011-08-12 15:02:00 +00002425 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002426 iSorter = pParse->nTab++;
2427 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
drhb07028f2011-10-14 21:49:18 +00002428#else
2429 iSorter = iTab;
drhca892a72011-09-03 00:17:51 +00002430#endif
dana20fde62011-07-12 14:28:05 +00002431
2432 /* Open the table. Loop through all rows of the table, inserting index
2433 ** records into the sorter. */
danielk1977c00da102006-01-07 13:21:04 +00002434 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002435 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002436 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002437
drhca892a72011-09-03 00:17:51 +00002438#ifndef SQLITE_OMIT_MERGE_SORT
drhb07028f2011-10-14 21:49:18 +00002439 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drhca892a72011-09-03 00:17:51 +00002440 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
2441 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2442 sqlite3VdbeJumpHere(v, addr1);
2443 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
2444 if( pIndex->onError!=OE_None ){
2445 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2446 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2447 addr2 = sqlite3VdbeCurrentAddr(v);
2448 sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
2449 sqlite3HaltConstraint(
2450 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
2451 );
2452 }else{
2453 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002454 }
drhca892a72011-09-03 00:17:51 +00002455 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2456 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2457 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2458#else
drhb07028f2011-10-14 21:49:18 +00002459 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2460 addr2 = addr1 + 1;
drh7f057c92005-06-24 03:53:06 +00002461 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002462 const int regRowid = regIdxKey + pIndex->nColumn;
2463 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2464 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002465
danielk1977de630352009-05-04 11:42:29 +00002466 /* The registers accessed by the OP_IsUnique opcode were allocated
2467 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2468 ** call above. Just before that function was freed they were released
2469 ** (made available to the compiler for reuse) using
2470 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2471 ** opcode use the values stored within seems dangerous. However, since
2472 ** we can be sure that no other temp registers have been allocated
2473 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2474 */
2475 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
dane0af83a2009-09-08 19:15:01 +00002476 sqlite3HaltConstraint(
2477 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002478 }
drhca892a72011-09-03 00:17:51 +00002479 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
danielk1977de630352009-05-04 11:42:29 +00002480 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drhca892a72011-09-03 00:17:51 +00002481#endif
drh2d401ab2008-01-10 23:50:11 +00002482 sqlite3ReleaseTempReg(pParse, regRecord);
drhca892a72011-09-03 00:17:51 +00002483 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
drhd654be82005-09-20 17:42:23 +00002484 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002485
drh66a51672008-01-03 00:01:23 +00002486 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2487 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002488 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002489}
2490
2491/*
drh23bf66d2004-12-14 03:34:34 +00002492** Create a new index for an SQL table. pName1.pName2 is the name of the index
2493** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002494** be NULL for a primary key or an index that is created to satisfy a
2495** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002496** as the table to be indexed. pParse->pNewTable is a table that is
2497** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002498**
drh382c0242001-10-06 16:33:02 +00002499** pList is a list of columns to be indexed. pList will be NULL if this
2500** is a primary key or unique-constraint on the most recent column added
2501** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002502**
2503** If the index is created successfully, return a pointer to the new Index
2504** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2505** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002506*/
dan1da40a32009-09-19 17:00:31 +00002507Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002508 Parse *pParse, /* All information about this parse */
2509 Token *pName1, /* First part of index name. May be NULL */
2510 Token *pName2, /* Second part of index name. May be NULL */
2511 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002512 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002513 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002514 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002515 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002516 int sortOrder, /* Sort order of primary key when pList==NULL */
2517 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002518){
dan1da40a32009-09-19 17:00:31 +00002519 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002520 Table *pTab = 0; /* Table to be indexed */
2521 Index *pIndex = 0; /* The index to be created */
2522 char *zName = 0; /* Name of the index */
2523 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002524 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002525 Token nullId; /* Fake token for an empty ID list */
2526 DbFixer sFix; /* For assigning database names to pTable */
2527 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002528 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002529 Db *pDb; /* The specific table containing the indexed database */
2530 int iDb; /* Index of the database that is being written */
2531 Token *pName = 0; /* Unqualified name of the index to create */
2532 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002533 int nCol;
2534 int nExtra = 0;
2535 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002536
drhd3001712009-05-12 17:46:53 +00002537 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
drh8af73d42009-05-13 22:58:28 +00002538 assert( pParse->nErr==0 ); /* Never called with prior errors */
2539 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002540 goto exit_create_index;
2541 }
2542 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002543 goto exit_create_index;
2544 }
drhdaffd0e2001-04-11 14:28:42 +00002545
drh75897232000-05-29 14:26:00 +00002546 /*
2547 ** Find the table that is to be indexed. Return early if not found.
2548 */
danielk1977cbb18d22004-05-28 11:37:27 +00002549 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002550
2551 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002552 ** to search for the table. 'Fix' the table name to this db
2553 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002554 */
2555 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002556 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002557 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002558 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002559
danielk197753c0f742005-03-29 03:10:59 +00002560#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002561 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002562 ** is a temp table. If so, set the database to 1. Do not do this
2563 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002564 */
danielk1977fe910332007-12-02 11:46:34 +00002565 if( !db->init.busy ){
2566 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002567 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002568 iDb = 1;
2569 }
danielk1977ef2cb632004-05-29 02:37:19 +00002570 }
danielk197753c0f742005-03-29 03:10:59 +00002571#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002572
2573 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2574 sqlite3FixSrcList(&sFix, pTblName)
2575 ){
drh85c23c62005-08-20 03:03:04 +00002576 /* Because the parser constructs pTblName from a single identifier,
2577 ** sqlite3FixSrcList can never fail. */
2578 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002579 }
dan41fb5cd2012-10-04 19:33:00 +00002580 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002581 assert( db->mallocFailed==0 || pTab==0 );
2582 if( pTab==0 ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002583 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002584 }else{
drhe3c41372001-09-17 20:25:58 +00002585 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002586 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002587 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002588 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002589 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002590 }
drhfdd6e852005-12-16 01:06:16 +00002591 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002592
drhd3001712009-05-12 17:46:53 +00002593 assert( pTab!=0 );
2594 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002595 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2596 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002597 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002598 goto exit_create_index;
2599 }
danielk1977576ec6b2005-01-21 11:55:25 +00002600#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002601 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002602 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002603 goto exit_create_index;
2604 }
danielk1977576ec6b2005-01-21 11:55:25 +00002605#endif
danielk19775ee9d692006-06-21 12:36:25 +00002606#ifndef SQLITE_OMIT_VIRTUALTABLE
2607 if( IsVirtual(pTab) ){
2608 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2609 goto exit_create_index;
2610 }
2611#endif
drh75897232000-05-29 14:26:00 +00002612
2613 /*
2614 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002615 ** index or table with the same name.
2616 **
2617 ** Exception: If we are reading the names of permanent indices from the
2618 ** sqlite_master table (because some other process changed the schema) and
2619 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002620 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002621 **
2622 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002623 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2624 ** own name.
drh75897232000-05-29 14:26:00 +00002625 */
danielk1977d8123362004-06-12 09:25:12 +00002626 if( pName ){
drh17435752007-08-16 04:30:38 +00002627 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002628 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002629 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002630 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002631 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002632 }
danielk1977d8123362004-06-12 09:25:12 +00002633 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002634 if( sqlite3FindTable(db, zName, 0)!=0 ){
2635 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2636 goto exit_create_index;
2637 }
2638 }
danielk197759a33f92007-03-17 10:26:59 +00002639 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2640 if( !ifNotExist ){
2641 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002642 }else{
2643 assert( !db->init.busy );
2644 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002645 }
danielk197759a33f92007-03-17 10:26:59 +00002646 goto exit_create_index;
2647 }
danielk1977a21c6b62005-01-24 10:25:59 +00002648 }else{
drhadbca9c2001-09-27 15:11:53 +00002649 int n;
2650 Index *pLoop;
2651 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002652 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002653 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002654 goto exit_create_index;
2655 }
drh75897232000-05-29 14:26:00 +00002656 }
2657
drhe5f9c642003-01-13 23:27:31 +00002658 /* Check for authorization to create an index.
2659 */
2660#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002661 {
drhfdd6e852005-12-16 01:06:16 +00002662 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002663 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002664 goto exit_create_index;
2665 }
2666 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002667 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002668 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002669 goto exit_create_index;
2670 }
drhe5f9c642003-01-13 23:27:31 +00002671 }
2672#endif
2673
drh75897232000-05-29 14:26:00 +00002674 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002675 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002676 ** So create a fake list to simulate this.
2677 */
2678 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002679 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002680 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002681 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002682 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002683 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002684 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002685 }
2686
danielk1977b3bf5562006-01-10 17:58:23 +00002687 /* Figure out how many bytes of space are required to store explicitly
2688 ** specified collation sequence names.
2689 */
2690 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002691 Expr *pExpr = pList->a[i].pExpr;
2692 if( pExpr ){
2693 CollSeq *pColl = pExpr->pColl;
2694 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2695 ** failure we have quit before reaching this point. */
2696 if( ALWAYS(pColl) ){
2697 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2698 }
danielk1977b3bf5562006-01-10 17:58:23 +00002699 }
2700 }
2701
drh75897232000-05-29 14:26:00 +00002702 /*
2703 ** Allocate the index structure.
2704 */
drhea678832008-12-10 19:26:22 +00002705 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002706 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002707 pIndex = sqlite3DbMallocZero(db,
drhe0711b42012-01-05 12:38:02 +00002708 ROUND8(sizeof(Index)) + /* Index structure */
drhe09b84c2011-11-14 02:53:54 +00002709 ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
2710 sizeof(char *)*nCol + /* Index.azColl */
2711 sizeof(int)*nCol + /* Index.aiColumn */
2712 sizeof(u8)*nCol + /* Index.aSortOrder */
2713 nName + 1 + /* Index.zName */
2714 nExtra /* Collation sequence names */
danielk1977b3bf5562006-01-10 17:58:23 +00002715 );
drh17435752007-08-16 04:30:38 +00002716 if( db->mallocFailed ){
2717 goto exit_create_index;
2718 }
drhe0711b42012-01-05 12:38:02 +00002719 zExtra = (char*)pIndex;
2720 pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
drhe09b84c2011-11-14 02:53:54 +00002721 pIndex->azColl = (char**)
2722 ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
2723 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
2724 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh78aecb72006-02-10 18:08:09 +00002725 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
drhfaacf172011-08-12 01:51:45 +00002726 pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
danielk1977b3bf5562006-01-10 17:58:23 +00002727 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2728 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002729 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002730 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002731 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002732 pIndex->onError = (u8)onError;
2733 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002734 pIndex->pSchema = db->aDb[iDb].pSchema;
drh21206082011-04-04 18:22:02 +00002735 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002736
drhfdd6e852005-12-16 01:06:16 +00002737 /* Check to see if we should honor DESC requests on index columns
2738 */
danielk1977da184232006-01-05 11:34:32 +00002739 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002740 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002741 }else{
2742 sortOrderMask = 0; /* Ignore DESC */
2743 }
2744
drh1ccde152000-06-17 13:12:39 +00002745 /* Scan the names of the columns of the table to be indexed and
2746 ** load the column indices into the Index structure. Report an error
2747 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002748 **
2749 ** TODO: Add a test to make sure that the same column is not named
2750 ** more than once within the same index. Only the first instance of
2751 ** the column will ever be used by the optimizer. Note that using the
2752 ** same column more than once cannot be an error because that would
2753 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002754 */
drhfdd6e852005-12-16 01:06:16 +00002755 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2756 const char *zColName = pListItem->zName;
2757 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002758 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002759 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002760
drhfdd6e852005-12-16 01:06:16 +00002761 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2762 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002763 }
2764 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002765 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002766 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00002767 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00002768 goto exit_create_index;
2769 }
drh967e8b72000-06-21 13:59:10 +00002770 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002771 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2772 ** the way the "idxlist" non-terminal is constructed by the parser,
2773 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2774 ** must exist or else there must have been an OOM error. But if there
2775 ** was an OOM error, we would never reach this point. */
2776 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2777 int nColl;
2778 zColl = pListItem->pExpr->pColl->zName;
2779 nColl = sqlite3Strlen30(zColl) + 1;
2780 assert( nExtra>=nColl );
2781 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002782 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002783 zExtra += nColl;
2784 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002785 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002786 zColl = pTab->aCol[j].zColl;
2787 if( !zColl ){
drha19b8962012-06-06 10:56:22 +00002788 zColl = "BINARY";
danielk1977b3bf5562006-01-10 17:58:23 +00002789 }
danielk19770202b292004-06-09 09:55:16 +00002790 }
drhb7f24de2009-05-13 17:35:23 +00002791 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002792 goto exit_create_index;
2793 }
danielk1977b3bf5562006-01-10 17:58:23 +00002794 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002795 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002796 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002797 }
drh51147ba2005-07-23 22:59:55 +00002798 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002799
danielk1977d8123362004-06-12 09:25:12 +00002800 if( pTab==pParse->pNewTable ){
2801 /* This routine has been called to create an automatic index as a
2802 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2803 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2804 ** i.e. one of:
2805 **
2806 ** CREATE TABLE t(x PRIMARY KEY, y);
2807 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2808 **
2809 ** Either way, check to see if the table already has such an index. If
2810 ** so, don't bother creating this one. This only applies to
2811 ** automatically created indices. Users can do as they wish with
2812 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002813 **
2814 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2815 ** (and thus suppressing the second one) even if they have different
2816 ** sort orders.
2817 **
2818 ** If there are different collating sequences or if the columns of
2819 ** the constraint occur in different orders, then the constraints are
2820 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002821 */
2822 Index *pIdx;
2823 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2824 int k;
2825 assert( pIdx->onError!=OE_None );
2826 assert( pIdx->autoIndex );
2827 assert( pIndex->onError!=OE_None );
2828
2829 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2830 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002831 const char *z1;
2832 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002833 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002834 z1 = pIdx->azColl[k];
2835 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002836 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002837 }
2838 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002839 if( pIdx->onError!=pIndex->onError ){
2840 /* This constraint creates the same index as a previous
2841 ** constraint specified somewhere in the CREATE TABLE statement.
2842 ** However the ON CONFLICT clauses are different. If both this
2843 ** constraint and the previous equivalent constraint have explicit
2844 ** ON CONFLICT clauses this is an error. Otherwise, use the
2845 ** explicitly specified behaviour for the index.
2846 */
2847 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2848 sqlite3ErrorMsg(pParse,
2849 "conflicting ON CONFLICT clauses specified", 0);
2850 }
2851 if( pIdx->onError==OE_Default ){
2852 pIdx->onError = pIndex->onError;
2853 }
2854 }
danielk1977d8123362004-06-12 09:25:12 +00002855 goto exit_create_index;
2856 }
2857 }
2858 }
2859
drh75897232000-05-29 14:26:00 +00002860 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002861 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002862 */
drh234c39d2004-07-24 03:30:47 +00002863 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002864 Index *p;
drh21206082011-04-04 18:22:02 +00002865 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002866 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002867 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002868 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002869 if( p ){
2870 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002871 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002872 goto exit_create_index;
2873 }
drh5e00f6c2001-09-13 13:46:56 +00002874 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002875 if( pTblName!=0 ){
2876 pIndex->tnum = db->init.newTnum;
2877 }
drhd78eeee2001-09-13 16:18:53 +00002878 }
2879
drh1d85d932004-02-14 23:05:52 +00002880 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002881 ** involves writing the index into the master table and filling in the
2882 ** index with the current table contents.
2883 **
drh1d85d932004-02-14 23:05:52 +00002884 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2885 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002886 ** CREATE INDEX statements are read out of the master table. In
2887 ** the latter case the index already exists on disk, which is why
2888 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002889 **
danielk1977cbb18d22004-05-28 11:37:27 +00002890 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002891 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2892 ** has just been created, it contains no data and the index initialization
2893 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002894 */
drhd3001712009-05-12 17:46:53 +00002895 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002896 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002897 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002898 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002899
danielk19774adee202004-05-08 08:23:19 +00002900 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002901 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002902
drhfdd6e852005-12-16 01:06:16 +00002903
drh063336a2004-11-05 20:58:39 +00002904 /* Create the rootpage for the index
2905 */
drhaee128d2005-02-14 20:48:18 +00002906 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002907 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002908
2909 /* Gather the complete text of the CREATE INDEX statement into
2910 ** the zStmt variable
2911 */
drhd3001712009-05-12 17:46:53 +00002912 if( pStart ){
2913 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002914 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002915 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002916 onError==OE_None ? "" : " UNIQUE",
dan28e4e352011-06-24 18:43:23 +00002917 (int)(pEnd->z - pName->z) + 1,
drh063336a2004-11-05 20:58:39 +00002918 pName->z);
2919 }else{
2920 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002921 /* zStmt = sqlite3MPrintf(""); */
2922 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002923 }
drh063336a2004-11-05 20:58:39 +00002924
2925 /* Add an entry in sqlite_master for this index
2926 */
2927 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002928 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002929 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2930 pIndex->zName,
2931 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002932 iMem,
drh063336a2004-11-05 20:58:39 +00002933 zStmt
2934 );
drh633e6d52008-07-28 19:34:53 +00002935 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002936
danielk1977a21c6b62005-01-24 10:25:59 +00002937 /* Fill the index with data and reparse the schema. Code an OP_Expire
2938 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002939 */
danielk1977cbb18d22004-05-28 11:37:27 +00002940 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002941 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002942 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00002943 sqlite3VdbeAddParseSchemaOp(v, iDb,
2944 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00002945 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002946 }
drh75897232000-05-29 14:26:00 +00002947 }
2948
danielk1977d8123362004-06-12 09:25:12 +00002949 /* When adding an index to the list of indices for a table, make
2950 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002951 ** OE_Ignore. This is necessary for the correct constraint check
2952 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2953 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002954 */
drh234c39d2004-07-24 03:30:47 +00002955 if( db->init.busy || pTblName==0 ){
2956 if( onError!=OE_Replace || pTab->pIndex==0
2957 || pTab->pIndex->onError==OE_Replace){
2958 pIndex->pNext = pTab->pIndex;
2959 pTab->pIndex = pIndex;
2960 }else{
2961 Index *pOther = pTab->pIndex;
2962 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2963 pOther = pOther->pNext;
2964 }
2965 pIndex->pNext = pOther->pNext;
2966 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002967 }
dan1da40a32009-09-19 17:00:31 +00002968 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00002969 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002970 }
danielk1977d8123362004-06-12 09:25:12 +00002971
drh75897232000-05-29 14:26:00 +00002972 /* Clean up before exiting */
2973exit_create_index:
drh956bc922004-07-24 17:38:29 +00002974 if( pIndex ){
drhb9755982010-07-24 16:34:37 +00002975 sqlite3DbFree(db, pIndex->zColAff);
danielk1977cb9d8d82009-03-18 18:43:36 +00002976 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002977 }
drh633e6d52008-07-28 19:34:53 +00002978 sqlite3ExprListDelete(db, pList);
2979 sqlite3SrcListDelete(db, pTblName);
2980 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00002981 return pRet;
drh75897232000-05-29 14:26:00 +00002982}
2983
2984/*
drh51147ba2005-07-23 22:59:55 +00002985** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002986** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002987**
2988** aiRowEst[0] is suppose to contain the number of elements in the index.
2989** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2990** number of rows in the table that match any particular value of the
2991** first column of the index. aiRowEst[2] is an estimate of the number
2992** of rows that match any particular combiniation of the first 2 columns
2993** of the index. And so forth. It must always be the case that
2994*
2995** aiRowEst[N]<=aiRowEst[N-1]
2996** aiRowEst[N]>=1
2997**
2998** Apart from that, we have little to go on besides intuition as to
2999** how aiRowEst[] should be initialized. The numbers generated here
3000** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003001*/
3002void sqlite3DefaultRowEst(Index *pIdx){
drhfaacf172011-08-12 01:51:45 +00003003 tRowcnt *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00003004 int i;
drhfaacf172011-08-12 01:51:45 +00003005 tRowcnt n;
drh28c4cf42005-07-27 20:41:43 +00003006 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00003007 a[0] = pIdx->pTable->nRowEst;
3008 if( a[0]<10 ) a[0] = 10;
3009 n = 10;
3010 for(i=1; i<=pIdx->nColumn; i++){
3011 a[i] = n;
3012 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00003013 }
3014 if( pIdx->onError!=OE_None ){
3015 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00003016 }
3017}
3018
3019/*
drh74e24cd2002-01-09 03:19:59 +00003020** This routine will drop an existing named index. This routine
3021** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003022*/
drh4d91a702006-01-04 15:54:36 +00003023void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003024 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003025 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003026 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003027 int iDb;
drh75897232000-05-29 14:26:00 +00003028
drh8af73d42009-05-13 22:58:28 +00003029 assert( pParse->nErr==0 ); /* Never called with prior errors */
3030 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003031 goto exit_drop_index;
3032 }
drhd24cc422003-03-27 12:51:24 +00003033 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003034 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3035 goto exit_drop_index;
3036 }
danielk19774adee202004-05-08 08:23:19 +00003037 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003038 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003039 if( !ifExists ){
3040 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003041 }else{
3042 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003043 }
drha6ecd332004-06-10 00:29:09 +00003044 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003045 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003046 }
drh485b39b2002-07-13 03:11:52 +00003047 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00003048 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003049 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003050 goto exit_drop_index;
3051 }
danielk1977da184232006-01-05 11:34:32 +00003052 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003053#ifndef SQLITE_OMIT_AUTHORIZATION
3054 {
3055 int code = SQLITE_DROP_INDEX;
3056 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003057 const char *zDb = db->aDb[iDb].zName;
3058 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003059 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003060 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003061 }
danielk1977da184232006-01-05 11:34:32 +00003062 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003063 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003064 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003065 }
drhed6c8672003-01-12 18:02:16 +00003066 }
drhe5f9c642003-01-13 23:27:31 +00003067#endif
drh75897232000-05-29 14:26:00 +00003068
3069 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003070 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003071 if( v ){
drh77658e22007-12-04 16:54:52 +00003072 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003073 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003074 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003075 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003076 );
drha5ae4c32011-08-07 01:31:52 +00003077 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003078 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003079 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003080 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003081 }
3082
drhd24cc422003-03-27 12:51:24 +00003083exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003084 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003085}
3086
3087/*
dan9ace1122012-03-29 07:51:45 +00003088** pArray is a pointer to an array of objects. Each object in the
3089** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3090** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003091**
dan9ace1122012-03-29 07:51:45 +00003092** When this function is called, *pnEntry contains the current size of
3093** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3094** in total).
drh13449892005-09-07 21:22:45 +00003095**
dan9ace1122012-03-29 07:51:45 +00003096** If the realloc() is successful (i.e. if no OOM condition occurs), the
3097** space allocated for the new object is zeroed, *pnEntry updated to
3098** reflect the new size of the array and a pointer to the new allocation
3099** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003100**
dan9ace1122012-03-29 07:51:45 +00003101** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3102** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003103*/
drhcf643722007-03-27 13:36:37 +00003104void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003105 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003106 void *pArray, /* Array of objects. Might be reallocated */
3107 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003108 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003109 int *pIdx /* Write the index of a new slot here */
3110){
3111 char *z;
drh6c535152012-02-02 03:38:30 +00003112 int n = *pnEntry;
3113 if( (n & (n-1))==0 ){
3114 int sz = (n==0) ? 1 : 2*n;
3115 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003116 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003117 *pIdx = -1;
3118 return pArray;
drh13449892005-09-07 21:22:45 +00003119 }
drhcf643722007-03-27 13:36:37 +00003120 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003121 }
drhcf643722007-03-27 13:36:37 +00003122 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003123 memset(&z[n * szEntry], 0, szEntry);
3124 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003125 ++*pnEntry;
3126 return pArray;
drh13449892005-09-07 21:22:45 +00003127}
3128
3129/*
drh75897232000-05-29 14:26:00 +00003130** Append a new element to the given IdList. Create a new IdList if
3131** need be.
drhdaffd0e2001-04-11 14:28:42 +00003132**
3133** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003134*/
drh17435752007-08-16 04:30:38 +00003135IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003136 int i;
drh75897232000-05-29 14:26:00 +00003137 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003138 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003139 if( pList==0 ) return 0;
3140 }
drhcf643722007-03-27 13:36:37 +00003141 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003142 db,
drhcf643722007-03-27 13:36:37 +00003143 pList->a,
3144 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003145 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003146 &i
3147 );
drh13449892005-09-07 21:22:45 +00003148 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003149 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003150 return 0;
drh75897232000-05-29 14:26:00 +00003151 }
drh17435752007-08-16 04:30:38 +00003152 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003153 return pList;
3154}
3155
3156/*
drhfe05af82005-07-21 03:14:59 +00003157** Delete an IdList.
3158*/
drh633e6d52008-07-28 19:34:53 +00003159void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003160 int i;
3161 if( pList==0 ) return;
3162 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003163 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003164 }
drh633e6d52008-07-28 19:34:53 +00003165 sqlite3DbFree(db, pList->a);
3166 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003167}
3168
3169/*
3170** Return the index in pList of the identifier named zId. Return -1
3171** if not found.
3172*/
3173int sqlite3IdListIndex(IdList *pList, const char *zName){
3174 int i;
3175 if( pList==0 ) return -1;
3176 for(i=0; i<pList->nId; i++){
3177 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3178 }
3179 return -1;
3180}
3181
3182/*
drha78c22c2008-11-11 18:28:58 +00003183** Expand the space allocated for the given SrcList object by
3184** creating nExtra new slots beginning at iStart. iStart is zero based.
3185** New slots are zeroed.
3186**
3187** For example, suppose a SrcList initially contains two entries: A,B.
3188** To append 3 new entries onto the end, do this:
3189**
3190** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3191**
3192** After the call above it would contain: A, B, nil, nil, nil.
3193** If the iStart argument had been 1 instead of 2, then the result
3194** would have been: A, nil, nil, nil, B. To prepend the new slots,
3195** the iStart value would be 0. The result then would
3196** be: nil, nil, nil, A, B.
3197**
3198** If a memory allocation fails the SrcList is unchanged. The
3199** db->mallocFailed flag will be set to true.
3200*/
3201SrcList *sqlite3SrcListEnlarge(
3202 sqlite3 *db, /* Database connection to notify of OOM errors */
3203 SrcList *pSrc, /* The SrcList to be enlarged */
3204 int nExtra, /* Number of new slots to add to pSrc->a[] */
3205 int iStart /* Index in pSrc->a[] of first new slot */
3206){
3207 int i;
3208
3209 /* Sanity checking on calling parameters */
3210 assert( iStart>=0 );
3211 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003212 assert( pSrc!=0 );
3213 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003214
3215 /* Allocate additional space if needed */
3216 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3217 SrcList *pNew;
3218 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003219 int nGot;
drha78c22c2008-11-11 18:28:58 +00003220 pNew = sqlite3DbRealloc(db, pSrc,
3221 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3222 if( pNew==0 ){
3223 assert( db->mallocFailed );
3224 return pSrc;
3225 }
3226 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003227 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003228 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003229 }
3230
3231 /* Move existing slots that come after the newly inserted slots
3232 ** out of the way */
3233 for(i=pSrc->nSrc-1; i>=iStart; i--){
3234 pSrc->a[i+nExtra] = pSrc->a[i];
3235 }
shane18e526c2008-12-10 22:30:24 +00003236 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003237
3238 /* Zero the newly allocated slots */
3239 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3240 for(i=iStart; i<iStart+nExtra; i++){
3241 pSrc->a[i].iCursor = -1;
3242 }
3243
3244 /* Return a pointer to the enlarged SrcList */
3245 return pSrc;
3246}
3247
3248
3249/*
drhad3cab52002-05-24 02:04:32 +00003250** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003251** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003252**
drha78c22c2008-11-11 18:28:58 +00003253** A SrcList is returned, or NULL if there is an OOM error. The returned
3254** SrcList might be the same as the SrcList that was input or it might be
3255** a new one. If an OOM error does occurs, then the prior value of pList
3256** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003257**
3258** If pDatabase is not null, it means that the table has an optional
3259** database name prefix. Like this: "database.table". The pDatabase
3260** points to the table name and the pTable points to the database name.
3261** The SrcList.a[].zName field is filled with the table name which might
3262** come from pTable (if pDatabase is NULL) or from pDatabase.
3263** SrcList.a[].zDatabase is filled with the database name from pTable,
3264** or with NULL if no database is specified.
3265**
3266** In other words, if call like this:
3267**
drh17435752007-08-16 04:30:38 +00003268** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003269**
3270** Then B is a table name and the database name is unspecified. If called
3271** like this:
3272**
drh17435752007-08-16 04:30:38 +00003273** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003274**
drhd3001712009-05-12 17:46:53 +00003275** Then C is the table name and B is the database name. If C is defined
3276** then so is B. In other words, we never have a case where:
3277**
3278** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003279**
3280** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3281** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003282*/
drh17435752007-08-16 04:30:38 +00003283SrcList *sqlite3SrcListAppend(
3284 sqlite3 *db, /* Connection to notify of malloc failures */
3285 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3286 Token *pTable, /* Table to append */
3287 Token *pDatabase /* Database of the table */
3288){
drha99db3b2004-06-19 14:49:12 +00003289 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003290 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003291 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003292 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003293 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003294 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003295 }
drha78c22c2008-11-11 18:28:58 +00003296 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3297 if( db->mallocFailed ){
3298 sqlite3SrcListDelete(db, pList);
3299 return 0;
drhad3cab52002-05-24 02:04:32 +00003300 }
drha78c22c2008-11-11 18:28:58 +00003301 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003302 if( pDatabase && pDatabase->z==0 ){
3303 pDatabase = 0;
3304 }
drhd3001712009-05-12 17:46:53 +00003305 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003306 Token *pTemp = pDatabase;
3307 pDatabase = pTable;
3308 pTable = pTemp;
3309 }
drh17435752007-08-16 04:30:38 +00003310 pItem->zName = sqlite3NameFromToken(db, pTable);
3311 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003312 return pList;
3313}
3314
3315/*
drhdfe88ec2008-11-03 20:55:06 +00003316** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003317*/
danielk19774adee202004-05-08 08:23:19 +00003318void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003319 int i;
drh9b3187e2005-01-18 14:45:47 +00003320 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003321 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003322 if( pList ){
3323 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3324 if( pItem->iCursor>=0 ) break;
3325 pItem->iCursor = pParse->nTab++;
3326 if( pItem->pSelect ){
3327 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3328 }
drh63eb5f22003-04-29 16:20:44 +00003329 }
3330 }
3331}
3332
3333/*
drhad3cab52002-05-24 02:04:32 +00003334** Delete an entire SrcList including all its substructure.
3335*/
drh633e6d52008-07-28 19:34:53 +00003336void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003337 int i;
drhbe5c89a2004-07-26 00:31:09 +00003338 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003339 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003340 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003341 sqlite3DbFree(db, pItem->zDatabase);
3342 sqlite3DbFree(db, pItem->zName);
3343 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003344 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003345 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003346 sqlite3SelectDelete(db, pItem->pSelect);
3347 sqlite3ExprDelete(db, pItem->pOn);
3348 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003349 }
drh633e6d52008-07-28 19:34:53 +00003350 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003351}
3352
drh982cef72000-05-30 16:27:03 +00003353/*
drh61dfc312006-12-16 16:25:15 +00003354** This routine is called by the parser to add a new term to the
3355** end of a growing FROM clause. The "p" parameter is the part of
3356** the FROM clause that has already been constructed. "p" is NULL
3357** if this is the first term of the FROM clause. pTable and pDatabase
3358** are the name of the table and database named in the FROM clause term.
3359** pDatabase is NULL if the database name qualifier is missing - the
3360** usual case. If the term has a alias, then pAlias points to the
3361** alias token. If the term is a subquery, then pSubquery is the
3362** SELECT statement that the subquery encodes. The pTable and
3363** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3364** parameters are the content of the ON and USING clauses.
3365**
3366** Return a new SrcList which encodes is the FROM with the new
3367** term added.
3368*/
3369SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003370 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003371 SrcList *p, /* The left part of the FROM clause already seen */
3372 Token *pTable, /* Name of the table to add to the FROM clause */
3373 Token *pDatabase, /* Name of the database containing pTable */
3374 Token *pAlias, /* The right-hand side of the AS subexpression */
3375 Select *pSubquery, /* A subquery used in place of a table name */
3376 Expr *pOn, /* The ON clause of a join */
3377 IdList *pUsing /* The USING clause of a join */
3378){
3379 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003380 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003381 if( !p && (pOn || pUsing) ){
3382 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3383 (pOn ? "ON" : "USING")
3384 );
3385 goto append_from_error;
3386 }
drh17435752007-08-16 04:30:38 +00003387 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003388 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003389 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003390 }
3391 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003392 assert( pAlias!=0 );
3393 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003394 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003395 }
3396 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003397 pItem->pOn = pOn;
3398 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003399 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003400
3401 append_from_error:
3402 assert( p==0 );
3403 sqlite3ExprDelete(db, pOn);
3404 sqlite3IdListDelete(db, pUsing);
3405 sqlite3SelectDelete(db, pSubquery);
3406 return 0;
drh61dfc312006-12-16 16:25:15 +00003407}
3408
3409/*
danielk1977b1c685b2008-10-06 16:18:39 +00003410** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3411** element of the source-list passed as the second argument.
3412*/
3413void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003414 assert( pIndexedBy!=0 );
3415 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003416 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3417 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3418 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3419 /* A "NOT INDEXED" clause was supplied. See parse.y
3420 ** construct "indexed_opt" for details. */
3421 pItem->notIndexed = 1;
3422 }else{
3423 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3424 }
3425 }
3426}
3427
3428/*
drh61dfc312006-12-16 16:25:15 +00003429** When building up a FROM clause in the parser, the join operator
3430** is initially attached to the left operand. But the code generator
3431** expects the join operator to be on the right operand. This routine
3432** Shifts all join operators from left to right for an entire FROM
3433** clause.
3434**
3435** Example: Suppose the join is like this:
3436**
3437** A natural cross join B
3438**
3439** The operator is "natural cross join". The A and B operands are stored
3440** in p->a[0] and p->a[1], respectively. The parser initially stores the
3441** operator with A. This routine shifts that operator over to B.
3442*/
3443void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003444 if( p ){
drh61dfc312006-12-16 16:25:15 +00003445 int i;
drhd017ab92011-08-23 00:01:58 +00003446 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003447 for(i=p->nSrc-1; i>0; i--){
3448 p->a[i].jointype = p->a[i-1].jointype;
3449 }
3450 p->a[0].jointype = 0;
3451 }
3452}
3453
3454/*
drhc4a3c772001-04-04 11:48:57 +00003455** Begin a transaction
3456*/
drh684917c2004-10-05 02:41:42 +00003457void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003458 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003459 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003460 int i;
drh5e00f6c2001-09-13 13:46:56 +00003461
drhd3001712009-05-12 17:46:53 +00003462 assert( pParse!=0 );
3463 db = pParse->db;
3464 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003465/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003466 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3467 return;
3468 }
danielk19771d850a72004-05-31 08:26:49 +00003469 v = sqlite3GetVdbe(pParse);
3470 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003471 if( type!=TK_DEFERRED ){
3472 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003473 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003474 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003475 }
3476 }
drh66a51672008-01-03 00:01:23 +00003477 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003478}
3479
3480/*
3481** Commit a transaction
3482*/
danielk19774adee202004-05-08 08:23:19 +00003483void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003484 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003485
drhd3001712009-05-12 17:46:53 +00003486 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003487 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003488 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3489 return;
3490 }
danielk19771d850a72004-05-31 08:26:49 +00003491 v = sqlite3GetVdbe(pParse);
3492 if( v ){
drh66a51672008-01-03 00:01:23 +00003493 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003494 }
drhc4a3c772001-04-04 11:48:57 +00003495}
3496
3497/*
3498** Rollback a transaction
3499*/
danielk19774adee202004-05-08 08:23:19 +00003500void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003501 Vdbe *v;
3502
drhd3001712009-05-12 17:46:53 +00003503 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003504 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003505 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3506 return;
3507 }
danielk19774adee202004-05-08 08:23:19 +00003508 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003509 if( v ){
drh66a51672008-01-03 00:01:23 +00003510 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003511 }
drhc4a3c772001-04-04 11:48:57 +00003512}
drhf57b14a2001-09-14 18:54:08 +00003513
3514/*
danielk1977fd7f0452008-12-17 17:30:26 +00003515** This function is called by the parser when it parses a command to create,
3516** release or rollback an SQL savepoint.
3517*/
3518void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003519 char *zName = sqlite3NameFromToken(pParse->db, pName);
3520 if( zName ){
3521 Vdbe *v = sqlite3GetVdbe(pParse);
3522#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003523 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003524 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3525#endif
3526 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3527 sqlite3DbFree(pParse->db, zName);
3528 return;
3529 }
3530 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003531 }
3532}
3533
3534/*
drhdc3ff9c2004-08-18 02:10:15 +00003535** Make sure the TEMP database is open and available for use. Return
3536** the number of errors. Leave any error messages in the pParse structure.
3537*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003538int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003539 sqlite3 *db = pParse->db;
3540 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003541 int rc;
drh10a76c92010-01-26 01:25:26 +00003542 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003543 static const int flags =
3544 SQLITE_OPEN_READWRITE |
3545 SQLITE_OPEN_CREATE |
3546 SQLITE_OPEN_EXCLUSIVE |
3547 SQLITE_OPEN_DELETEONCLOSE |
3548 SQLITE_OPEN_TEMP_DB;
3549
dan3a6d8ae2011-04-23 15:54:54 +00003550 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003551 if( rc!=SQLITE_OK ){
3552 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3553 "file for storing temporary tables");
3554 pParse->rc = rc;
3555 return 1;
3556 }
drh10a76c92010-01-26 01:25:26 +00003557 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003558 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003559 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3560 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003561 return 1;
drh10a76c92010-01-26 01:25:26 +00003562 }
drhdc3ff9c2004-08-18 02:10:15 +00003563 }
3564 return 0;
3565}
3566
3567/*
drh80242052004-06-09 00:48:12 +00003568** Generate VDBE code that will verify the schema cookie and start
3569** a read-transaction for all named database files.
3570**
3571** It is important that all schema cookies be verified and all
3572** read transactions be started before anything else happens in
3573** the VDBE program. But this routine can be called after much other
3574** code has been generated. So here is what we do:
3575**
drhc275b4e2004-07-19 17:25:24 +00003576** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003577** will jump to a subroutine at the end of the program. Then we
3578** record every database that needs its schema verified in the
3579** pParse->cookieMask field. Later, after all other code has been
3580** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003581** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003582** will be made to point to that subroutine. The generation of the
3583** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003584**
3585** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3586** schema on any databases. This can be used to position the OP_Goto
3587** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003588*/
danielk19774adee202004-05-08 08:23:19 +00003589void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003590 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003591
dan65a7cd12009-09-01 12:16:01 +00003592 if( pToplevel->cookieGoto==0 ){
3593 Vdbe *v = sqlite3GetVdbe(pToplevel);
3594 if( v==0 ) return; /* This only happens if there was a prior error */
3595 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003596 }
drhc275b4e2004-07-19 17:25:24 +00003597 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003598 sqlite3 *db = pToplevel->db;
drh64123582011-04-02 20:01:02 +00003599 yDbMask mask;
dan65a7cd12009-09-01 12:16:01 +00003600
drhc275b4e2004-07-19 17:25:24 +00003601 assert( iDb<db->nDb );
3602 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003603 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drh21206082011-04-04 18:22:02 +00003604 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh64123582011-04-02 20:01:02 +00003605 mask = ((yDbMask)1)<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003606 if( (pToplevel->cookieMask & mask)==0 ){
3607 pToplevel->cookieMask |= mask;
3608 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003609 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003610 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003611 }
drhc275b4e2004-07-19 17:25:24 +00003612 }
drh001bbcb2003-03-19 03:14:00 +00003613 }
drh001bbcb2003-03-19 03:14:00 +00003614}
3615
3616/*
dan57966752011-04-09 17:32:58 +00003617** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3618** attached database. Otherwise, invoke it for the database named zDb only.
3619*/
3620void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3621 sqlite3 *db = pParse->db;
3622 int i;
3623 for(i=0; i<db->nDb; i++){
3624 Db *pDb = &db->aDb[i];
3625 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3626 sqlite3CodeVerifySchema(pParse, i);
3627 }
3628 }
3629}
3630
3631/*
drh1c928532002-01-31 15:54:21 +00003632** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003633** might change the database.
3634**
3635** This routine starts a new transaction if we are not already within
3636** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003637** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003638** be set for operations that might fail (due to a constraint) part of
3639** the way through and which will need to undo some writes without having to
3640** rollback the whole transaction. For operations where all constraints
3641** can be checked before any changes are made to the database, it is never
3642** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003643*/
drh7f0f12e2004-05-21 13:39:50 +00003644void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003645 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003646 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003647 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003648 pToplevel->isMultiWrite |= setStatement;
3649}
3650
drhff738bc2009-09-24 00:09:58 +00003651/*
3652** Indicate that the statement currently under construction might write
3653** more than one entry (example: deleting one row then inserting another,
3654** inserting multiple rows in a table, or inserting a row and index entries.)
3655** If an abort occurs after some of these writes have completed, then it will
3656** be necessary to undo the completed writes.
3657*/
3658void sqlite3MultiWrite(Parse *pParse){
3659 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3660 pToplevel->isMultiWrite = 1;
3661}
3662
dane0af83a2009-09-08 19:15:01 +00003663/*
drhff738bc2009-09-24 00:09:58 +00003664** The code generator calls this routine if is discovers that it is
3665** possible to abort a statement prior to completion. In order to
3666** perform this abort without corrupting the database, we need to make
3667** sure that the statement is protected by a statement transaction.
3668**
3669** Technically, we only need to set the mayAbort flag if the
3670** isMultiWrite flag was previously set. There is a time dependency
3671** such that the abort must occur after the multiwrite. This makes
3672** some statements involving the REPLACE conflict resolution algorithm
3673** go a little faster. But taking advantage of this time dependency
3674** makes it more difficult to prove that the code is correct (in
3675** particular, it prevents us from writing an effective
3676** implementation of sqlite3AssertMayAbort()) and so we have chosen
3677** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003678*/
3679void sqlite3MayAbort(Parse *pParse){
3680 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3681 pToplevel->mayAbort = 1;
3682}
3683
3684/*
3685** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3686** error. The onError parameter determines which (if any) of the statement
3687** and/or current transaction is rolled back.
3688*/
3689void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3690 Vdbe *v = sqlite3GetVdbe(pParse);
3691 if( onError==OE_Abort ){
3692 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003693 }
dane0af83a2009-09-08 19:15:01 +00003694 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003695}
3696
drh4343fea2004-11-05 23:46:15 +00003697/*
3698** Check to see if pIndex uses the collating sequence pColl. Return
3699** true if it does and false if it does not.
3700*/
3701#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003702static int collationMatch(const char *zColl, Index *pIndex){
3703 int i;
drh04491712009-05-13 17:21:13 +00003704 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003705 for(i=0; i<pIndex->nColumn; i++){
3706 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003707 assert( z!=0 );
3708 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003709 return 1;
3710 }
drh4343fea2004-11-05 23:46:15 +00003711 }
3712 return 0;
3713}
3714#endif
3715
3716/*
3717** Recompute all indices of pTab that use the collating sequence pColl.
3718** If pColl==0 then recompute all indices of pTab.
3719*/
3720#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003721static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003722 Index *pIndex; /* An index associated with pTab */
3723
3724 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003725 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003726 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3727 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003728 sqlite3RefillIndex(pParse, pIndex, -1);
3729 }
3730 }
3731}
3732#endif
3733
3734/*
3735** Recompute all indices of all tables in all databases where the
3736** indices use the collating sequence pColl. If pColl==0 then recompute
3737** all indices everywhere.
3738*/
3739#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003740static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003741 Db *pDb; /* A single database */
3742 int iDb; /* The database index number */
3743 sqlite3 *db = pParse->db; /* The database connection */
3744 HashElem *k; /* For looping over tables in pDb */
3745 Table *pTab; /* A table in the database */
3746
drh21206082011-04-04 18:22:02 +00003747 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00003748 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003749 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003750 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003751 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003752 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003753 }
3754 }
3755}
3756#endif
3757
3758/*
drheee46cf2004-11-06 00:02:48 +00003759** Generate code for the REINDEX command.
3760**
3761** REINDEX -- 1
3762** REINDEX <collation> -- 2
3763** REINDEX ?<database>.?<tablename> -- 3
3764** REINDEX ?<database>.?<indexname> -- 4
3765**
3766** Form 1 causes all indices in all attached databases to be rebuilt.
3767** Form 2 rebuilds all indices in all databases that use the named
3768** collating function. Forms 3 and 4 rebuild the named index or all
3769** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003770*/
3771#ifndef SQLITE_OMIT_REINDEX
3772void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3773 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3774 char *z; /* Name of a table or index */
3775 const char *zDb; /* Name of the database */
3776 Table *pTab; /* A table in the database */
3777 Index *pIndex; /* An index associated with pTab */
3778 int iDb; /* The database index number */
3779 sqlite3 *db = pParse->db; /* The database connection */
3780 Token *pObjName; /* Name of the table or index to be reindexed */
3781
danielk197733a5edc2005-01-27 00:22:02 +00003782 /* Read the database schema. If an error occurs, leave an error message
3783 ** and code in pParse and return NULL. */
3784 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003785 return;
danielk197733a5edc2005-01-27 00:22:02 +00003786 }
3787
drh8af73d42009-05-13 22:58:28 +00003788 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003789 reindexDatabases(pParse, 0);
3790 return;
drhd3001712009-05-12 17:46:53 +00003791 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003792 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003793 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003794 zColl = sqlite3NameFromToken(pParse->db, pName1);
3795 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003796 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003797 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003798 reindexDatabases(pParse, zColl);
3799 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003800 return;
3801 }
drh633e6d52008-07-28 19:34:53 +00003802 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003803 }
3804 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3805 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003806 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003807 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003808 zDb = db->aDb[iDb].zName;
3809 pTab = sqlite3FindTable(db, z, zDb);
3810 if( pTab ){
3811 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003812 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003813 return;
3814 }
3815 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003816 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003817 if( pIndex ){
3818 sqlite3BeginWriteOperation(pParse, 0, iDb);
3819 sqlite3RefillIndex(pParse, pIndex, -1);
3820 return;
3821 }
3822 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3823}
3824#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003825
3826/*
3827** Return a dynamicly allocated KeyInfo structure that can be used
3828** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3829**
3830** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003831** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003832** pointer. If an error occurs (out of memory or missing collation
3833** sequence), NULL is returned and the state of pParse updated to reflect
3834** the error.
3835*/
3836KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3837 int i;
3838 int nCol = pIdx->nColumn;
3839 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003840 sqlite3 *db = pParse->db;
3841 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003842
3843 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003844 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003845 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3846 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3847 for(i=0; i<nCol; i++){
3848 char *zColl = pIdx->azColl[i];
3849 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003850 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003851 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3852 }
drh1bd10f82008-12-10 21:19:56 +00003853 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003854 }
3855
3856 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003857 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003858 pKey = 0;
3859 }
3860 return pKey;
3861}