blob: 7c05e29e22c73c181c4600eb06d8cacdb81d944f [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
drhbed86902000-06-02 13:27:59 +000024**
drhb7f24de2009-05-13 17:35:23 +000025** $Id: build.c,v 1.543 2009/05/13 17:35:23 drh Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
28
29/*
drhe0bc4042002-06-25 01:09:11 +000030** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000031** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000032*/
danielk19774adee202004-05-08 08:23:19 +000033void sqlite3BeginParse(Parse *pParse, int explainFlag){
drh1bd10f82008-12-10 21:19:56 +000034 pParse->explain = (u8)explainFlag;
drh7c972de2003-09-06 22:18:07 +000035 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000036}
37
danielk1977c00da102006-01-07 13:21:04 +000038#ifndef SQLITE_OMIT_SHARED_CACHE
39/*
40** The TableLock structure is only used by the sqlite3TableLock() and
41** codeTableLocks() functions.
42*/
43struct TableLock {
drhd698bc12006-03-23 23:33:26 +000044 int iDb; /* The database containing the table to be locked */
45 int iTab; /* The root page of the table to be locked */
46 u8 isWriteLock; /* True for write lock. False for a read lock */
47 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000048};
49
50/*
drhd698bc12006-03-23 23:33:26 +000051** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000052**
drhd698bc12006-03-23 23:33:26 +000053** The table to be locked has root page iTab and is found in database iDb.
54** A read or a write lock can be taken depending on isWritelock.
55**
56** This routine just records the fact that the lock is desired. The
57** code to make the lock occur is generated by a later call to
58** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000059*/
60void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000061 Parse *pParse, /* Parsing context */
62 int iDb, /* Index of the database containing the table to lock */
63 int iTab, /* Root page number of the table to be locked */
64 u8 isWriteLock, /* True for a write lock */
65 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000066){
67 int i;
68 int nBytes;
69 TableLock *p;
danielk1977c00da102006-01-07 13:21:04 +000070
drh04491712009-05-13 17:21:13 +000071 if( NEVER(iDb<0) ) return;
danielk1977c00da102006-01-07 13:21:04 +000072 for(i=0; i<pParse->nTableLock; i++){
73 p = &pParse->aTableLock[i];
74 if( p->iDb==iDb && p->iTab==iTab ){
75 p->isWriteLock = (p->isWriteLock || isWriteLock);
76 return;
77 }
78 }
79
80 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
drh17435752007-08-16 04:30:38 +000081 pParse->aTableLock =
82 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
danielk1977c00da102006-01-07 13:21:04 +000083 if( pParse->aTableLock ){
84 p = &pParse->aTableLock[pParse->nTableLock++];
85 p->iDb = iDb;
86 p->iTab = iTab;
87 p->isWriteLock = isWriteLock;
88 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000089 }else{
90 pParse->nTableLock = 0;
91 pParse->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000092 }
93}
94
95/*
96** Code an OP_TableLock instruction for each table locked by the
97** statement (configured by calls to sqlite3TableLock()).
98*/
99static void codeTableLocks(Parse *pParse){
100 int i;
101 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000102
drh04491712009-05-13 17:21:13 +0000103 pVdbe = sqlite3GetVdbe(pParse);
104 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
danielk1977c00da102006-01-07 13:21:04 +0000105
106 for(i=0; i<pParse->nTableLock; i++){
107 TableLock *p = &pParse->aTableLock[i];
108 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000109 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
110 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000111 }
112}
113#else
114 #define codeTableLocks(x)
115#endif
116
drhe0bc4042002-06-25 01:09:11 +0000117/*
drh75897232000-05-29 14:26:00 +0000118** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000119** parsed and a VDBE program to execute that statement has been
120** prepared. This routine puts the finishing touches on the
121** VDBE program and resets the pParse structure for the next
122** parse.
drh75897232000-05-29 14:26:00 +0000123**
124** Note that if an error occurred, it might be the case that
125** no VDBE code was generated.
126*/
drh80242052004-06-09 00:48:12 +0000127void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000128 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000129 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000130
drh17435752007-08-16 04:30:38 +0000131 db = pParse->db;
132 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000133 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000134 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000135
drh80242052004-06-09 00:48:12 +0000136 /* Begin by generating some termination code at the end of the
137 ** vdbe program
138 */
drh80242052004-06-09 00:48:12 +0000139 v = sqlite3GetVdbe(pParse);
140 if( v ){
drh66a51672008-01-03 00:01:23 +0000141 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000142
143 /* The cookie mask contains one bit for each database file open.
144 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
145 ** set for each database that is used. Generate code to start a
146 ** transaction on each used database and to verify the schema cookie
147 ** on each used database.
148 */
drhc275b4e2004-07-19 17:25:24 +0000149 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000150 u32 mask;
drh26e4a8b2008-05-01 17:16:52 +0000151 int iDb;
drhd654be82005-09-20 17:42:23 +0000152 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000153 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
154 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000155 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000156 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drh8a939192009-04-20 17:43:03 +0000157 if( db->init.busy==0 ){
158 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
159 }
drh80242052004-06-09 00:48:12 +0000160 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000161#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000162 {
163 int i;
164 for(i=0; i<pParse->nVtabLock; i++){
165 char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
166 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
167 }
168 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000169 }
170#endif
danielk1977c00da102006-01-07 13:21:04 +0000171
172 /* Once all the cookies have been verified and transactions opened,
173 ** obtain the required table-locks. This is a no-op unless the
174 ** shared-cache feature is enabled.
175 */
176 codeTableLocks(pParse);
drh66a51672008-01-03 00:01:23 +0000177 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000178 }
drh71c697e2004-08-08 23:39:19 +0000179 }
180
drh3f7d4e42004-07-24 14:35:58 +0000181
drh80242052004-06-09 00:48:12 +0000182 /* Get the VDBE program ready for execution
183 */
drh04491712009-05-13 17:21:13 +0000184 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000185#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000186 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000187 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000188#endif
drhceea3322009-04-23 13:22:42 +0000189 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
danielk19776ab3a2e2009-02-19 14:39:25 +0000190 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
191 pParse->nTab, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000192 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000193 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000194 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000195 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000196 }
drha226d052002-09-25 19:04:07 +0000197 pParse->nTab = 0;
198 pParse->nMem = 0;
199 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000200 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000201 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000202 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000203}
204
205/*
drh205f48e2004-11-05 00:43:11 +0000206** Run the parser and code generator recursively in order to generate
207** code for the SQL statement given onto the end of the pParse context
208** currently under construction. When the parser is run recursively
209** this way, the final OP_Halt is not appended and other initialization
210** and finalization steps are omitted because those are handling by the
211** outermost parser.
212**
213** Not everything is nestable. This facility is designed to permit
214** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000215** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000216*/
217void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
218 va_list ap;
219 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000220 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000221 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000222# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
223 char saveBuf[SAVE_SZ];
224
drh205f48e2004-11-05 00:43:11 +0000225 if( pParse->nErr ) return;
226 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
227 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000228 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000229 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000230 if( zSql==0 ){
231 return; /* A malloc must have failed */
232 }
drh205f48e2004-11-05 00:43:11 +0000233 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000234 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
235 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000236 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000237 sqlite3DbFree(db, zErrMsg);
238 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000239 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000240 pParse->nested--;
241}
242
243/*
danielk19778a414492004-06-29 08:59:35 +0000244** Locate the in-memory structure that describes a particular database
245** table given the name of that table and (optionally) the name of the
246** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000247**
danielk19778a414492004-06-29 08:59:35 +0000248** If zDatabase is 0, all databases are searched for the table and the
249** first matching table is returned. (No checking for duplicate table
250** names is done.) The search order is TEMP first, then MAIN, then any
251** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000252**
danielk19774adee202004-05-08 08:23:19 +0000253** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000254*/
drh9bb575f2004-09-06 17:24:11 +0000255Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000256 Table *p = 0;
257 int i;
drh0a687d12008-07-08 14:52:07 +0000258 int nName;
drh645f63e2004-06-22 13:22:40 +0000259 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000260 nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000261 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000262 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000263 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh0a687d12008-07-08 14:52:07 +0000264 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000265 if( p ) break;
266 }
drh74e24cd2002-01-09 03:19:59 +0000267 return p;
drh75897232000-05-29 14:26:00 +0000268}
269
270/*
danielk19778a414492004-06-29 08:59:35 +0000271** Locate the in-memory structure that describes a particular database
272** table given the name of that table and (optionally) the name of the
273** database containing the table. Return NULL if not found. Also leave an
274** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000275**
danielk19778a414492004-06-29 08:59:35 +0000276** The difference between this routine and sqlite3FindTable() is that this
277** routine leaves an error message in pParse->zErrMsg where
278** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000279*/
drhca424112008-01-25 15:04:48 +0000280Table *sqlite3LocateTable(
281 Parse *pParse, /* context in which to report errors */
282 int isView, /* True if looking for a VIEW rather than a TABLE */
283 const char *zName, /* Name of the table we are looking for */
284 const char *zDbase /* Name of the database. Might be NULL */
285){
drha69d9162003-04-17 22:57:53 +0000286 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000287
danielk19778a414492004-06-29 08:59:35 +0000288 /* Read the database schema. If an error occurs, leave an error message
289 ** and code in pParse and return NULL. */
290 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
291 return 0;
292 }
293
danielk19774adee202004-05-08 08:23:19 +0000294 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000295 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000296 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000297 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000298 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000299 }else{
drhca424112008-01-25 15:04:48 +0000300 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000301 }
drha6ecd332004-06-10 00:29:09 +0000302 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000303 }
304 return p;
305}
306
307/*
308** Locate the in-memory structure that describes
309** a particular index given the name of that index
310** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000311** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000312**
313** If zDatabase is 0, all databases are searched for the
314** table and the first matching index is returned. (No checking
315** for duplicate index names is done.) The search order is
316** TEMP first, then MAIN, then any auxiliary databases added
317** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000318*/
drh9bb575f2004-09-06 17:24:11 +0000319Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000320 Index *p = 0;
321 int i;
drhdee0e402009-05-03 20:23:53 +0000322 int nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000323 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000324 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000325 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000326 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000327 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh04491712009-05-13 17:21:13 +0000328 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000329 if( p ) break;
330 }
drh74e24cd2002-01-09 03:19:59 +0000331 return p;
drh75897232000-05-29 14:26:00 +0000332}
333
334/*
drh956bc922004-07-24 17:38:29 +0000335** Reclaim the memory used by an index
336*/
337static void freeIndex(Index *p){
drhd9da78a2009-03-24 15:08:09 +0000338 sqlite3 *db = p->pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000339 testcase( db==0 );
drh633e6d52008-07-28 19:34:53 +0000340 sqlite3DbFree(db, p->zColAff);
341 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000342}
343
344/*
drh75897232000-05-29 14:26:00 +0000345** Remove the given index from the index hash table, and free
346** its memory structures.
347**
drhd229ca92002-01-09 13:30:41 +0000348** The index is removed from the database hash tables but
349** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000350** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000351*/
drh03881232009-02-13 03:43:31 +0000352static void sqlite3DeleteIndex(Index *p){
drhd229ca92002-01-09 13:30:41 +0000353 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000354 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000355
drhea678832008-12-10 19:26:22 +0000356 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
drha83ccca2009-04-28 13:01:09 +0000357 sqlite3Strlen30(zName), 0);
drh85c23c62005-08-20 03:03:04 +0000358 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000359 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000360}
361
362/*
drhc96d8532005-05-03 12:30:33 +0000363** For the index called zIdxName which is found in the database iDb,
364** unlike that index from its Table then remove the index from
365** the index hash table and free all memory structures associated
366** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000367*/
drh9bb575f2004-09-06 17:24:11 +0000368void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000369 Index *pIndex;
370 int len;
danielk1977da184232006-01-05 11:34:32 +0000371 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000372
drhdee0e402009-05-03 20:23:53 +0000373 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000374 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh04491712009-05-13 17:21:13 +0000375 /* Justification of ALWAYS(): This routine is only called from the
376 ** OP_DropIndex opcode. And there is no way that opcode will ever run
377 ** unless the corresponding index is in the symbol table. */
378 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000379 if( pIndex->pTable->pIndex==pIndex ){
380 pIndex->pTable->pIndex = pIndex->pNext;
381 }else{
382 Index *p;
drh04491712009-05-13 17:21:13 +0000383 /* Justification of ALWAYS(); The index must be on the list of
384 ** indices. */
385 p = pIndex->pTable->pIndex;
386 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
387 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000388 p->pNext = pIndex->pNext;
389 }
drh5e00f6c2001-09-13 13:46:56 +0000390 }
drh956bc922004-07-24 17:38:29 +0000391 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000392 }
drh956bc922004-07-24 17:38:29 +0000393 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000394}
395
396/*
drhe0bc4042002-06-25 01:09:11 +0000397** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000398** a single database. This routine is called to reclaim memory
399** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000400** if there were schema changes during the transaction or if a
401** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000402**
drh62312862009-02-03 22:17:42 +0000403** If iDb==0 then reset the internal schema tables for all database
404** files. If iDb>=1 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000405** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000406*/
drh9bb575f2004-09-06 17:24:11 +0000407void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000408 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000409 assert( iDb>=0 && iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000410
411 if( iDb==0 ){
412 sqlite3BtreeEnterAll(db);
413 }
drh1c2d8412003-03-31 00:30:47 +0000414 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000415 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000416 if( pDb->pSchema ){
danielk19774eab8b72007-12-27 15:12:16 +0000417 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
danielk1977de0fe3e2006-01-06 06:33:12 +0000418 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000419 }
drh1c2d8412003-03-31 00:30:47 +0000420 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000421 }
drh1c2d8412003-03-31 00:30:47 +0000422 assert( iDb==0 );
423 db->flags &= ~SQLITE_InternChanges;
danielk19774eab8b72007-12-27 15:12:16 +0000424 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000425
426 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000427 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000428 ** opportunity to do this here since we have just deleted all of the
429 ** schema hash tables and therefore do not have to make any changes
430 ** to any of those tables.
431 */
432 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000433 struct Db *pDb = &db->aDb[i];
434 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000435 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000436 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000437 continue;
438 }
439 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000440 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000441 }
drh8bf8dc92003-05-17 17:35:10 +0000442 j++;
drh1c2d8412003-03-31 00:30:47 +0000443 }
444 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
445 db->nDb = j;
446 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
447 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000448 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000449 db->aDb = db->aDbStatic;
450 }
drhe0bc4042002-06-25 01:09:11 +0000451}
452
453/*
drhe0bc4042002-06-25 01:09:11 +0000454** This routine is called when a commit occurs.
455*/
drh9bb575f2004-09-06 17:24:11 +0000456void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000457 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000458}
459
460/*
drh956bc922004-07-24 17:38:29 +0000461** Clear the column names from a table or view.
462*/
463static void sqliteResetColumnNames(Table *pTable){
464 int i;
465 Column *pCol;
drhd9da78a2009-03-24 15:08:09 +0000466 sqlite3 *db = pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000467 testcase( db==0 );
drh956bc922004-07-24 17:38:29 +0000468 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000469 if( (pCol = pTable->aCol)!=0 ){
470 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000471 sqlite3DbFree(db, pCol->zName);
472 sqlite3ExprDelete(db, pCol->pDflt);
473 sqlite3DbFree(db, pCol->zType);
474 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000475 }
drh633e6d52008-07-28 19:34:53 +0000476 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000477 }
drh956bc922004-07-24 17:38:29 +0000478 pTable->aCol = 0;
479 pTable->nCol = 0;
480}
481
482/*
drh75897232000-05-29 14:26:00 +0000483** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000484** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000485**
486** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000487** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000488** memory structures of the indices and foreign keys associated with
489** the table.
drh75897232000-05-29 14:26:00 +0000490*/
danielk1977a04a34f2007-04-16 15:06:25 +0000491void sqlite3DeleteTable(Table *pTable){
drh75897232000-05-29 14:26:00 +0000492 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000493 FKey *pFKey, *pNextFKey;
drh633e6d52008-07-28 19:34:53 +0000494 sqlite3 *db;
drhc2eef3b2002-08-31 18:53:06 +0000495
drh75897232000-05-29 14:26:00 +0000496 if( pTable==0 ) return;
drhd9da78a2009-03-24 15:08:09 +0000497 db = pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000498 testcase( db==0 );
drhc2eef3b2002-08-31 18:53:06 +0000499
drhed8a3bb2005-06-06 21:19:56 +0000500 /* Do not delete the table until the reference count reaches zero. */
501 pTable->nRef--;
502 if( pTable->nRef>0 ){
503 return;
504 }
505 assert( pTable->nRef==0 );
506
drhc2eef3b2002-08-31 18:53:06 +0000507 /* Delete all indices associated with this table
508 */
509 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
510 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000511 assert( pIndex->pSchema==pTable->pSchema );
drh03881232009-02-13 03:43:31 +0000512 sqlite3DeleteIndex(pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000513 }
514
danielk1977576ec6b2005-01-21 11:55:25 +0000515#ifndef SQLITE_OMIT_FOREIGN_KEY
drhe61922a2009-05-02 13:29:37 +0000516 /* Delete all foreign keys associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000517 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
518 pNextFKey = pFKey->pNextFrom;
drh633e6d52008-07-28 19:34:53 +0000519 sqlite3DbFree(db, pFKey);
drhc2eef3b2002-08-31 18:53:06 +0000520 }
danielk1977576ec6b2005-01-21 11:55:25 +0000521#endif
drhc2eef3b2002-08-31 18:53:06 +0000522
523 /* Delete the Table structure itself.
524 */
drh956bc922004-07-24 17:38:29 +0000525 sqliteResetColumnNames(pTable);
drh633e6d52008-07-28 19:34:53 +0000526 sqlite3DbFree(db, pTable->zName);
527 sqlite3DbFree(db, pTable->zColAff);
528 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000529#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000530 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000531#endif
drhb9bb7c12006-06-11 23:41:55 +0000532 sqlite3VtabClear(pTable);
drh633e6d52008-07-28 19:34:53 +0000533 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000534}
535
536/*
drh5edc3122001-09-13 21:53:09 +0000537** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000538** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000539*/
drh9bb575f2004-09-06 17:24:11 +0000540void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000541 Table *p;
drh956bc922004-07-24 17:38:29 +0000542 Db *pDb;
543
drhd229ca92002-01-09 13:30:41 +0000544 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000545 assert( iDb>=0 && iDb<db->nDb );
546 assert( zTabName && zTabName[0] );
547 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000548 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000549 sqlite3Strlen30(zTabName),0);
drhe61922a2009-05-02 13:29:37 +0000550 sqlite3DeleteTable(p);
drh956bc922004-07-24 17:38:29 +0000551 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000552}
553
554/*
drha99db3b2004-06-19 14:49:12 +0000555** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000556** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000557** is obtained from sqliteMalloc() and must be freed by the calling
558** function.
drh75897232000-05-29 14:26:00 +0000559**
drh24fb6272009-05-01 21:13:36 +0000560** Any quotation marks (ex: "name", 'name', [name], or `name`) that
561** surround the body of the token are removed.
562**
drhc96d8532005-05-03 12:30:33 +0000563** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000564** are not \000 terminated and are not persistent. The returned string
565** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000566*/
drh17435752007-08-16 04:30:38 +0000567char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000568 char *zName;
569 if( pName ){
drh17435752007-08-16 04:30:38 +0000570 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drh24fb6272009-05-01 21:13:36 +0000571 if( pName->quoted ) sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000572 }else{
573 zName = 0;
574 }
drh75897232000-05-29 14:26:00 +0000575 return zName;
576}
577
578/*
danielk1977cbb18d22004-05-28 11:37:27 +0000579** Open the sqlite_master table stored in database number iDb for
580** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000581*/
danielk1977c00da102006-01-07 13:21:04 +0000582void sqlite3OpenMasterTable(Parse *p, int iDb){
583 Vdbe *v = sqlite3GetVdbe(p);
584 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000585 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000586 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000587 if( p->nTab==0 ){
588 p->nTab = 1;
589 }
drhe0bc4042002-06-25 01:09:11 +0000590}
591
592/*
danielk197704103022009-02-03 16:51:24 +0000593** Parameter zName points to a nul-terminated buffer containing the name
594** of a database ("main", "temp" or the name of an attached db). This
595** function returns the index of the named database in db->aDb[], or
596** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000597*/
danielk197704103022009-02-03 16:51:24 +0000598int sqlite3FindDbName(sqlite3 *db, const char *zName){
599 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000600 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000601 Db *pDb;
602 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000603 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000604 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000605 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000606 break;
drh73c42a12004-11-20 18:13:10 +0000607 }
danielk1977cbb18d22004-05-28 11:37:27 +0000608 }
609 }
danielk1977576ec6b2005-01-21 11:55:25 +0000610 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000611}
612
danielk197704103022009-02-03 16:51:24 +0000613/*
614** The token *pName contains the name of a database (either "main" or
615** "temp" or the name of an attached db). This routine returns the
616** index of the named database in db->aDb[], or -1 if the named db
617** does not exist.
618*/
619int sqlite3FindDb(sqlite3 *db, Token *pName){
620 int i; /* Database number */
621 char *zName; /* Name we are searching for */
622 zName = sqlite3NameFromToken(db, pName);
623 i = sqlite3FindDbName(db, zName);
624 sqlite3DbFree(db, zName);
625 return i;
626}
627
drh0e3d7472004-06-19 17:33:07 +0000628/* The table or view or trigger name is passed to this routine via tokens
629** pName1 and pName2. If the table name was fully qualified, for example:
630**
631** CREATE TABLE xxx.yyy (...);
632**
633** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
634** the table name is not fully qualified, i.e.:
635**
636** CREATE TABLE yyy(...);
637**
638** Then pName1 is set to "yyy" and pName2 is "".
639**
640** This routine sets the *ppUnqual pointer to point at the token (pName1 or
641** pName2) that stores the unqualified table name. The index of the
642** database "xxx" is returned.
643*/
danielk1977ef2cb632004-05-29 02:37:19 +0000644int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000645 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000646 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000647 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
648 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000649){
drh0e3d7472004-06-19 17:33:07 +0000650 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000651 sqlite3 *db = pParse->db;
652
drhc4a64fa2009-05-11 20:53:28 +0000653 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000654 if( db->init.busy ) {
655 sqlite3ErrorMsg(pParse, "corrupt database");
656 pParse->nErr++;
657 return -1;
658 }
danielk1977cbb18d22004-05-28 11:37:27 +0000659 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000660 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000661 if( iDb<0 ){
662 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
663 pParse->nErr++;
664 return -1;
665 }
666 }else{
667 assert( db->init.iDb==0 || db->init.busy );
668 iDb = db->init.iDb;
669 *pUnqual = pName1;
670 }
671 return iDb;
672}
673
674/*
danielk1977d8123362004-06-12 09:25:12 +0000675** This routine is used to check if the UTF-8 string zName is a legal
676** unqualified name for a new schema object (table, index, view or
677** trigger). All names are legal except those that begin with the string
678** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
679** is reserved for internal use.
680*/
681int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000682 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000683 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000684 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000685 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
686 return SQLITE_ERROR;
687 }
688 return SQLITE_OK;
689}
690
691/*
drh75897232000-05-29 14:26:00 +0000692** Begin constructing a new table representation in memory. This is
693** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000694** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000695** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000696** flag is true if the table should be stored in the auxiliary database
697** file instead of in the main database file. This is normally the case
698** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000699** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000700**
drhf57b3392001-10-08 13:22:32 +0000701** The new table record is initialized and put in pParse->pNewTable.
702** As more of the CREATE TABLE statement is parsed, additional action
703** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000704** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000705** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000706*/
danielk19774adee202004-05-08 08:23:19 +0000707void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000708 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000709 Token *pName1, /* First part of the name of the table or view */
710 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000711 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000712 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000713 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000714 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000715){
drh75897232000-05-29 14:26:00 +0000716 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000717 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000718 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000719 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000720 int iDb; /* Database number to create the table in */
721 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000722
danielk1977cbb18d22004-05-28 11:37:27 +0000723 /* The table or view name to create is passed to this routine via tokens
724 ** pName1 and pName2. If the table name was fully qualified, for example:
725 **
726 ** CREATE TABLE xxx.yyy (...);
727 **
728 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
729 ** the table name is not fully qualified, i.e.:
730 **
731 ** CREATE TABLE yyy(...);
732 **
733 ** Then pName1 is set to "yyy" and pName2 is "".
734 **
735 ** The call below sets the pName pointer to point at the token (pName1 or
736 ** pName2) that stores the unqualified table name. The variable iDb is
737 ** set to the index of the database that the table or view is to be
738 ** created in.
739 */
danielk1977ef2cb632004-05-29 02:37:19 +0000740 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000741 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000742 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000743 /* If creating a temp table, the name may not be qualified */
744 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000745 return;
746 }
danielk197753c0f742005-03-29 03:10:59 +0000747 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000748
749 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000750 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000751 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000752 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000753 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000754 }
drh1d85d932004-02-14 23:05:52 +0000755 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000756#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000757 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000758 {
759 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000760 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000761 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000762 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000763 }
drhe5f9c642003-01-13 23:27:31 +0000764 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000765 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000766 code = SQLITE_CREATE_TEMP_VIEW;
767 }else{
768 code = SQLITE_CREATE_VIEW;
769 }
770 }else{
danielk197753c0f742005-03-29 03:10:59 +0000771 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000772 code = SQLITE_CREATE_TEMP_TABLE;
773 }else{
774 code = SQLITE_CREATE_TABLE;
775 }
776 }
danielk1977f1a381e2006-06-16 08:01:02 +0000777 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000778 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000779 }
780 }
781#endif
drhf57b3392001-10-08 13:22:32 +0000782
drhf57b3392001-10-08 13:22:32 +0000783 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000784 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000785 ** it does. The exception is if the statement being parsed was passed
786 ** to an sqlite3_declare_vtab() call. In that case only the column names
787 ** and types will be used, so there is no need to test for namespace
788 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000789 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000790 if( !IN_DECLARE_VTAB ){
791 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
792 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000793 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000794 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
795 if( pTable ){
796 if( !noErr ){
797 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
798 }
799 goto begin_table_error;
800 }
801 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
802 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
803 goto begin_table_error;
804 }
drh75897232000-05-29 14:26:00 +0000805 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000806
danielk197726783a52007-08-29 14:06:22 +0000807 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000808 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000809 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000810 pParse->rc = SQLITE_NOMEM;
811 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000812 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000813 }
drh75897232000-05-29 14:26:00 +0000814 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000815 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000816 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000817 pTable->nRef = 1;
drhc4a64fa2009-05-11 20:53:28 +0000818 pTable->dbMem = 0;
819 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000820 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000821
drh4794f732004-11-05 17:17:50 +0000822 /* If this is the magic sqlite_sequence table used by autoincrement,
823 ** then record a pointer to this table in the main database structure
824 ** so that INSERT can find the table easily.
825 */
826#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000827 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000828 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000829 }
830#endif
831
drh17f71932002-02-21 12:01:27 +0000832 /* Begin generating the code that will insert the table record into
833 ** the SQLITE_MASTER table. Note in particular that we must go ahead
834 ** and allocate the record number for the table entry now. Before any
835 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
836 ** indices to be created and the table record must come before the
837 ** indices. Hence, the record number for the table must be allocated
838 ** now.
839 */
danielk19774adee202004-05-08 08:23:19 +0000840 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000841 int j1;
drhe321c292006-01-12 01:56:43 +0000842 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000843 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000844 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000845
danielk197720b1eaf2006-07-26 16:22:14 +0000846#ifndef SQLITE_OMIT_VIRTUALTABLE
847 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000848 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000849 }
850#endif
851
danielk197736963fd2005-02-19 08:18:05 +0000852 /* If the file format and encoding in the database have not been set,
853 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000854 */
drhb7654112008-01-12 12:48:07 +0000855 reg1 = pParse->regRowid = ++pParse->nMem;
856 reg2 = pParse->regRoot = ++pParse->nMem;
857 reg3 = ++pParse->nMem;
858 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */
drhfb982642007-08-30 01:19:59 +0000859 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000860 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000861 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000862 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000863 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
864 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
865 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
866 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
867 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000868
drh4794f732004-11-05 17:17:50 +0000869 /* This just creates a place-holder record in the sqlite_master table.
870 ** The record created does not contain anything yet. It will be replaced
871 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000872 **
drh0fa991b2009-03-21 16:19:26 +0000873 ** The rowid for the new entry is left in register pParse->regRowid.
874 ** The root page number of the new table is left in reg pParse->regRoot.
875 ** The rowid and root page number values are needed by the code that
876 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000877 */
danielk1977f1a381e2006-06-16 08:01:02 +0000878#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
879 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000880 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000881 }else
882#endif
883 {
drhb7654112008-01-12 12:48:07 +0000884 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000885 }
danielk1977c00da102006-01-07 13:21:04 +0000886 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000887 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
888 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
889 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
890 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000891 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000892 }
drh23bf66d2004-12-14 03:34:34 +0000893
894 /* Normal (non-error) return. */
895 return;
896
897 /* If an error occurs, we jump here */
898begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000899 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000900 return;
drh75897232000-05-29 14:26:00 +0000901}
902
903/*
danielk1977c60e9b82005-01-31 12:42:29 +0000904** This macro is used to compare two strings in a case-insensitive manner.
905** It is slightly faster than calling sqlite3StrICmp() directly, but
906** produces larger code.
907**
908** WARNING: This macro is not compatible with the strcmp() family. It
909** returns true if the two strings are equal, otherwise false.
910*/
911#define STRICMP(x, y) (\
912sqlite3UpperToLower[*(unsigned char *)(x)]== \
913sqlite3UpperToLower[*(unsigned char *)(y)] \
914&& sqlite3StrICmp((x)+1,(y)+1)==0 )
915
916/*
drh75897232000-05-29 14:26:00 +0000917** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000918**
919** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000920** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000921** first to get things going. Then this routine is called for each
922** column.
drh75897232000-05-29 14:26:00 +0000923*/
danielk19774adee202004-05-08 08:23:19 +0000924void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000925 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000926 int i;
drha99db3b2004-06-19 14:49:12 +0000927 char *z;
drhc9b84a12002-06-20 11:36:48 +0000928 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000929 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000930 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000931#if SQLITE_MAX_COLUMN
932 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000933 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
934 return;
935 }
drhbb4957f2008-03-20 14:03:29 +0000936#endif
danielk1977ae74e032008-12-23 11:11:51 +0000937 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000938 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000939 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000940 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000941 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000942 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000943 return;
944 }
945 }
drh75897232000-05-29 14:26:00 +0000946 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000947 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000948 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000949 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000950 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000951 return;
952 }
drh6d4abfb2001-10-22 02:58:08 +0000953 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000954 }
drhc9b84a12002-06-20 11:36:48 +0000955 pCol = &p->aCol[p->nCol];
956 memset(pCol, 0, sizeof(p->aCol[0]));
957 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000958
959 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000960 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
961 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000962 */
danielk19774f057f92004-06-08 00:02:33 +0000963 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000964 p->nCol++;
drh75897232000-05-29 14:26:00 +0000965}
966
967/*
drh382c0242001-10-06 16:33:02 +0000968** This routine is called by the parser while in the middle of
969** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
970** been seen on a column. This routine sets the notNull flag on
971** the column currently under construction.
972*/
danielk19774adee202004-05-08 08:23:19 +0000973void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000974 Table *p;
drhc4a64fa2009-05-11 20:53:28 +0000975 p = pParse->pNewTable;
976 if( p==0 || NEVER(p->nCol<1) ) return;
977 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000978}
979
980/*
danielk197752a83fb2005-01-31 12:56:44 +0000981** Scan the column type name zType (length nType) and return the
982** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000983**
984** This routine does a case-independent search of zType for the
985** substrings in the following table. If one of the substrings is
986** found, the corresponding affinity is returned. If zType contains
987** more than one of the substrings, entries toward the top of
988** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000989** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000990**
991** Substring | Affinity
992** --------------------------------
993** 'INT' | SQLITE_AFF_INTEGER
994** 'CHAR' | SQLITE_AFF_TEXT
995** 'CLOB' | SQLITE_AFF_TEXT
996** 'TEXT' | SQLITE_AFF_TEXT
997** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000998** 'REAL' | SQLITE_AFF_REAL
999** 'FLOA' | SQLITE_AFF_REAL
1000** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001001**
1002** If none of the substrings in the above table are found,
1003** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001004*/
drh8a512562005-11-14 22:29:05 +00001005char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +00001006 u32 h = 0;
1007 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +00001008 const unsigned char *zIn = pType->z;
1009 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +00001010
danielk1977b3dff962005-02-01 01:21:55 +00001011 while( zIn!=zEnd ){
1012 h = (h<<8) + sqlite3UpperToLower[*zIn];
1013 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001014 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1015 aff = SQLITE_AFF_TEXT;
1016 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1017 aff = SQLITE_AFF_TEXT;
1018 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1019 aff = SQLITE_AFF_TEXT;
1020 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001021 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001022 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001023#ifndef SQLITE_OMIT_FLOATING_POINT
1024 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1025 && aff==SQLITE_AFF_NUMERIC ){
1026 aff = SQLITE_AFF_REAL;
1027 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1028 && aff==SQLITE_AFF_NUMERIC ){
1029 aff = SQLITE_AFF_REAL;
1030 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1031 && aff==SQLITE_AFF_NUMERIC ){
1032 aff = SQLITE_AFF_REAL;
1033#endif
danielk1977201f7162005-02-01 02:13:29 +00001034 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001035 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001036 break;
danielk197752a83fb2005-01-31 12:56:44 +00001037 }
1038 }
danielk1977b3dff962005-02-01 01:21:55 +00001039
1040 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001041}
1042
1043/*
drh382c0242001-10-06 16:33:02 +00001044** This routine is called by the parser while in the middle of
1045** parsing a CREATE TABLE statement. The pFirst token is the first
1046** token in the sequence of tokens that describe the type of the
1047** column currently under construction. pLast is the last token
1048** in the sequence. Use this information to construct a string
1049** that contains the typename of the column and store that string
1050** in zType.
1051*/
drh487e2622005-06-25 18:42:14 +00001052void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001053 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001054 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001055
drhc4a64fa2009-05-11 20:53:28 +00001056 p = pParse->pNewTable;
1057 if( p==0 || NEVER(p->nCol<1) ) return;
1058 pCol = &p->aCol[p->nCol-1];
1059 assert( pCol->zType==0 );
1060 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drh8a512562005-11-14 22:29:05 +00001061 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001062}
1063
1064/*
danielk19777977a172004-11-09 12:44:37 +00001065** The expression is the default value for the most recently added column
1066** of the table currently under construction.
1067**
1068** Default value expressions must be constant. Raise an exception if this
1069** is not the case.
drhd9b02572001-04-15 00:37:09 +00001070**
1071** This routine is called by the parser while in the middle of
1072** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001073*/
danielk19777977a172004-11-09 12:44:37 +00001074void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001075 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001076 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001077 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001078 p = pParse->pNewTable;
1079 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001080 pCol = &(p->aCol[p->nCol-1]);
1081 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1082 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1083 pCol->zName);
1084 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001085 /* A copy of pExpr is used instead of the original, as pExpr contains
1086 ** tokens that point to volatile memory. The 'span' of the expression
1087 ** is required by pragma table_info.
1088 */
drh633e6d52008-07-28 19:34:53 +00001089 sqlite3ExprDelete(db, pCol->pDflt);
drh12ffee82009-04-08 13:51:51 +00001090 pCol->pDflt = sqlite3ExprDup(db, pExpr, EXPRDUP_REDUCE|EXPRDUP_SPAN);
drh42b9d7c2005-08-13 00:56:27 +00001091 }
danielk19777977a172004-11-09 12:44:37 +00001092 }
drh633e6d52008-07-28 19:34:53 +00001093 sqlite3ExprDelete(db, pExpr);
drh7020f652000-06-03 18:06:52 +00001094}
1095
1096/*
drh4a324312001-12-21 14:30:42 +00001097** Designate the PRIMARY KEY for the table. pList is a list of names
1098** of columns that form the primary key. If pList is NULL, then the
1099** most recently added column of the table is the primary key.
1100**
1101** A table can have at most one primary key. If the table already has
1102** a primary key (and this is the second primary key) then create an
1103** error.
1104**
1105** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001106** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001107** field of the table under construction to be the index of the
1108** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1109** no INTEGER PRIMARY KEY.
1110**
1111** If the key is not an INTEGER PRIMARY KEY, then create a unique
1112** index for the key. No index is created for INTEGER PRIMARY KEYs.
1113*/
drh205f48e2004-11-05 00:43:11 +00001114void sqlite3AddPrimaryKey(
1115 Parse *pParse, /* Parsing context */
1116 ExprList *pList, /* List of field names to be indexed */
1117 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001118 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1119 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001120){
drh4a324312001-12-21 14:30:42 +00001121 Table *pTab = pParse->pNewTable;
1122 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001123 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001124 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001125 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001126 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001127 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001128 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001129 }
drh7d10d5a2008-08-20 16:35:10 +00001130 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001131 if( pList==0 ){
1132 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001133 pTab->aCol[iCol].isPrimKey = 1;
1134 }else{
danielk19770202b292004-06-09 09:55:16 +00001135 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001136 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001137 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1138 break;
1139 }
drh78100cc2003-08-23 22:40:53 +00001140 }
drh6e4fc2c2005-09-15 21:24:51 +00001141 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001142 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001143 }
drh4a324312001-12-21 14:30:42 +00001144 }
danielk19770202b292004-06-09 09:55:16 +00001145 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001146 }
1147 if( iCol>=0 && iCol<pTab->nCol ){
1148 zType = pTab->aCol[iCol].zType;
1149 }
drhfdd6e852005-12-16 01:06:16 +00001150 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1151 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001152 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001153 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001154 assert( autoInc==0 || autoInc==1 );
1155 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001156 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001157#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001158 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1159 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001160#endif
drh4a324312001-12-21 14:30:42 +00001161 }else{
drh4d91a702006-01-04 15:54:36 +00001162 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001163 pList = 0;
drh4a324312001-12-21 14:30:42 +00001164 }
drhe0194f22003-02-26 13:52:51 +00001165
1166primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001167 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001168 return;
drh4a324312001-12-21 14:30:42 +00001169}
1170
1171/*
drhffe07b22005-11-03 00:41:17 +00001172** Add a new CHECK constraint to the table currently under construction.
1173*/
1174void sqlite3AddCheckConstraint(
1175 Parse *pParse, /* Parsing context */
1176 Expr *pCheckExpr /* The check expression */
1177){
drh633e6d52008-07-28 19:34:53 +00001178 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001179#ifndef SQLITE_OMIT_CHECK
1180 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001181 if( pTab && !IN_DECLARE_VTAB ){
drhffe07b22005-11-03 00:41:17 +00001182 /* The CHECK expression must be duplicated so that tokens refer
1183 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1184 ** statement */
drh17435752007-08-16 04:30:38 +00001185 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
danielk19776ab3a2e2009-02-19 14:39:25 +00001186 sqlite3ExprDup(db, pCheckExpr, 0));
drhffe07b22005-11-03 00:41:17 +00001187 }
1188#endif
drh633e6d52008-07-28 19:34:53 +00001189 sqlite3ExprDelete(db, pCheckExpr);
drhffe07b22005-11-03 00:41:17 +00001190}
1191
1192/*
drhd3d39e92004-05-20 22:16:29 +00001193** Set the collation function of the most recently parsed table column
1194** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001195*/
danielk197739002502007-11-12 09:50:26 +00001196void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001197 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001198 int i;
danielk197739002502007-11-12 09:50:26 +00001199 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001200 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001201
danielk1977b8cbb872006-06-19 05:33:45 +00001202 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001203 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001204 db = pParse->db;
1205 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001206 if( !zColl ) return;
1207
drhc4a64fa2009-05-11 20:53:28 +00001208 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001209 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001210 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001211
1212 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1213 ** then an index may have been created on this column before the
1214 ** collation type was added. Correct this if it is the case.
1215 */
1216 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1217 assert( pIdx->nColumn==1 );
1218 if( pIdx->aiColumn[0]==i ){
1219 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001220 }
1221 }
danielk197739002502007-11-12 09:50:26 +00001222 }else{
drh633e6d52008-07-28 19:34:53 +00001223 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001224 }
danielk19777cedc8d2004-06-10 10:50:08 +00001225}
1226
danielk1977466be562004-06-10 02:16:01 +00001227/*
1228** This function returns the collation sequence for database native text
1229** encoding identified by the string zName, length nName.
1230**
1231** If the requested collation sequence is not available, or not available
1232** in the database native encoding, the collation factory is invoked to
1233** request it. If the collation factory does not supply such a sequence,
1234** and the sequence is available in another text encoding, then that is
1235** returned instead.
1236**
1237** If no versions of the requested collations sequence are available, or
1238** another error occurs, NULL is returned and an error message written into
1239** pParse.
drha34001c2007-02-02 12:44:37 +00001240**
1241** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1242** invokes the collation factory if the named collation cannot be found
1243** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001244**
1245** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001246*/
drhc4a64fa2009-05-11 20:53:28 +00001247CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001248 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001249 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001250 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001251 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001252
drhc4a64fa2009-05-11 20:53:28 +00001253 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001254 if( !initbusy && (!pColl || !pColl->xCmp) ){
drhc4a64fa2009-05-11 20:53:28 +00001255 pColl = sqlite3GetCollSeq(db, pColl, zName);
danielk19774dade032005-05-25 10:45:10 +00001256 if( !pColl ){
drhc4a64fa2009-05-11 20:53:28 +00001257 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
danielk19774dade032005-05-25 10:45:10 +00001258 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001259 }
1260 }
1261
danielk19770202b292004-06-09 09:55:16 +00001262 return pColl;
1263}
1264
1265
drh8e2ca022002-06-17 17:07:19 +00001266/*
drh3f7d4e42004-07-24 14:35:58 +00001267** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001268**
1269** The schema cookie is used to determine when the schema for the
1270** database changes. After each schema change, the cookie value
1271** changes. When a process first reads the schema it records the
1272** cookie. Thereafter, whenever it goes to access the database,
1273** it checks the cookie to make sure the schema has not changed
1274** since it was last read.
1275**
1276** This plan is not completely bullet-proof. It is possible for
1277** the schema to change multiple times and for the cookie to be
1278** set back to prior value. But schema changes are infrequent
1279** and the probability of hitting the same cookie value is only
1280** 1 chance in 2^32. So we're safe enough.
1281*/
drh9cbf3422008-01-17 16:22:13 +00001282void sqlite3ChangeCookie(Parse *pParse, int iDb){
1283 int r1 = sqlite3GetTempReg(pParse);
1284 sqlite3 *db = pParse->db;
1285 Vdbe *v = pParse->pVdbe;
1286 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
1287 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
1288 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001289}
1290
1291/*
drh969fa7c2002-02-18 18:30:32 +00001292** Measure the number of characters needed to output the given
1293** identifier. The number returned includes any quotes used
1294** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001295**
1296** The estimate is conservative. It might be larger that what is
1297** really needed.
drh969fa7c2002-02-18 18:30:32 +00001298*/
1299static int identLength(const char *z){
1300 int n;
drh17f71932002-02-21 12:01:27 +00001301 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001302 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001303 }
drh234c39d2004-07-24 03:30:47 +00001304 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001305}
1306
1307/*
danielk19771b870de2009-03-14 08:37:23 +00001308** The first parameter is a pointer to an output buffer. The second
1309** parameter is a pointer to an integer that contains the offset at
1310** which to write into the output buffer. This function copies the
1311** nul-terminated string pointed to by the third parameter, zSignedIdent,
1312** to the specified offset in the buffer and updates *pIdx to refer
1313** to the first byte after the last byte written before returning.
1314**
1315** If the string zSignedIdent consists entirely of alpha-numeric
1316** characters, does not begin with a digit and is not an SQL keyword,
1317** then it is copied to the output buffer exactly as it is. Otherwise,
1318** it is quoted using double-quotes.
1319*/
drhc4a64fa2009-05-11 20:53:28 +00001320static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001321 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001322 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001323 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001324
drh17f71932002-02-21 12:01:27 +00001325 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001326 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001327 }
danielk19771b870de2009-03-14 08:37:23 +00001328 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1329 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001330 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001331 }
1332
drh234c39d2004-07-24 03:30:47 +00001333 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001334 for(j=0; zIdent[j]; j++){
1335 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001336 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001337 }
drh234c39d2004-07-24 03:30:47 +00001338 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001339 z[i] = 0;
1340 *pIdx = i;
1341}
1342
1343/*
1344** Generate a CREATE TABLE statement appropriate for the given
1345** table. Memory to hold the text of the statement is obtained
1346** from sqliteMalloc() and must be freed by the calling function.
1347*/
drh1d34fde2009-02-03 15:50:33 +00001348static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001349 int i, k, n;
1350 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001351 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001352 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001353 n = 0;
drh234c39d2004-07-24 03:30:47 +00001354 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001355 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001356 }
1357 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001358 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001359 zSep = "";
1360 zSep2 = ",";
1361 zEnd = ")";
1362 }else{
1363 zSep = "\n ";
1364 zSep2 = ",\n ";
1365 zEnd = "\n)";
1366 }
drhe0bc4042002-06-25 01:09:11 +00001367 n += 35 + 6*p->nCol;
drhe5ae5732008-06-15 02:51:47 +00001368 zStmt = sqlite3Malloc( n );
drh820a9062008-01-31 13:35:48 +00001369 if( zStmt==0 ){
1370 db->mallocFailed = 1;
1371 return 0;
1372 }
drhbdb339f2009-02-02 18:03:21 +00001373 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001374 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001375 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001376 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001377 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001378 static const char * const azType[] = {
1379 /* SQLITE_AFF_TEXT */ " TEXT",
1380 /* SQLITE_AFF_NONE */ "",
1381 /* SQLITE_AFF_NUMERIC */ " NUM",
1382 /* SQLITE_AFF_INTEGER */ " INT",
1383 /* SQLITE_AFF_REAL */ " REAL"
1384 };
1385 int len;
1386 const char *zType;
1387
drh5bb3eb92007-05-04 13:15:55 +00001388 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001389 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001390 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001391 identPut(zStmt, &k, pCol->zName);
1392 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1393 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
1394 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1395 testcase( pCol->affinity==SQLITE_AFF_NONE );
1396 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1397 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1398 testcase( pCol->affinity==SQLITE_AFF_REAL );
1399
1400 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1401 len = sqlite3Strlen30(zType);
1402#ifndef NDEBUG
1403 if( pCol->affinity!=SQLITE_AFF_NONE ){
1404 Token typeToken;
1405 typeToken.z = (u8*)zType;
1406 typeToken.n = len;
1407 assert( pCol->affinity==sqlite3AffinityType(&typeToken) );
danielk1977517eb642004-06-07 10:00:31 +00001408 }
drhc4a64fa2009-05-11 20:53:28 +00001409#endif
1410 memcpy(&zStmt[k], zType, len);
1411 k += len;
1412 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001413 }
drh5bb3eb92007-05-04 13:15:55 +00001414 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001415 return zStmt;
1416}
1417
1418/*
drh75897232000-05-29 14:26:00 +00001419** This routine is called to report the final ")" that terminates
1420** a CREATE TABLE statement.
1421**
drhf57b3392001-10-08 13:22:32 +00001422** The table structure that other action routines have been building
1423** is added to the internal hash tables, assuming no errors have
1424** occurred.
drh75897232000-05-29 14:26:00 +00001425**
drh1d85d932004-02-14 23:05:52 +00001426** An entry for the table is made in the master table on disk, unless
1427** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001428** it means we are reading the sqlite_master table because we just
1429** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001430** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001431** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001432**
1433** If the pSelect argument is not NULL, it means that this routine
1434** was called to create a table generated from a
1435** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1436** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001437*/
danielk197719a8e7e2005-03-17 05:03:38 +00001438void sqlite3EndTable(
1439 Parse *pParse, /* Parse context */
1440 Token *pCons, /* The ',' token after the last column defn. */
1441 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1442 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1443){
drh75897232000-05-29 14:26:00 +00001444 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001445 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001446 int iDb;
drh75897232000-05-29 14:26:00 +00001447
drh04491712009-05-13 17:21:13 +00001448 if( (pEnd==0 && pSelect==0) || NEVER(pParse->nErr) || db->mallocFailed ) {
danielk1977261919c2005-12-06 12:52:59 +00001449 return;
1450 }
drh28037572000-08-02 13:47:41 +00001451 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001452 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001453
danielk1977517eb642004-06-07 10:00:31 +00001454 assert( !db->init.busy || !pSelect );
1455
drhb9bb7c12006-06-11 23:41:55 +00001456 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001457
drhffe07b22005-11-03 00:41:17 +00001458#ifndef SQLITE_OMIT_CHECK
1459 /* Resolve names in all CHECK constraint expressions.
1460 */
1461 if( p->pCheck ){
1462 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1463 NameContext sNC; /* Name context for pParse->pNewTable */
1464
1465 memset(&sNC, 0, sizeof(sNC));
1466 memset(&sSrc, 0, sizeof(sSrc));
1467 sSrc.nSrc = 1;
1468 sSrc.a[0].zName = p->zName;
1469 sSrc.a[0].pTab = p;
1470 sSrc.a[0].iCursor = -1;
1471 sNC.pParse = pParse;
1472 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001473 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001474 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001475 return;
1476 }
1477 }
1478#endif /* !defined(SQLITE_OMIT_CHECK) */
1479
drh1d85d932004-02-14 23:05:52 +00001480 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001481 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1482 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001483 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001484 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001485 */
drh1d85d932004-02-14 23:05:52 +00001486 if( db->init.busy ){
1487 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001488 }
1489
drhe3c41372001-09-17 20:25:58 +00001490 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001491 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001492 **
drhe0bc4042002-06-25 01:09:11 +00001493 ** If this is a TEMPORARY table, write the entry into the auxiliary
1494 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001495 */
drh1d85d932004-02-14 23:05:52 +00001496 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001497 int n;
drhd8bc7082000-06-07 23:51:50 +00001498 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001499 char *zType; /* "view" or "table" */
1500 char *zType2; /* "VIEW" or "TABLE" */
1501 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001502
danielk19774adee202004-05-08 08:23:19 +00001503 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001504 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001505
drh66a51672008-01-03 00:01:23 +00001506 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001507
drh0fa991b2009-03-21 16:19:26 +00001508 /*
1509 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001510 */
drh4ff6dfa2002-03-03 23:06:00 +00001511 if( p->pSelect==0 ){
1512 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001513 zType = "table";
1514 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001515#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001516 }else{
1517 /* A view */
drh4794f732004-11-05 17:17:50 +00001518 zType = "view";
1519 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001520#endif
drh4ff6dfa2002-03-03 23:06:00 +00001521 }
danielk1977517eb642004-06-07 10:00:31 +00001522
danielk1977517eb642004-06-07 10:00:31 +00001523 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1524 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001525 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001526 **
1527 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1528 ** suitable state to query for the column names and types to be used
1529 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001530 **
1531 ** A shared-cache write-lock is not required to write to the new table,
1532 ** as a schema-lock must have already been obtained to create it. Since
1533 ** a schema-lock excludes all other database users, the write-lock would
1534 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001535 */
1536 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001537 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001538 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001539
danielk19776ab3a2e2009-02-19 14:39:25 +00001540 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001541 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001542 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001543 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001544 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001545 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001546 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001547 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001548 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001549 if( pSelTab==0 ) return;
1550 assert( p->aCol==0 );
1551 p->nCol = pSelTab->nCol;
1552 p->aCol = pSelTab->aCol;
1553 pSelTab->nCol = 0;
1554 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001555 sqlite3DeleteTable(pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001556 }
1557 }
drh4794f732004-11-05 17:17:50 +00001558
drh4794f732004-11-05 17:17:50 +00001559 /* Compute the complete text of the CREATE statement */
1560 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001561 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001562 }else{
drh1bd10f82008-12-10 21:19:56 +00001563 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001564 zStmt = sqlite3MPrintf(db,
1565 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1566 );
drh4794f732004-11-05 17:17:50 +00001567 }
1568
1569 /* A slot for the record has already been allocated in the
1570 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001571 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001572 */
1573 sqlite3NestedParse(pParse,
1574 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001575 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1576 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001577 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001578 zType,
1579 p->zName,
1580 p->zName,
drhb7654112008-01-12 12:48:07 +00001581 pParse->regRoot,
1582 zStmt,
1583 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001584 );
drh633e6d52008-07-28 19:34:53 +00001585 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001586 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001587
1588#ifndef SQLITE_OMIT_AUTOINCREMENT
1589 /* Check to see if we need to create an sqlite_sequence table for
1590 ** keeping track of autoincrement keys.
1591 */
drh7d10d5a2008-08-20 16:35:10 +00001592 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001593 Db *pDb = &db->aDb[iDb];
1594 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001595 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001596 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1597 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001598 );
1599 }
1600 }
1601#endif
drh4794f732004-11-05 17:17:50 +00001602
1603 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001604 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1605 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001606 }
drh17e9e292003-02-01 13:53:28 +00001607
drh2958a4e2004-11-12 03:56:15 +00001608
drh17e9e292003-02-01 13:53:28 +00001609 /* Add the table to the in-memory representation of the database.
1610 */
drh768578e2009-05-12 00:40:12 +00001611 if( db->init.busy && ALWAYS(pParse->nErr==0) ){
drh17e9e292003-02-01 13:53:28 +00001612 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001613 Schema *pSchema = p->pSchema;
drhea678832008-12-10 19:26:22 +00001614 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001615 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001616 if( pOld ){
1617 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001618 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001619 return;
1620 }
drh17e9e292003-02-01 13:53:28 +00001621 pParse->pNewTable = 0;
1622 db->nTable++;
1623 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001624
1625#ifndef SQLITE_OMIT_ALTERTABLE
1626 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001627 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001628 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001629 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001630 if( pCons->z==0 ){
1631 pCons = pEnd;
1632 }
drh1bd10f82008-12-10 21:19:56 +00001633 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001634 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001635 }
1636#endif
drh17e9e292003-02-01 13:53:28 +00001637 }
drh75897232000-05-29 14:26:00 +00001638}
1639
drhb7f91642004-10-31 02:22:47 +00001640#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001641/*
drha76b5df2002-02-23 02:32:10 +00001642** The parser calls this routine in order to create a new VIEW
1643*/
danielk19774adee202004-05-08 08:23:19 +00001644void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001645 Parse *pParse, /* The parsing context */
1646 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001647 Token *pName1, /* The token that holds the name of the view */
1648 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001649 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001650 int isTemp, /* TRUE for a TEMPORARY view */
1651 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001652){
drha76b5df2002-02-23 02:32:10 +00001653 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001654 int n;
drh4c755c02004-08-08 20:22:17 +00001655 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001656 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001657 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001658 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001659 int iDb;
drh17435752007-08-16 04:30:38 +00001660 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001661
drh7c3d64f2005-06-06 15:32:08 +00001662 if( pParse->nVar>0 ){
1663 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001664 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001665 return;
1666 }
drhfdd48a72006-09-11 23:45:48 +00001667 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001668 p = pParse->pNewTable;
drh768578e2009-05-12 00:40:12 +00001669 if( p==0 || NEVER(pParse->nErr>0) ){
drh633e6d52008-07-28 19:34:53 +00001670 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001671 return;
1672 }
danielk1977ef2cb632004-05-29 02:37:19 +00001673 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001674 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001675 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001676 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001677 ){
drh633e6d52008-07-28 19:34:53 +00001678 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001679 return;
1680 }
drh174b6192002-12-03 02:22:52 +00001681
drh4b59ab52002-08-24 18:24:51 +00001682 /* Make a copy of the entire SELECT statement that defines the view.
1683 ** This will force all the Expr.token.z values to be dynamically
1684 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001685 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001686 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001687 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001688 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001689 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001690 return;
1691 }
drh17435752007-08-16 04:30:38 +00001692 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001693 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001694 }
drh4b59ab52002-08-24 18:24:51 +00001695
1696 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1697 ** the end.
1698 */
drha76b5df2002-02-23 02:32:10 +00001699 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001700 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001701 sEnd.z += sEnd.n;
1702 }
1703 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001704 n = (int)(sEnd.z - pBegin->z);
drh4c755c02004-08-08 20:22:17 +00001705 z = (const unsigned char*)pBegin->z;
drh768578e2009-05-12 00:40:12 +00001706 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001707 sEnd.z = &z[n-1];
1708 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001709
danielk19774adee202004-05-08 08:23:19 +00001710 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001711 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001712 return;
drh417be792002-03-03 18:59:40 +00001713}
drhb7f91642004-10-31 02:22:47 +00001714#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001715
danielk1977fe3fcbe22006-06-12 12:08:45 +00001716#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001717/*
1718** The Table structure pTable is really a VIEW. Fill in the names of
1719** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001720** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001721*/
danielk19774adee202004-05-08 08:23:19 +00001722int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001723 Table *pSelTab; /* A fake table from which we get the result set */
1724 Select *pSel; /* Copy of the SELECT that implements the view */
1725 int nErr = 0; /* Number of errors encountered */
1726 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001727 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001728 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001729
1730 assert( pTable );
1731
danielk1977fe3fcbe22006-06-12 12:08:45 +00001732#ifndef SQLITE_OMIT_VIRTUALTABLE
1733 if( sqlite3VtabCallConnect(pParse, pTable) ){
1734 return SQLITE_ERROR;
1735 }
drh4cbdda92006-06-14 19:00:20 +00001736 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001737#endif
1738
1739#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001740 /* A positive nCol means the columns names for this view are
1741 ** already known.
1742 */
1743 if( pTable->nCol>0 ) return 0;
1744
1745 /* A negative nCol is a special marker meaning that we are currently
1746 ** trying to compute the column names. If we enter this routine with
1747 ** a negative nCol, it means two or more views form a loop, like this:
1748 **
1749 ** CREATE VIEW one AS SELECT * FROM two;
1750 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001751 **
drh768578e2009-05-12 00:40:12 +00001752 ** Actually, the error above is now caught prior to reaching this point.
1753 ** But the following test is still important as it does come up
1754 ** in the following:
1755 **
1756 ** CREATE TABLE main.ex1(a);
1757 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1758 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001759 */
1760 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001761 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001762 return 1;
1763 }
drh85c23c62005-08-20 03:03:04 +00001764 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001765
1766 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001767 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1768 ** "*" elements in the results set of the view and will assign cursors
1769 ** to the elements of the FROM clause. But we do not want these changes
1770 ** to be permanent. So the computation is done on a copy of the SELECT
1771 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001772 */
drh9b3187e2005-01-18 14:45:47 +00001773 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001774 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001775 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001776 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001777 n = pParse->nTab;
1778 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1779 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001780 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001781#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001782 xAuth = db->xAuth;
1783 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001784 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001785 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001786#else
drh7d10d5a2008-08-20 16:35:10 +00001787 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001788#endif
drhd9da78a2009-03-24 15:08:09 +00001789 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001790 pParse->nTab = n;
1791 if( pSelTab ){
1792 assert( pTable->aCol==0 );
1793 pTable->nCol = pSelTab->nCol;
1794 pTable->aCol = pSelTab->aCol;
1795 pSelTab->nCol = 0;
1796 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001797 sqlite3DeleteTable(pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001798 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001799 }else{
1800 pTable->nCol = 0;
1801 nErr++;
1802 }
drh633e6d52008-07-28 19:34:53 +00001803 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001804 } else {
drh417be792002-03-03 18:59:40 +00001805 nErr++;
1806 }
drhb7f91642004-10-31 02:22:47 +00001807#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001808 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001809}
1810#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001811
drhb7f91642004-10-31 02:22:47 +00001812#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001813/*
drh8bf8dc92003-05-17 17:35:10 +00001814** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001815*/
drh9bb575f2004-09-06 17:24:11 +00001816static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001817 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001818 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001819 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001820 Table *pTab = sqliteHashData(i);
1821 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001822 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001823 }
1824 }
drh8bf8dc92003-05-17 17:35:10 +00001825 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001826}
drhb7f91642004-10-31 02:22:47 +00001827#else
1828# define sqliteViewResetAll(A,B)
1829#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001830
drh75897232000-05-29 14:26:00 +00001831/*
danielk1977a0bf2652004-11-04 14:30:04 +00001832** This function is called by the VDBE to adjust the internal schema
1833** used by SQLite when the btree layer moves a table root page. The
1834** root-page of a table or index in database iDb has changed from iFrom
1835** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001836**
1837** Ticket #1728: The symbol table might still contain information
1838** on tables and/or indices that are the process of being deleted.
1839** If you are unlucky, one of those deleted indices or tables might
1840** have the same rootpage number as the real table or index that is
1841** being moved. So we cannot stop searching after the first match
1842** because the first match might be for one of the deleted indices
1843** or tables and not the table/index that is actually being moved.
1844** We must continue looping until all tables and indices with
1845** rootpage==iFrom have been converted to have a rootpage of iTo
1846** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001847*/
1848#ifndef SQLITE_OMIT_AUTOVACUUM
1849void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1850 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001851 Hash *pHash;
1852
1853 pHash = &pDb->pSchema->tblHash;
1854 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001855 Table *pTab = sqliteHashData(pElem);
1856 if( pTab->tnum==iFrom ){
1857 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001858 }
1859 }
danielk1977da184232006-01-05 11:34:32 +00001860 pHash = &pDb->pSchema->idxHash;
1861 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001862 Index *pIdx = sqliteHashData(pElem);
1863 if( pIdx->tnum==iFrom ){
1864 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001865 }
1866 }
danielk1977a0bf2652004-11-04 14:30:04 +00001867}
1868#endif
1869
1870/*
1871** Write code to erase the table with root-page iTable from database iDb.
1872** Also write code to modify the sqlite_master table and internal schema
1873** if a root-page of another table is moved by the btree-layer whilst
1874** erasing iTable (this can happen with an auto-vacuum database).
1875*/
drh4e0cff62004-11-05 05:10:28 +00001876static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1877 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001878 int r1 = sqlite3GetTempReg(pParse);
1879 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
drh40e016e2004-11-04 14:47:11 +00001880#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001881 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001882 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001883 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001884 ** reflect this.
1885 **
drh0fa991b2009-03-21 16:19:26 +00001886 ** The "#NNN" in the SQL is a special constant that means whatever value
1887 ** is in register NNN. See sqlite3RegisterExpr().
drh4e0cff62004-11-05 05:10:28 +00001888 */
danielk197763e3e9f2004-11-05 09:19:27 +00001889 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001890 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1891 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001892#endif
drhb7654112008-01-12 12:48:07 +00001893 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001894}
1895
1896/*
1897** Write VDBE code to erase table pTab and all associated indices on disk.
1898** Code to update the sqlite_master tables and internal schema definitions
1899** in case a root-page belonging to another table is moved by the btree layer
1900** is also added (this can happen with an auto-vacuum database).
1901*/
drh4e0cff62004-11-05 05:10:28 +00001902static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001903#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001904 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001905 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1906 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001907 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001908 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001909 }
1910#else
1911 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1912 ** is not defined), then it is important to call OP_Destroy on the
1913 ** table and index root-pages in order, starting with the numerically
1914 ** largest root-page number. This guarantees that none of the root-pages
1915 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1916 ** following were coded:
1917 **
1918 ** OP_Destroy 4 0
1919 ** ...
1920 ** OP_Destroy 5 0
1921 **
1922 ** and root page 5 happened to be the largest root-page number in the
1923 ** database, then root page 5 would be moved to page 4 by the
1924 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1925 ** a free-list page.
1926 */
1927 int iTab = pTab->tnum;
1928 int iDestroyed = 0;
1929
1930 while( 1 ){
1931 Index *pIdx;
1932 int iLargest = 0;
1933
1934 if( iDestroyed==0 || iTab<iDestroyed ){
1935 iLargest = iTab;
1936 }
1937 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1938 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001939 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001940 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1941 iLargest = iIdx;
1942 }
1943 }
danielk1977da184232006-01-05 11:34:32 +00001944 if( iLargest==0 ){
1945 return;
1946 }else{
1947 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1948 destroyRootPage(pParse, iLargest, iDb);
1949 iDestroyed = iLargest;
1950 }
danielk1977a0bf2652004-11-04 14:30:04 +00001951 }
1952#endif
1953}
1954
1955/*
drh75897232000-05-29 14:26:00 +00001956** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001957** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001958*/
drha0733842005-12-29 01:11:36 +00001959void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001960 Table *pTab;
drh75897232000-05-29 14:26:00 +00001961 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001962 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001963 int iDb;
drh75897232000-05-29 14:26:00 +00001964
drh04491712009-05-13 17:21:13 +00001965 if( NEVER(pParse->nErr) || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001966 goto exit_drop_table;
1967 }
danielk1977a8858102004-05-28 12:11:21 +00001968 assert( pName->nSrc==1 );
drhca424112008-01-25 15:04:48 +00001969 pTab = sqlite3LocateTable(pParse, isView,
1970 pName->a[0].zName, pName->a[0].zDatabase);
danielk1977a8858102004-05-28 12:11:21 +00001971
drha0733842005-12-29 01:11:36 +00001972 if( pTab==0 ){
1973 if( noErr ){
1974 sqlite3ErrorClear(pParse);
1975 }
1976 goto exit_drop_table;
1977 }
danielk1977da184232006-01-05 11:34:32 +00001978 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001979 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00001980
1981 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1982 ** it is initialized.
1983 */
1984 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1985 goto exit_drop_table;
1986 }
drhe5f9c642003-01-13 23:27:31 +00001987#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001988 {
1989 int code;
danielk1977da184232006-01-05 11:34:32 +00001990 const char *zTab = SCHEMA_TABLE(iDb);
1991 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00001992 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00001993 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001994 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001995 }
drhe5f9c642003-01-13 23:27:31 +00001996 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001997 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001998 code = SQLITE_DROP_TEMP_VIEW;
1999 }else{
2000 code = SQLITE_DROP_VIEW;
2001 }
danielk19774b2688a2006-06-20 11:01:07 +00002002#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002003 }else if( IsVirtual(pTab) ){
2004 code = SQLITE_DROP_VTABLE;
2005 zArg2 = pTab->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002006#endif
drhe5f9c642003-01-13 23:27:31 +00002007 }else{
danielk197753c0f742005-03-29 03:10:59 +00002008 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002009 code = SQLITE_DROP_TEMP_TABLE;
2010 }else{
2011 code = SQLITE_DROP_TABLE;
2012 }
2013 }
danielk1977f1a381e2006-06-16 08:01:02 +00002014 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002015 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002016 }
danielk1977a8858102004-05-28 12:11:21 +00002017 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2018 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002019 }
drhe5f9c642003-01-13 23:27:31 +00002020 }
2021#endif
drhc456e572008-08-11 18:44:58 +00002022 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002023 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002024 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002025 }
danielk1977576ec6b2005-01-21 11:55:25 +00002026
2027#ifndef SQLITE_OMIT_VIEW
2028 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2029 ** on a table.
2030 */
danielk1977a8858102004-05-28 12:11:21 +00002031 if( isView && pTab->pSelect==0 ){
2032 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2033 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002034 }
danielk1977a8858102004-05-28 12:11:21 +00002035 if( !isView && pTab->pSelect ){
2036 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2037 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002038 }
danielk1977576ec6b2005-01-21 11:55:25 +00002039#endif
drh75897232000-05-29 14:26:00 +00002040
drh1ccde152000-06-17 13:12:39 +00002041 /* Generate code to remove the table from the master table
2042 ** on disk.
2043 */
danielk19774adee202004-05-08 08:23:19 +00002044 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002045 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002046 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002047 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002048 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002049
danielk197720b1eaf2006-07-26 16:22:14 +00002050#ifndef SQLITE_OMIT_VIRTUALTABLE
2051 if( IsVirtual(pTab) ){
drh768578e2009-05-12 00:40:12 +00002052 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002053 }
2054#endif
2055
danielk19778e227872004-06-07 07:52:17 +00002056 /* Drop all triggers associated with the table being dropped. Code
2057 ** is generated to remove entries from sqlite_master and/or
2058 ** sqlite_temp_master if required.
2059 */
danielk19772f886d12009-02-28 10:47:41 +00002060 pTrigger = sqlite3TriggerList(pParse, pTab);
drhe0bc4042002-06-25 01:09:11 +00002061 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002062 assert( pTrigger->pSchema==pTab->pSchema ||
2063 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002064 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002065 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002066 }
drh8bf8dc92003-05-17 17:35:10 +00002067
danielk19774d36b812004-11-19 07:07:30 +00002068#ifndef SQLITE_OMIT_AUTOINCREMENT
2069 /* Remove any entries of the sqlite_sequence table associated with
2070 ** the table being dropped. This is done before the table is dropped
2071 ** at the btree level, in case the sqlite_sequence table needs to
2072 ** move as a result of the drop (can happen in auto-vacuum mode).
2073 */
drh7d10d5a2008-08-20 16:35:10 +00002074 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002075 sqlite3NestedParse(pParse,
2076 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2077 pDb->zName, pTab->zName
2078 );
2079 }
2080#endif
2081
danielk19778e227872004-06-07 07:52:17 +00002082 /* Drop all SQLITE_MASTER table and index entries that refer to the
2083 ** table. The program name loops through the master table and deletes
2084 ** every row that refers to a table of the same name as the one being
2085 ** dropped. Triggers are handled seperately because a trigger can be
2086 ** created in the temp database that refers to a table in another
2087 ** database.
2088 */
drhf1974842004-11-05 03:56:00 +00002089 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002090 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002091 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002092
2093 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2094 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2095 sqlite3NestedParse(pParse,
2096 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2097 );
2098 }
2099
danielk19774b2688a2006-06-20 11:01:07 +00002100 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002101 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002102 }
drh2958a4e2004-11-12 03:56:15 +00002103
danielk1977a21c6b62005-01-24 10:25:59 +00002104 /* Remove the table entry from SQLite's internal schema and modify
2105 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002106 */
drh4cbdda92006-06-14 19:00:20 +00002107 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002108 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002109 }
drh66a51672008-01-03 00:01:23 +00002110 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002111 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002112 }
drhd24cc422003-03-27 12:51:24 +00002113 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002114
2115exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002116 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002117}
2118
2119/*
drhc2eef3b2002-08-31 18:53:06 +00002120** This routine is called to create a new foreign key on the table
2121** currently under construction. pFromCol determines which columns
2122** in the current table point to the foreign key. If pFromCol==0 then
2123** connect the key to the last column inserted. pTo is the name of
2124** the table referred to. pToCol is a list of tables in the other
2125** pTo table that the foreign key points to. flags contains all
2126** information about the conflict resolution algorithms specified
2127** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2128**
2129** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002130** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002131**
2132** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002133** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002134*/
danielk19774adee202004-05-08 08:23:19 +00002135void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002136 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002137 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002138 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002139 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002140 int flags /* Conflict resolution algorithms. */
2141){
danielk197718576932008-08-06 13:47:40 +00002142 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002143#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002144 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00002145 Table *p = pParse->pNewTable;
2146 int nByte;
2147 int i;
2148 int nCol;
2149 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002150
2151 assert( pTo!=0 );
drhd3001712009-05-12 17:46:53 +00002152 if( p==0 || NEVER(pParse->nErr) || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002153 if( pFromCol==0 ){
2154 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002155 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002156 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002157 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002158 " should reference only one column of table %T",
2159 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002160 goto fk_end;
2161 }
2162 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002163 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002164 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002165 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002166 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002167 goto fk_end;
2168 }else{
danielk19770202b292004-06-09 09:55:16 +00002169 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002170 }
drhe61922a2009-05-02 13:29:37 +00002171 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002172 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002173 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002174 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002175 }
2176 }
drh633e6d52008-07-28 19:34:53 +00002177 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002178 if( pFKey==0 ){
2179 goto fk_end;
2180 }
drhc2eef3b2002-08-31 18:53:06 +00002181 pFKey->pFrom = p;
2182 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002183 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002184 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002185 memcpy(z, pTo->z, pTo->n);
2186 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002187 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002188 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002189 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002190 if( pFromCol==0 ){
2191 pFKey->aCol[0].iFrom = p->nCol-1;
2192 }else{
2193 for(i=0; i<nCol; i++){
2194 int j;
2195 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002196 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002197 pFKey->aCol[i].iFrom = j;
2198 break;
2199 }
2200 }
2201 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002202 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002203 "unknown column \"%s\" in foreign key definition",
2204 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002205 goto fk_end;
2206 }
2207 }
2208 }
2209 if( pToCol ){
2210 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002211 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002212 pFKey->aCol[i].zCol = z;
2213 memcpy(z, pToCol->a[i].zName, n);
2214 z[n] = 0;
2215 z += n+1;
2216 }
2217 }
2218 pFKey->isDeferred = 0;
drh1bd10f82008-12-10 21:19:56 +00002219 pFKey->deleteConf = (u8)(flags & 0xff);
2220 pFKey->updateConf = (u8)((flags >> 8 ) & 0xff);
2221 pFKey->insertConf = (u8)((flags >> 16 ) & 0xff);
drhc2eef3b2002-08-31 18:53:06 +00002222
2223 /* Link the foreign key to the table as the last step.
2224 */
2225 p->pFKey = pFKey;
2226 pFKey = 0;
2227
2228fk_end:
drh633e6d52008-07-28 19:34:53 +00002229 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002230#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002231 sqlite3ExprListDelete(db, pFromCol);
2232 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002233}
2234
2235/*
2236** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2237** clause is seen as part of a foreign key definition. The isDeferred
2238** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2239** The behavior of the most recently created foreign key is adjusted
2240** accordingly.
2241*/
danielk19774adee202004-05-08 08:23:19 +00002242void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002243#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002244 Table *pTab;
2245 FKey *pFKey;
2246 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh1bd10f82008-12-10 21:19:56 +00002247 assert( isDeferred==0 || isDeferred==1 );
2248 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002249#endif
drhc2eef3b2002-08-31 18:53:06 +00002250}
2251
2252/*
drh063336a2004-11-05 20:58:39 +00002253** Generate code that will erase and refill index *pIdx. This is
2254** used to initialize a newly created index or to recompute the
2255** content of an index in response to a REINDEX command.
2256**
2257** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002258** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002259** root page number of the index. If memRootPage is negative, then
2260** the index already exists and must be cleared before being refilled and
2261** the root page number of the index is taken from pIndex->tnum.
2262*/
2263static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2264 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002265 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2266 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drh063336a2004-11-05 20:58:39 +00002267 int addr1; /* Address of top of loop */
2268 int tnum; /* Root page of index */
2269 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002270 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002271 int regIdxKey; /* Registers containing the index key */
2272 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002273 sqlite3 *db = pParse->db; /* The database connection */
2274 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002275
danielk19771d54df82004-11-23 15:41:16 +00002276#ifndef SQLITE_OMIT_AUTHORIZATION
2277 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002278 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002279 return;
2280 }
2281#endif
2282
danielk1977c00da102006-01-07 13:21:04 +00002283 /* Require a write-lock on the table to perform this operation */
2284 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2285
drh063336a2004-11-05 20:58:39 +00002286 v = sqlite3GetVdbe(pParse);
2287 if( v==0 ) return;
2288 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002289 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002290 }else{
2291 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002292 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002293 }
danielk1977b3bf5562006-01-10 17:58:23 +00002294 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002295 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002296 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002297 if( memRootPage>=0 ){
2298 sqlite3VdbeChangeP5(v, 1);
2299 }
danielk1977c00da102006-01-07 13:21:04 +00002300 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002301 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002302 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002303 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002304 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002305 const int regRowid = regIdxKey + pIndex->nColumn;
2306 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2307 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002308
danielk1977de630352009-05-04 11:42:29 +00002309 /* The registers accessed by the OP_IsUnique opcode were allocated
2310 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2311 ** call above. Just before that function was freed they were released
2312 ** (made available to the compiler for reuse) using
2313 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2314 ** opcode use the values stored within seems dangerous. However, since
2315 ** we can be sure that no other temp registers have been allocated
2316 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2317 */
2318 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
drh66a51672008-01-03 00:01:23 +00002319 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
2320 "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002321 }
drh2d401ab2008-01-10 23:50:11 +00002322 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
danielk1977de630352009-05-04 11:42:29 +00002323 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002324 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002325 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002326 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002327 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2328 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002329}
2330
2331/*
drh23bf66d2004-12-14 03:34:34 +00002332** Create a new index for an SQL table. pName1.pName2 is the name of the index
2333** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002334** be NULL for a primary key or an index that is created to satisfy a
2335** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002336** as the table to be indexed. pParse->pNewTable is a table that is
2337** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002338**
drh382c0242001-10-06 16:33:02 +00002339** pList is a list of columns to be indexed. pList will be NULL if this
2340** is a primary key or unique-constraint on the most recent column added
2341** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002342*/
danielk19774adee202004-05-08 08:23:19 +00002343void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002344 Parse *pParse, /* All information about this parse */
2345 Token *pName1, /* First part of index name. May be NULL */
2346 Token *pName2, /* Second part of index name. May be NULL */
2347 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002348 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002349 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002350 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002351 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002352 int sortOrder, /* Sort order of primary key when pList==NULL */
2353 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002354){
drhfdd6e852005-12-16 01:06:16 +00002355 Table *pTab = 0; /* Table to be indexed */
2356 Index *pIndex = 0; /* The index to be created */
2357 char *zName = 0; /* Name of the index */
2358 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002359 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002360 Token nullId; /* Fake token for an empty ID list */
2361 DbFixer sFix; /* For assigning database names to pTable */
2362 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002363 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002364 Db *pDb; /* The specific table containing the indexed database */
2365 int iDb; /* Index of the database that is being written */
2366 Token *pName = 0; /* Unqualified name of the index to create */
2367 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002368 int nCol;
2369 int nExtra = 0;
2370 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002371
drhd3001712009-05-12 17:46:53 +00002372 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
2373 if( NEVER(pParse->nErr>0) || db->mallocFailed || IN_DECLARE_VTAB ){
2374 goto exit_create_index;
2375 }
2376 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002377 goto exit_create_index;
2378 }
drhdaffd0e2001-04-11 14:28:42 +00002379
drh75897232000-05-29 14:26:00 +00002380 /*
2381 ** Find the table that is to be indexed. Return early if not found.
2382 */
danielk1977cbb18d22004-05-28 11:37:27 +00002383 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002384
2385 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002386 ** to search for the table. 'Fix' the table name to this db
2387 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002388 */
2389 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002390 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002391 if( iDb<0 ) goto exit_create_index;
2392
danielk197753c0f742005-03-29 03:10:59 +00002393#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002394 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002395 ** is a temp table. If so, set the database to 1. Do not do this
2396 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002397 */
danielk1977fe910332007-12-02 11:46:34 +00002398 if( !db->init.busy ){
2399 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002400 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002401 iDb = 1;
2402 }
danielk1977ef2cb632004-05-29 02:37:19 +00002403 }
danielk197753c0f742005-03-29 03:10:59 +00002404#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002405
2406 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2407 sqlite3FixSrcList(&sFix, pTblName)
2408 ){
drh85c23c62005-08-20 03:03:04 +00002409 /* Because the parser constructs pTblName from a single identifier,
2410 ** sqlite3FixSrcList can never fail. */
2411 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002412 }
drhca424112008-01-25 15:04:48 +00002413 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002414 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002415 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002416 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002417 }else{
drhe3c41372001-09-17 20:25:58 +00002418 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002419 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002420 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002421 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002422 }
drhfdd6e852005-12-16 01:06:16 +00002423 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002424
drhd3001712009-05-12 17:46:53 +00002425 assert( pTab!=0 );
2426 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002427 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2428 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002429 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002430 goto exit_create_index;
2431 }
danielk1977576ec6b2005-01-21 11:55:25 +00002432#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002433 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002434 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002435 goto exit_create_index;
2436 }
danielk1977576ec6b2005-01-21 11:55:25 +00002437#endif
danielk19775ee9d692006-06-21 12:36:25 +00002438#ifndef SQLITE_OMIT_VIRTUALTABLE
2439 if( IsVirtual(pTab) ){
2440 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2441 goto exit_create_index;
2442 }
2443#endif
drh75897232000-05-29 14:26:00 +00002444
2445 /*
2446 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002447 ** index or table with the same name.
2448 **
2449 ** Exception: If we are reading the names of permanent indices from the
2450 ** sqlite_master table (because some other process changed the schema) and
2451 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002452 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002453 **
2454 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002455 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2456 ** own name.
drh75897232000-05-29 14:26:00 +00002457 */
danielk1977d8123362004-06-12 09:25:12 +00002458 if( pName ){
drh17435752007-08-16 04:30:38 +00002459 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002460 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002461 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002462 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002463 }
danielk1977d8123362004-06-12 09:25:12 +00002464 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002465 if( sqlite3FindTable(db, zName, 0)!=0 ){
2466 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2467 goto exit_create_index;
2468 }
2469 }
danielk197759a33f92007-03-17 10:26:59 +00002470 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2471 if( !ifNotExist ){
2472 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002473 }
danielk197759a33f92007-03-17 10:26:59 +00002474 goto exit_create_index;
2475 }
danielk1977a21c6b62005-01-24 10:25:59 +00002476 }else{
drhadbca9c2001-09-27 15:11:53 +00002477 int n;
2478 Index *pLoop;
2479 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002480 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002481 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002482 goto exit_create_index;
2483 }
drh75897232000-05-29 14:26:00 +00002484 }
2485
drhe5f9c642003-01-13 23:27:31 +00002486 /* Check for authorization to create an index.
2487 */
2488#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002489 {
drhfdd6e852005-12-16 01:06:16 +00002490 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002491 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002492 goto exit_create_index;
2493 }
2494 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002495 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002496 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002497 goto exit_create_index;
2498 }
drhe5f9c642003-01-13 23:27:31 +00002499 }
2500#endif
2501
drh75897232000-05-29 14:26:00 +00002502 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002503 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002504 ** So create a fake list to simulate this.
2505 */
2506 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002507 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002508 nullId.n = sqlite3Strlen30((char*)nullId.z);
drh6a863cd2009-05-06 18:42:21 +00002509 nullId.quoted = 0;
danielk19771e536952007-08-16 10:09:01 +00002510 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002511 if( pList==0 ) goto exit_create_index;
drh1bd10f82008-12-10 21:19:56 +00002512 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002513 }
2514
danielk1977b3bf5562006-01-10 17:58:23 +00002515 /* Figure out how many bytes of space are required to store explicitly
2516 ** specified collation sequence names.
2517 */
2518 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002519 Expr *pExpr = pList->a[i].pExpr;
2520 if( pExpr ){
2521 CollSeq *pColl = pExpr->pColl;
2522 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2523 ** failure we have quit before reaching this point. */
2524 if( ALWAYS(pColl) ){
2525 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2526 }
danielk1977b3bf5562006-01-10 17:58:23 +00002527 }
2528 }
2529
drh75897232000-05-29 14:26:00 +00002530 /*
2531 ** Allocate the index structure.
2532 */
drhea678832008-12-10 19:26:22 +00002533 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002534 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002535 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002536 sizeof(Index) + /* Index structure */
2537 sizeof(int)*nCol + /* Index.aiColumn */
2538 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2539 sizeof(char *)*nCol + /* Index.azColl */
2540 sizeof(u8)*nCol + /* Index.aSortOrder */
2541 nName + 1 + /* Index.zName */
2542 nExtra /* Collation sequence names */
2543 );
drh17435752007-08-16 04:30:38 +00002544 if( db->mallocFailed ){
2545 goto exit_create_index;
2546 }
drh78aecb72006-02-10 18:08:09 +00002547 pIndex->azColl = (char**)(&pIndex[1]);
2548 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002549 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002550 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002551 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2552 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002553 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002554 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002555 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002556 pIndex->onError = (u8)onError;
2557 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002558 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002559
drhfdd6e852005-12-16 01:06:16 +00002560 /* Check to see if we should honor DESC requests on index columns
2561 */
danielk1977da184232006-01-05 11:34:32 +00002562 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002563 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002564 }else{
2565 sortOrderMask = 0; /* Ignore DESC */
2566 }
2567
drh1ccde152000-06-17 13:12:39 +00002568 /* Scan the names of the columns of the table to be indexed and
2569 ** load the column indices into the Index structure. Report an error
2570 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002571 **
2572 ** TODO: Add a test to make sure that the same column is not named
2573 ** more than once within the same index. Only the first instance of
2574 ** the column will ever be used by the optimizer. Note that using the
2575 ** same column more than once cannot be an error because that would
2576 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002577 */
drhfdd6e852005-12-16 01:06:16 +00002578 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2579 const char *zColName = pListItem->zName;
2580 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002581 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002582 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002583
drhfdd6e852005-12-16 01:06:16 +00002584 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2585 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002586 }
2587 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002588 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002589 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002590 goto exit_create_index;
2591 }
drh967e8b72000-06-21 13:59:10 +00002592 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002593 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2594 ** the way the "idxlist" non-terminal is constructed by the parser,
2595 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2596 ** must exist or else there must have been an OOM error. But if there
2597 ** was an OOM error, we would never reach this point. */
2598 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2599 int nColl;
2600 zColl = pListItem->pExpr->pColl->zName;
2601 nColl = sqlite3Strlen30(zColl) + 1;
2602 assert( nExtra>=nColl );
2603 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002604 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002605 zExtra += nColl;
2606 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002607 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002608 zColl = pTab->aCol[j].zColl;
2609 if( !zColl ){
2610 zColl = db->pDfltColl->zName;
2611 }
danielk19770202b292004-06-09 09:55:16 +00002612 }
drhb7f24de2009-05-13 17:35:23 +00002613 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002614 goto exit_create_index;
2615 }
danielk1977b3bf5562006-01-10 17:58:23 +00002616 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002617 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002618 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002619 }
drh51147ba2005-07-23 22:59:55 +00002620 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002621
danielk1977d8123362004-06-12 09:25:12 +00002622 if( pTab==pParse->pNewTable ){
2623 /* This routine has been called to create an automatic index as a
2624 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2625 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2626 ** i.e. one of:
2627 **
2628 ** CREATE TABLE t(x PRIMARY KEY, y);
2629 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2630 **
2631 ** Either way, check to see if the table already has such an index. If
2632 ** so, don't bother creating this one. This only applies to
2633 ** automatically created indices. Users can do as they wish with
2634 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002635 **
2636 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2637 ** (and thus suppressing the second one) even if they have different
2638 ** sort orders.
2639 **
2640 ** If there are different collating sequences or if the columns of
2641 ** the constraint occur in different orders, then the constraints are
2642 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002643 */
2644 Index *pIdx;
2645 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2646 int k;
2647 assert( pIdx->onError!=OE_None );
2648 assert( pIdx->autoIndex );
2649 assert( pIndex->onError!=OE_None );
2650
2651 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2652 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002653 const char *z1;
2654 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002655 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002656 z1 = pIdx->azColl[k];
2657 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002658 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002659 }
2660 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002661 if( pIdx->onError!=pIndex->onError ){
2662 /* This constraint creates the same index as a previous
2663 ** constraint specified somewhere in the CREATE TABLE statement.
2664 ** However the ON CONFLICT clauses are different. If both this
2665 ** constraint and the previous equivalent constraint have explicit
2666 ** ON CONFLICT clauses this is an error. Otherwise, use the
2667 ** explicitly specified behaviour for the index.
2668 */
2669 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2670 sqlite3ErrorMsg(pParse,
2671 "conflicting ON CONFLICT clauses specified", 0);
2672 }
2673 if( pIdx->onError==OE_Default ){
2674 pIdx->onError = pIndex->onError;
2675 }
2676 }
danielk1977d8123362004-06-12 09:25:12 +00002677 goto exit_create_index;
2678 }
2679 }
2680 }
2681
drh75897232000-05-29 14:26:00 +00002682 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002683 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002684 */
drh234c39d2004-07-24 03:30:47 +00002685 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002686 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002687 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002688 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002689 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002690 if( p ){
2691 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002692 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002693 goto exit_create_index;
2694 }
drh5e00f6c2001-09-13 13:46:56 +00002695 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002696 if( pTblName!=0 ){
2697 pIndex->tnum = db->init.newTnum;
2698 }
drhd78eeee2001-09-13 16:18:53 +00002699 }
2700
drh1d85d932004-02-14 23:05:52 +00002701 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002702 ** involves writing the index into the master table and filling in the
2703 ** index with the current table contents.
2704 **
drh1d85d932004-02-14 23:05:52 +00002705 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2706 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002707 ** CREATE INDEX statements are read out of the master table. In
2708 ** the latter case the index already exists on disk, which is why
2709 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002710 **
danielk1977cbb18d22004-05-28 11:37:27 +00002711 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002712 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2713 ** has just been created, it contains no data and the index initialization
2714 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002715 */
drhd3001712009-05-12 17:46:53 +00002716 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002717 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002718 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002719 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002720
danielk19774adee202004-05-08 08:23:19 +00002721 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002722 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002723
drhfdd6e852005-12-16 01:06:16 +00002724
drh063336a2004-11-05 20:58:39 +00002725 /* Create the rootpage for the index
2726 */
drhaee128d2005-02-14 20:48:18 +00002727 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002728 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002729
2730 /* Gather the complete text of the CREATE INDEX statement into
2731 ** the zStmt variable
2732 */
drhd3001712009-05-12 17:46:53 +00002733 if( pStart ){
2734 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002735 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002736 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002737 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002738 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002739 pName->z);
2740 }else{
2741 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002742 /* zStmt = sqlite3MPrintf(""); */
2743 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002744 }
drh063336a2004-11-05 20:58:39 +00002745
2746 /* Add an entry in sqlite_master for this index
2747 */
2748 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002749 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002750 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2751 pIndex->zName,
2752 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002753 iMem,
drh063336a2004-11-05 20:58:39 +00002754 zStmt
2755 );
drh633e6d52008-07-28 19:34:53 +00002756 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002757
danielk1977a21c6b62005-01-24 10:25:59 +00002758 /* Fill the index with data and reparse the schema. Code an OP_Expire
2759 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002760 */
danielk1977cbb18d22004-05-28 11:37:27 +00002761 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002762 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002763 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002764 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2765 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2766 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002767 }
drh75897232000-05-29 14:26:00 +00002768 }
2769
danielk1977d8123362004-06-12 09:25:12 +00002770 /* When adding an index to the list of indices for a table, make
2771 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002772 ** OE_Ignore. This is necessary for the correct constraint check
2773 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2774 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002775 */
drh234c39d2004-07-24 03:30:47 +00002776 if( db->init.busy || pTblName==0 ){
2777 if( onError!=OE_Replace || pTab->pIndex==0
2778 || pTab->pIndex->onError==OE_Replace){
2779 pIndex->pNext = pTab->pIndex;
2780 pTab->pIndex = pIndex;
2781 }else{
2782 Index *pOther = pTab->pIndex;
2783 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2784 pOther = pOther->pNext;
2785 }
2786 pIndex->pNext = pOther->pNext;
2787 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002788 }
drh234c39d2004-07-24 03:30:47 +00002789 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002790 }
danielk1977d8123362004-06-12 09:25:12 +00002791
drh75897232000-05-29 14:26:00 +00002792 /* Clean up before exiting */
2793exit_create_index:
drh956bc922004-07-24 17:38:29 +00002794 if( pIndex ){
danielk1977cb9d8d82009-03-18 18:43:36 +00002795 sqlite3_free(pIndex->zColAff);
2796 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002797 }
drh633e6d52008-07-28 19:34:53 +00002798 sqlite3ExprListDelete(db, pList);
2799 sqlite3SrcListDelete(db, pTblName);
2800 sqlite3DbFree(db, zName);
drh75897232000-05-29 14:26:00 +00002801 return;
2802}
2803
2804/*
drh51147ba2005-07-23 22:59:55 +00002805** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002806** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002807**
2808** aiRowEst[0] is suppose to contain the number of elements in the index.
2809** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2810** number of rows in the table that match any particular value of the
2811** first column of the index. aiRowEst[2] is an estimate of the number
2812** of rows that match any particular combiniation of the first 2 columns
2813** of the index. And so forth. It must always be the case that
2814*
2815** aiRowEst[N]<=aiRowEst[N-1]
2816** aiRowEst[N]>=1
2817**
2818** Apart from that, we have little to go on besides intuition as to
2819** how aiRowEst[] should be initialized. The numbers generated here
2820** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002821*/
2822void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002823 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002824 int i;
drh28c4cf42005-07-27 20:41:43 +00002825 assert( a!=0 );
2826 a[0] = 1000000;
drhdb513882006-05-11 23:14:59 +00002827 for(i=pIdx->nColumn; i>=5; i--){
2828 a[i] = 5;
2829 }
2830 while( i>=1 ){
2831 a[i] = 11 - i;
2832 i--;
drh28c4cf42005-07-27 20:41:43 +00002833 }
2834 if( pIdx->onError!=OE_None ){
2835 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002836 }
2837}
2838
2839/*
drh74e24cd2002-01-09 03:19:59 +00002840** This routine will drop an existing named index. This routine
2841** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002842*/
drh4d91a702006-01-04 15:54:36 +00002843void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002844 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002845 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002846 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002847 int iDb;
drh75897232000-05-29 14:26:00 +00002848
drhd3001712009-05-12 17:46:53 +00002849 if( NEVER(pParse->nErr>0) || db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002850 goto exit_drop_index;
2851 }
drhd24cc422003-03-27 12:51:24 +00002852 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002853 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2854 goto exit_drop_index;
2855 }
danielk19774adee202004-05-08 08:23:19 +00002856 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002857 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002858 if( !ifExists ){
2859 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2860 }
drha6ecd332004-06-10 00:29:09 +00002861 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002862 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002863 }
drh485b39b2002-07-13 03:11:52 +00002864 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002865 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002866 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002867 goto exit_drop_index;
2868 }
danielk1977da184232006-01-05 11:34:32 +00002869 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002870#ifndef SQLITE_OMIT_AUTHORIZATION
2871 {
2872 int code = SQLITE_DROP_INDEX;
2873 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002874 const char *zDb = db->aDb[iDb].zName;
2875 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002876 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002877 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002878 }
danielk1977da184232006-01-05 11:34:32 +00002879 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002880 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002881 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002882 }
drhed6c8672003-01-12 18:02:16 +00002883 }
drhe5f9c642003-01-13 23:27:31 +00002884#endif
drh75897232000-05-29 14:26:00 +00002885
2886 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002887 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002888 if( v ){
drh77658e22007-12-04 16:54:52 +00002889 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002890 sqlite3NestedParse(pParse,
2891 "DELETE FROM %Q.%s WHERE name=%Q",
2892 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2893 pIndex->zName
2894 );
danielk1977006015d2008-04-11 17:11:26 +00002895 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2896 sqlite3NestedParse(pParse,
2897 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2898 db->aDb[iDb].zName, pIndex->zName
2899 );
2900 }
drh9cbf3422008-01-17 16:22:13 +00002901 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002902 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002903 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002904 }
2905
drhd24cc422003-03-27 12:51:24 +00002906exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002907 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002908}
2909
2910/*
drhcf643722007-03-27 13:36:37 +00002911** pArray is a pointer to an array of objects. Each object in the
2912** array is szEntry bytes in size. This routine allocates a new
2913** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002914**
drhcf643722007-03-27 13:36:37 +00002915** *pnEntry is the number of entries already in use. *pnAlloc is
2916** the previously allocated size of the array. initSize is the
2917** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002918**
drhcf643722007-03-27 13:36:37 +00002919** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002920**
drhcf643722007-03-27 13:36:37 +00002921** This routine returns a pointer to the array of objects. This
2922** might be the same as the pArray parameter or it might be a different
2923** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002924*/
drhcf643722007-03-27 13:36:37 +00002925void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002926 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002927 void *pArray, /* Array of objects. Might be reallocated */
2928 int szEntry, /* Size of each object in the array */
2929 int initSize, /* Suggested initial allocation, in elements */
2930 int *pnEntry, /* Number of objects currently in use */
2931 int *pnAlloc, /* Current size of the allocation, in elements */
2932 int *pIdx /* Write the index of a new slot here */
2933){
2934 char *z;
2935 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002936 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002937 int newSize;
drhcf643722007-03-27 13:36:37 +00002938 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002939 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002940 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002941 *pIdx = -1;
2942 return pArray;
drh13449892005-09-07 21:22:45 +00002943 }
drh6a1e0712008-12-05 15:24:15 +00002944 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002945 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002946 }
drhcf643722007-03-27 13:36:37 +00002947 z = (char*)pArray;
2948 memset(&z[*pnEntry * szEntry], 0, szEntry);
2949 *pIdx = *pnEntry;
2950 ++*pnEntry;
2951 return pArray;
drh13449892005-09-07 21:22:45 +00002952}
2953
2954/*
drh75897232000-05-29 14:26:00 +00002955** Append a new element to the given IdList. Create a new IdList if
2956** need be.
drhdaffd0e2001-04-11 14:28:42 +00002957**
2958** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002959*/
drh17435752007-08-16 04:30:38 +00002960IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002961 int i;
drh75897232000-05-29 14:26:00 +00002962 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002963 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002964 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002965 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002966 }
drhcf643722007-03-27 13:36:37 +00002967 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002968 db,
drhcf643722007-03-27 13:36:37 +00002969 pList->a,
2970 sizeof(pList->a[0]),
2971 5,
2972 &pList->nId,
2973 &pList->nAlloc,
2974 &i
2975 );
drh13449892005-09-07 21:22:45 +00002976 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002977 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002978 return 0;
drh75897232000-05-29 14:26:00 +00002979 }
drh17435752007-08-16 04:30:38 +00002980 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002981 return pList;
2982}
2983
2984/*
drhfe05af82005-07-21 03:14:59 +00002985** Delete an IdList.
2986*/
drh633e6d52008-07-28 19:34:53 +00002987void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00002988 int i;
2989 if( pList==0 ) return;
2990 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00002991 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00002992 }
drh633e6d52008-07-28 19:34:53 +00002993 sqlite3DbFree(db, pList->a);
2994 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00002995}
2996
2997/*
2998** Return the index in pList of the identifier named zId. Return -1
2999** if not found.
3000*/
3001int sqlite3IdListIndex(IdList *pList, const char *zName){
3002 int i;
3003 if( pList==0 ) return -1;
3004 for(i=0; i<pList->nId; i++){
3005 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3006 }
3007 return -1;
3008}
3009
3010/*
drha78c22c2008-11-11 18:28:58 +00003011** Expand the space allocated for the given SrcList object by
3012** creating nExtra new slots beginning at iStart. iStart is zero based.
3013** New slots are zeroed.
3014**
3015** For example, suppose a SrcList initially contains two entries: A,B.
3016** To append 3 new entries onto the end, do this:
3017**
3018** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3019**
3020** After the call above it would contain: A, B, nil, nil, nil.
3021** If the iStart argument had been 1 instead of 2, then the result
3022** would have been: A, nil, nil, nil, B. To prepend the new slots,
3023** the iStart value would be 0. The result then would
3024** be: nil, nil, nil, A, B.
3025**
3026** If a memory allocation fails the SrcList is unchanged. The
3027** db->mallocFailed flag will be set to true.
3028*/
3029SrcList *sqlite3SrcListEnlarge(
3030 sqlite3 *db, /* Database connection to notify of OOM errors */
3031 SrcList *pSrc, /* The SrcList to be enlarged */
3032 int nExtra, /* Number of new slots to add to pSrc->a[] */
3033 int iStart /* Index in pSrc->a[] of first new slot */
3034){
3035 int i;
3036
3037 /* Sanity checking on calling parameters */
3038 assert( iStart>=0 );
3039 assert( nExtra>=1 );
3040 if( pSrc==0 || iStart>pSrc->nSrc ){
3041 assert( db->mallocFailed );
3042 return pSrc;
3043 }
3044
3045 /* Allocate additional space if needed */
3046 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3047 SrcList *pNew;
3048 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003049 int nGot;
drha78c22c2008-11-11 18:28:58 +00003050 pNew = sqlite3DbRealloc(db, pSrc,
3051 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3052 if( pNew==0 ){
3053 assert( db->mallocFailed );
3054 return pSrc;
3055 }
3056 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003057 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003058 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003059 }
3060
3061 /* Move existing slots that come after the newly inserted slots
3062 ** out of the way */
3063 for(i=pSrc->nSrc-1; i>=iStart; i--){
3064 pSrc->a[i+nExtra] = pSrc->a[i];
3065 }
shane18e526c2008-12-10 22:30:24 +00003066 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003067
3068 /* Zero the newly allocated slots */
3069 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3070 for(i=iStart; i<iStart+nExtra; i++){
3071 pSrc->a[i].iCursor = -1;
3072 }
3073
3074 /* Return a pointer to the enlarged SrcList */
3075 return pSrc;
3076}
3077
3078
3079/*
drhad3cab52002-05-24 02:04:32 +00003080** Append a new table name to the given SrcList. Create a new SrcList if
3081** need be. A new entry is created in the SrcList even if pToken is NULL.
3082**
drha78c22c2008-11-11 18:28:58 +00003083** A SrcList is returned, or NULL if there is an OOM error. The returned
3084** SrcList might be the same as the SrcList that was input or it might be
3085** a new one. If an OOM error does occurs, then the prior value of pList
3086** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003087**
3088** If pDatabase is not null, it means that the table has an optional
3089** database name prefix. Like this: "database.table". The pDatabase
3090** points to the table name and the pTable points to the database name.
3091** The SrcList.a[].zName field is filled with the table name which might
3092** come from pTable (if pDatabase is NULL) or from pDatabase.
3093** SrcList.a[].zDatabase is filled with the database name from pTable,
3094** or with NULL if no database is specified.
3095**
3096** In other words, if call like this:
3097**
drh17435752007-08-16 04:30:38 +00003098** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003099**
3100** Then B is a table name and the database name is unspecified. If called
3101** like this:
3102**
drh17435752007-08-16 04:30:38 +00003103** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003104**
drhd3001712009-05-12 17:46:53 +00003105** Then C is the table name and B is the database name. If C is defined
3106** then so is B. In other words, we never have a case where:
3107**
3108** sqlite3SrcListAppend(D,A,0,C);
drhad3cab52002-05-24 02:04:32 +00003109*/
drh17435752007-08-16 04:30:38 +00003110SrcList *sqlite3SrcListAppend(
3111 sqlite3 *db, /* Connection to notify of malloc failures */
3112 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3113 Token *pTable, /* Table to append */
3114 Token *pDatabase /* Database of the table */
3115){
drha99db3b2004-06-19 14:49:12 +00003116 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003117 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003118 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003119 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003120 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003121 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003122 }
drha78c22c2008-11-11 18:28:58 +00003123 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3124 if( db->mallocFailed ){
3125 sqlite3SrcListDelete(db, pList);
3126 return 0;
drhad3cab52002-05-24 02:04:32 +00003127 }
drha78c22c2008-11-11 18:28:58 +00003128 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003129 if( pDatabase && pDatabase->z==0 ){
3130 pDatabase = 0;
3131 }
drhd3001712009-05-12 17:46:53 +00003132 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003133 Token *pTemp = pDatabase;
3134 pDatabase = pTable;
3135 pTable = pTemp;
3136 }
drh17435752007-08-16 04:30:38 +00003137 pItem->zName = sqlite3NameFromToken(db, pTable);
3138 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003139 return pList;
3140}
3141
3142/*
drhdfe88ec2008-11-03 20:55:06 +00003143** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003144*/
danielk19774adee202004-05-08 08:23:19 +00003145void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003146 int i;
drh9b3187e2005-01-18 14:45:47 +00003147 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003148 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003149 if( pList ){
3150 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3151 if( pItem->iCursor>=0 ) break;
3152 pItem->iCursor = pParse->nTab++;
3153 if( pItem->pSelect ){
3154 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3155 }
drh63eb5f22003-04-29 16:20:44 +00003156 }
3157 }
3158}
3159
3160/*
drhad3cab52002-05-24 02:04:32 +00003161** Delete an entire SrcList including all its substructure.
3162*/
drh633e6d52008-07-28 19:34:53 +00003163void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003164 int i;
drhbe5c89a2004-07-26 00:31:09 +00003165 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003166 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003167 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003168 sqlite3DbFree(db, pItem->zDatabase);
3169 sqlite3DbFree(db, pItem->zName);
3170 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003171 sqlite3DbFree(db, pItem->zIndex);
danielk1977a04a34f2007-04-16 15:06:25 +00003172 sqlite3DeleteTable(pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003173 sqlite3SelectDelete(db, pItem->pSelect);
3174 sqlite3ExprDelete(db, pItem->pOn);
3175 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003176 }
drh633e6d52008-07-28 19:34:53 +00003177 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003178}
3179
drh982cef72000-05-30 16:27:03 +00003180/*
drh61dfc312006-12-16 16:25:15 +00003181** This routine is called by the parser to add a new term to the
3182** end of a growing FROM clause. The "p" parameter is the part of
3183** the FROM clause that has already been constructed. "p" is NULL
3184** if this is the first term of the FROM clause. pTable and pDatabase
3185** are the name of the table and database named in the FROM clause term.
3186** pDatabase is NULL if the database name qualifier is missing - the
3187** usual case. If the term has a alias, then pAlias points to the
3188** alias token. If the term is a subquery, then pSubquery is the
3189** SELECT statement that the subquery encodes. The pTable and
3190** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3191** parameters are the content of the ON and USING clauses.
3192**
3193** Return a new SrcList which encodes is the FROM with the new
3194** term added.
3195*/
3196SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003197 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003198 SrcList *p, /* The left part of the FROM clause already seen */
3199 Token *pTable, /* Name of the table to add to the FROM clause */
3200 Token *pDatabase, /* Name of the database containing pTable */
3201 Token *pAlias, /* The right-hand side of the AS subexpression */
3202 Select *pSubquery, /* A subquery used in place of a table name */
3203 Expr *pOn, /* The ON clause of a join */
3204 IdList *pUsing /* The USING clause of a join */
3205){
3206 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003207 sqlite3 *db = pParse->db;
3208 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh61dfc312006-12-16 16:25:15 +00003209 if( p==0 || p->nSrc==0 ){
drh633e6d52008-07-28 19:34:53 +00003210 sqlite3ExprDelete(db, pOn);
3211 sqlite3IdListDelete(db, pUsing);
3212 sqlite3SelectDelete(db, pSubquery);
drh61dfc312006-12-16 16:25:15 +00003213 return p;
3214 }
3215 pItem = &p->a[p->nSrc-1];
3216 if( pAlias && pAlias->n ){
drh17435752007-08-16 04:30:38 +00003217 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003218 }
3219 pItem->pSelect = pSubquery;
3220 pItem->pOn = pOn;
3221 pItem->pUsing = pUsing;
3222 return p;
3223}
3224
3225/*
danielk1977b1c685b2008-10-06 16:18:39 +00003226** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3227** element of the source-list passed as the second argument.
3228*/
3229void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3230 if( pIndexedBy && p && p->nSrc>0 ){
3231 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3232 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3233 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3234 /* A "NOT INDEXED" clause was supplied. See parse.y
3235 ** construct "indexed_opt" for details. */
3236 pItem->notIndexed = 1;
3237 }else{
3238 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3239 }
3240 }
3241}
3242
3243/*
drh61dfc312006-12-16 16:25:15 +00003244** When building up a FROM clause in the parser, the join operator
3245** is initially attached to the left operand. But the code generator
3246** expects the join operator to be on the right operand. This routine
3247** Shifts all join operators from left to right for an entire FROM
3248** clause.
3249**
3250** Example: Suppose the join is like this:
3251**
3252** A natural cross join B
3253**
3254** The operator is "natural cross join". The A and B operands are stored
3255** in p->a[0] and p->a[1], respectively. The parser initially stores the
3256** operator with A. This routine shifts that operator over to B.
3257*/
3258void sqlite3SrcListShiftJoinType(SrcList *p){
3259 if( p && p->a ){
3260 int i;
3261 for(i=p->nSrc-1; i>0; i--){
3262 p->a[i].jointype = p->a[i-1].jointype;
3263 }
3264 p->a[0].jointype = 0;
3265 }
3266}
3267
3268/*
drhc4a3c772001-04-04 11:48:57 +00003269** Begin a transaction
3270*/
drh684917c2004-10-05 02:41:42 +00003271void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003272 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003273 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003274 int i;
drh5e00f6c2001-09-13 13:46:56 +00003275
drhd3001712009-05-12 17:46:53 +00003276 assert( pParse!=0 );
3277 db = pParse->db;
3278 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003279/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003280 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3281 return;
3282 }
danielk19771d850a72004-05-31 08:26:49 +00003283 v = sqlite3GetVdbe(pParse);
3284 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003285 if( type!=TK_DEFERRED ){
3286 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003287 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003288 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003289 }
3290 }
drh66a51672008-01-03 00:01:23 +00003291 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003292}
3293
3294/*
3295** Commit a transaction
3296*/
danielk19774adee202004-05-08 08:23:19 +00003297void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003298 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003299 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003300
drhd3001712009-05-12 17:46:53 +00003301 assert( pParse!=0 );
3302 db = pParse->db;
3303 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003304/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003305 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3306 return;
3307 }
danielk19771d850a72004-05-31 08:26:49 +00003308 v = sqlite3GetVdbe(pParse);
3309 if( v ){
drh66a51672008-01-03 00:01:23 +00003310 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003311 }
drhc4a3c772001-04-04 11:48:57 +00003312}
3313
3314/*
3315** Rollback a transaction
3316*/
danielk19774adee202004-05-08 08:23:19 +00003317void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003318 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003319 Vdbe *v;
3320
drhd3001712009-05-12 17:46:53 +00003321 assert( pParse!=0 );
3322 db = pParse->db;
3323 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003324/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003325 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3326 return;
3327 }
danielk19774adee202004-05-08 08:23:19 +00003328 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003329 if( v ){
drh66a51672008-01-03 00:01:23 +00003330 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003331 }
drhc4a3c772001-04-04 11:48:57 +00003332}
drhf57b14a2001-09-14 18:54:08 +00003333
3334/*
danielk1977fd7f0452008-12-17 17:30:26 +00003335** This function is called by the parser when it parses a command to create,
3336** release or rollback an SQL savepoint.
3337*/
3338void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003339 char *zName = sqlite3NameFromToken(pParse->db, pName);
3340 if( zName ){
3341 Vdbe *v = sqlite3GetVdbe(pParse);
3342#ifndef SQLITE_OMIT_AUTHORIZATION
3343 static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3344 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3345#endif
3346 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3347 sqlite3DbFree(pParse->db, zName);
3348 return;
3349 }
3350 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003351 }
3352}
3353
3354/*
drhdc3ff9c2004-08-18 02:10:15 +00003355** Make sure the TEMP database is open and available for use. Return
3356** the number of errors. Leave any error messages in the pParse structure.
3357*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003358int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003359 sqlite3 *db = pParse->db;
3360 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003361 int rc;
3362 static const int flags =
3363 SQLITE_OPEN_READWRITE |
3364 SQLITE_OPEN_CREATE |
3365 SQLITE_OPEN_EXCLUSIVE |
3366 SQLITE_OPEN_DELETEONCLOSE |
3367 SQLITE_OPEN_TEMP_DB;
3368
3369 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
drhc797d4d2007-05-08 01:08:49 +00003370 &db->aDb[1].pBt);
drhdc3ff9c2004-08-18 02:10:15 +00003371 if( rc!=SQLITE_OK ){
3372 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3373 "file for storing temporary tables");
3374 pParse->rc = rc;
3375 return 1;
3376 }
drh60a713c2008-01-21 16:22:45 +00003377 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
danielk197714db2662006-01-09 16:12:04 +00003378 assert( db->aDb[1].pSchema );
drhfdc40e92008-04-17 20:59:37 +00003379 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
3380 db->dfltJournalMode);
drhdc3ff9c2004-08-18 02:10:15 +00003381 }
3382 return 0;
3383}
3384
3385/*
drh80242052004-06-09 00:48:12 +00003386** Generate VDBE code that will verify the schema cookie and start
3387** a read-transaction for all named database files.
3388**
3389** It is important that all schema cookies be verified and all
3390** read transactions be started before anything else happens in
3391** the VDBE program. But this routine can be called after much other
3392** code has been generated. So here is what we do:
3393**
drhc275b4e2004-07-19 17:25:24 +00003394** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003395** will jump to a subroutine at the end of the program. Then we
3396** record every database that needs its schema verified in the
3397** pParse->cookieMask field. Later, after all other code has been
3398** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003399** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003400** will be made to point to that subroutine. The generation of the
3401** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003402**
3403** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3404** schema on any databases. This can be used to position the OP_Goto
3405** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003406*/
danielk19774adee202004-05-08 08:23:19 +00003407void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003408 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003409 Vdbe *v;
3410 int mask;
3411
3412 v = sqlite3GetVdbe(pParse);
3413 if( v==0 ) return; /* This only happens if there was a prior error */
3414 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003415 if( pParse->cookieGoto==0 ){
drh66a51672008-01-03 00:01:23 +00003416 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003417 }
drhc275b4e2004-07-19 17:25:24 +00003418 if( iDb>=0 ){
3419 assert( iDb<db->nDb );
3420 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003421 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003422 mask = 1<<iDb;
3423 if( (pParse->cookieMask & mask)==0 ){
3424 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003425 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003426 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003427 sqlite3OpenTempDatabase(pParse);
3428 }
drhc275b4e2004-07-19 17:25:24 +00003429 }
drh001bbcb2003-03-19 03:14:00 +00003430 }
drh001bbcb2003-03-19 03:14:00 +00003431}
3432
3433/*
drh1c928532002-01-31 15:54:21 +00003434** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003435** might change the database.
3436**
3437** This routine starts a new transaction if we are not already within
3438** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003439** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003440** be set for operations that might fail (due to a constraint) part of
3441** the way through and which will need to undo some writes without having to
3442** rollback the whole transaction. For operations where all constraints
3443** can be checked before any changes are made to the database, it is never
3444** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003445*/
drh7f0f12e2004-05-21 13:39:50 +00003446void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003447 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003448 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003449 sqlite3CodeVerifySchema(pParse, iDb);
3450 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003451 if( setStatement && pParse->nested==0 ){
drh66a51672008-01-03 00:01:23 +00003452 sqlite3VdbeAddOp1(v, OP_Statement, iDb);
danielk19771d850a72004-05-31 08:26:49 +00003453 }
drh663fc632002-02-02 18:49:19 +00003454}
3455
drh4343fea2004-11-05 23:46:15 +00003456/*
3457** Check to see if pIndex uses the collating sequence pColl. Return
3458** true if it does and false if it does not.
3459*/
3460#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003461static int collationMatch(const char *zColl, Index *pIndex){
3462 int i;
drh04491712009-05-13 17:21:13 +00003463 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003464 for(i=0; i<pIndex->nColumn; i++){
3465 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003466 assert( z!=0 );
3467 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003468 return 1;
3469 }
drh4343fea2004-11-05 23:46:15 +00003470 }
3471 return 0;
3472}
3473#endif
3474
3475/*
3476** Recompute all indices of pTab that use the collating sequence pColl.
3477** If pColl==0 then recompute all indices of pTab.
3478*/
3479#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003480static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003481 Index *pIndex; /* An index associated with pTab */
3482
3483 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003484 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003485 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3486 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003487 sqlite3RefillIndex(pParse, pIndex, -1);
3488 }
3489 }
3490}
3491#endif
3492
3493/*
3494** Recompute all indices of all tables in all databases where the
3495** indices use the collating sequence pColl. If pColl==0 then recompute
3496** all indices everywhere.
3497*/
3498#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003499static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003500 Db *pDb; /* A single database */
3501 int iDb; /* The database index number */
3502 sqlite3 *db = pParse->db; /* The database connection */
3503 HashElem *k; /* For looping over tables in pDb */
3504 Table *pTab; /* A table in the database */
3505
3506 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003507 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003508 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003509 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003510 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003511 }
3512 }
3513}
3514#endif
3515
3516/*
drheee46cf2004-11-06 00:02:48 +00003517** Generate code for the REINDEX command.
3518**
3519** REINDEX -- 1
3520** REINDEX <collation> -- 2
3521** REINDEX ?<database>.?<tablename> -- 3
3522** REINDEX ?<database>.?<indexname> -- 4
3523**
3524** Form 1 causes all indices in all attached databases to be rebuilt.
3525** Form 2 rebuilds all indices in all databases that use the named
3526** collating function. Forms 3 and 4 rebuild the named index or all
3527** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003528*/
3529#ifndef SQLITE_OMIT_REINDEX
3530void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3531 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3532 char *z; /* Name of a table or index */
3533 const char *zDb; /* Name of the database */
3534 Table *pTab; /* A table in the database */
3535 Index *pIndex; /* An index associated with pTab */
3536 int iDb; /* The database index number */
3537 sqlite3 *db = pParse->db; /* The database connection */
3538 Token *pObjName; /* Name of the table or index to be reindexed */
3539
danielk197733a5edc2005-01-27 00:22:02 +00003540 /* Read the database schema. If an error occurs, leave an error message
3541 ** and code in pParse and return NULL. */
3542 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003543 return;
danielk197733a5edc2005-01-27 00:22:02 +00003544 }
3545
drhd3001712009-05-12 17:46:53 +00003546 if( pName1==0 || NEVER(pName1->z==0) ){
drh4343fea2004-11-05 23:46:15 +00003547 reindexDatabases(pParse, 0);
3548 return;
drhd3001712009-05-12 17:46:53 +00003549 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003550 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003551 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003552 zColl = sqlite3NameFromToken(pParse->db, pName1);
3553 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003554 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003555 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003556 reindexDatabases(pParse, zColl);
3557 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003558 return;
3559 }
drh633e6d52008-07-28 19:34:53 +00003560 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003561 }
3562 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3563 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003564 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003565 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003566 zDb = db->aDb[iDb].zName;
3567 pTab = sqlite3FindTable(db, z, zDb);
3568 if( pTab ){
3569 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003570 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003571 return;
3572 }
3573 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003574 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003575 if( pIndex ){
3576 sqlite3BeginWriteOperation(pParse, 0, iDb);
3577 sqlite3RefillIndex(pParse, pIndex, -1);
3578 return;
3579 }
3580 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3581}
3582#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003583
3584/*
3585** Return a dynamicly allocated KeyInfo structure that can be used
3586** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3587**
3588** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003589** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003590** pointer. If an error occurs (out of memory or missing collation
3591** sequence), NULL is returned and the state of pParse updated to reflect
3592** the error.
3593*/
3594KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3595 int i;
3596 int nCol = pIdx->nColumn;
3597 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003598 sqlite3 *db = pParse->db;
3599 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003600
3601 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003602 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003603 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3604 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3605 for(i=0; i<nCol; i++){
3606 char *zColl = pIdx->azColl[i];
3607 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003608 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003609 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3610 }
drh1bd10f82008-12-10 21:19:56 +00003611 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003612 }
3613
3614 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003615 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003616 pKey = 0;
3617 }
3618 return pKey;
3619}