blob: 0696f1c82df3c2033abec537f695a23e9b849a32 [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**
danielk1977bd1a0a42009-07-01 16:12:07 +000025** $Id: build.c,v 1.556 2009/07/01 16:12:08 danielk1977 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
drh8af73d42009-05-13 22:58:28 +000071 assert( iDb>=0 );
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);
drh0b9f50d2009-06-23 20:28:53 +0000177
178 /* Initialize any AUTOINCREMENT data structures required.
179 */
180 sqlite3AutoincrementBegin(pParse);
181
182 /* Finally, jump back to the beginning of the executable code. */
drh66a51672008-01-03 00:01:23 +0000183 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000184 }
drh71c697e2004-08-08 23:39:19 +0000185 }
186
drh3f7d4e42004-07-24 14:35:58 +0000187
drh80242052004-06-09 00:48:12 +0000188 /* Get the VDBE program ready for execution
189 */
drh04491712009-05-13 17:21:13 +0000190 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000191#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000192 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000193 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000194#endif
drhceea3322009-04-23 13:22:42 +0000195 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
danielk19776ab3a2e2009-02-19 14:39:25 +0000196 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
197 pParse->nTab, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000198 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000199 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000200 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000201 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000202 }
drha226d052002-09-25 19:04:07 +0000203 pParse->nTab = 0;
204 pParse->nMem = 0;
205 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000206 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000207 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000208 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000209}
210
211/*
drh205f48e2004-11-05 00:43:11 +0000212** Run the parser and code generator recursively in order to generate
213** code for the SQL statement given onto the end of the pParse context
214** currently under construction. When the parser is run recursively
215** this way, the final OP_Halt is not appended and other initialization
216** and finalization steps are omitted because those are handling by the
217** outermost parser.
218**
219** Not everything is nestable. This facility is designed to permit
220** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000221** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000222*/
223void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
224 va_list ap;
225 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000226 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000227 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000228# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
229 char saveBuf[SAVE_SZ];
230
drh205f48e2004-11-05 00:43:11 +0000231 if( pParse->nErr ) return;
232 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
233 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000234 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000235 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000236 if( zSql==0 ){
237 return; /* A malloc must have failed */
238 }
drh205f48e2004-11-05 00:43:11 +0000239 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000240 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
241 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000242 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000243 sqlite3DbFree(db, zErrMsg);
244 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000245 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000246 pParse->nested--;
247}
248
249/*
danielk19778a414492004-06-29 08:59:35 +0000250** Locate the in-memory structure that describes a particular database
251** table given the name of that table and (optionally) the name of the
252** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000253**
danielk19778a414492004-06-29 08:59:35 +0000254** If zDatabase is 0, all databases are searched for the table and the
255** first matching table is returned. (No checking for duplicate table
256** names is done.) The search order is TEMP first, then MAIN, then any
257** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000258**
danielk19774adee202004-05-08 08:23:19 +0000259** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000260*/
drh9bb575f2004-09-06 17:24:11 +0000261Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000262 Table *p = 0;
263 int i;
drh0a687d12008-07-08 14:52:07 +0000264 int nName;
drh645f63e2004-06-22 13:22:40 +0000265 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000266 nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000267 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000268 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000269 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh0a687d12008-07-08 14:52:07 +0000270 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000271 if( p ) break;
272 }
drh74e24cd2002-01-09 03:19:59 +0000273 return p;
drh75897232000-05-29 14:26:00 +0000274}
275
276/*
danielk19778a414492004-06-29 08:59:35 +0000277** Locate the in-memory structure that describes a particular database
278** table given the name of that table and (optionally) the name of the
279** database containing the table. Return NULL if not found. Also leave an
280** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000281**
danielk19778a414492004-06-29 08:59:35 +0000282** The difference between this routine and sqlite3FindTable() is that this
283** routine leaves an error message in pParse->zErrMsg where
284** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000285*/
drhca424112008-01-25 15:04:48 +0000286Table *sqlite3LocateTable(
287 Parse *pParse, /* context in which to report errors */
288 int isView, /* True if looking for a VIEW rather than a TABLE */
289 const char *zName, /* Name of the table we are looking for */
290 const char *zDbase /* Name of the database. Might be NULL */
291){
drha69d9162003-04-17 22:57:53 +0000292 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000293
danielk19778a414492004-06-29 08:59:35 +0000294 /* Read the database schema. If an error occurs, leave an error message
295 ** and code in pParse and return NULL. */
296 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
297 return 0;
298 }
299
danielk19774adee202004-05-08 08:23:19 +0000300 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000301 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000302 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000303 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000304 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000305 }else{
drhca424112008-01-25 15:04:48 +0000306 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000307 }
drha6ecd332004-06-10 00:29:09 +0000308 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000309 }
310 return p;
311}
312
313/*
314** Locate the in-memory structure that describes
315** a particular index given the name of that index
316** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000317** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000318**
319** If zDatabase is 0, all databases are searched for the
320** table and the first matching index is returned. (No checking
321** for duplicate index names is done.) The search order is
322** TEMP first, then MAIN, then any auxiliary databases added
323** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000324*/
drh9bb575f2004-09-06 17:24:11 +0000325Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000326 Index *p = 0;
327 int i;
drhdee0e402009-05-03 20:23:53 +0000328 int nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000329 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000330 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000331 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000332 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000333 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh04491712009-05-13 17:21:13 +0000334 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000335 if( p ) break;
336 }
drh74e24cd2002-01-09 03:19:59 +0000337 return p;
drh75897232000-05-29 14:26:00 +0000338}
339
340/*
drh956bc922004-07-24 17:38:29 +0000341** Reclaim the memory used by an index
342*/
343static void freeIndex(Index *p){
drhd9da78a2009-03-24 15:08:09 +0000344 sqlite3 *db = p->pTable->dbMem;
drh8af73d42009-05-13 22:58:28 +0000345 /* testcase( db==0 ); */
drh633e6d52008-07-28 19:34:53 +0000346 sqlite3DbFree(db, p->zColAff);
347 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000348}
349
350/*
drh75897232000-05-29 14:26:00 +0000351** Remove the given index from the index hash table, and free
352** its memory structures.
353**
drhd229ca92002-01-09 13:30:41 +0000354** The index is removed from the database hash tables but
355** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000356** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000357*/
drh03881232009-02-13 03:43:31 +0000358static void sqlite3DeleteIndex(Index *p){
drhd229ca92002-01-09 13:30:41 +0000359 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000360 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000361
drhea678832008-12-10 19:26:22 +0000362 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
drha83ccca2009-04-28 13:01:09 +0000363 sqlite3Strlen30(zName), 0);
drh85c23c62005-08-20 03:03:04 +0000364 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000365 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000366}
367
368/*
drhc96d8532005-05-03 12:30:33 +0000369** For the index called zIdxName which is found in the database iDb,
370** unlike that index from its Table then remove the index from
371** the index hash table and free all memory structures associated
372** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000373*/
drh9bb575f2004-09-06 17:24:11 +0000374void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000375 Index *pIndex;
376 int len;
danielk1977da184232006-01-05 11:34:32 +0000377 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000378
drhdee0e402009-05-03 20:23:53 +0000379 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000380 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh9635cc72009-06-25 11:50:21 +0000381 if( pIndex ){
drh956bc922004-07-24 17:38:29 +0000382 if( pIndex->pTable->pIndex==pIndex ){
383 pIndex->pTable->pIndex = pIndex->pNext;
384 }else{
385 Index *p;
drh04491712009-05-13 17:21:13 +0000386 /* Justification of ALWAYS(); The index must be on the list of
387 ** indices. */
388 p = pIndex->pTable->pIndex;
389 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
390 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000391 p->pNext = pIndex->pNext;
392 }
drh5e00f6c2001-09-13 13:46:56 +0000393 }
drh956bc922004-07-24 17:38:29 +0000394 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000395 }
drh956bc922004-07-24 17:38:29 +0000396 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000397}
398
399/*
drhe0bc4042002-06-25 01:09:11 +0000400** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000401** a single database. This routine is called to reclaim memory
402** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000403** if there were schema changes during the transaction or if a
404** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000405**
drh62312862009-02-03 22:17:42 +0000406** If iDb==0 then reset the internal schema tables for all database
407** files. If iDb>=1 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000408** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000409*/
drh9bb575f2004-09-06 17:24:11 +0000410void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000411 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000412 assert( iDb>=0 && iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000413
414 if( iDb==0 ){
415 sqlite3BtreeEnterAll(db);
416 }
drh1c2d8412003-03-31 00:30:47 +0000417 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000418 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000419 if( pDb->pSchema ){
danielk19774eab8b72007-12-27 15:12:16 +0000420 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
danielk1977de0fe3e2006-01-06 06:33:12 +0000421 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000422 }
drh1c2d8412003-03-31 00:30:47 +0000423 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000424 }
drh1c2d8412003-03-31 00:30:47 +0000425 assert( iDb==0 );
426 db->flags &= ~SQLITE_InternChanges;
danielk19774eab8b72007-12-27 15:12:16 +0000427 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000428
429 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000430 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000431 ** opportunity to do this here since we have just deleted all of the
432 ** schema hash tables and therefore do not have to make any changes
433 ** to any of those tables.
434 */
435 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000436 struct Db *pDb = &db->aDb[i];
437 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000438 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000439 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000440 continue;
441 }
442 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000443 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000444 }
drh8bf8dc92003-05-17 17:35:10 +0000445 j++;
drh1c2d8412003-03-31 00:30:47 +0000446 }
447 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
448 db->nDb = j;
449 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
450 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000451 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000452 db->aDb = db->aDbStatic;
453 }
drhe0bc4042002-06-25 01:09:11 +0000454}
455
456/*
drhe0bc4042002-06-25 01:09:11 +0000457** This routine is called when a commit occurs.
458*/
drh9bb575f2004-09-06 17:24:11 +0000459void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000460 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000461}
462
463/*
drh956bc922004-07-24 17:38:29 +0000464** Clear the column names from a table or view.
465*/
466static void sqliteResetColumnNames(Table *pTable){
467 int i;
468 Column *pCol;
drhd9da78a2009-03-24 15:08:09 +0000469 sqlite3 *db = pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000470 testcase( db==0 );
drh956bc922004-07-24 17:38:29 +0000471 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000472 if( (pCol = pTable->aCol)!=0 ){
473 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000474 sqlite3DbFree(db, pCol->zName);
475 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000476 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000477 sqlite3DbFree(db, pCol->zType);
478 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000479 }
drh633e6d52008-07-28 19:34:53 +0000480 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000481 }
drh956bc922004-07-24 17:38:29 +0000482 pTable->aCol = 0;
483 pTable->nCol = 0;
484}
485
486/*
drh75897232000-05-29 14:26:00 +0000487** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000488** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000489**
490** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000491** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000492** memory structures of the indices and foreign keys associated with
493** the table.
drh75897232000-05-29 14:26:00 +0000494*/
danielk1977a04a34f2007-04-16 15:06:25 +0000495void sqlite3DeleteTable(Table *pTable){
drh75897232000-05-29 14:26:00 +0000496 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000497 FKey *pFKey, *pNextFKey;
drh633e6d52008-07-28 19:34:53 +0000498 sqlite3 *db;
drhc2eef3b2002-08-31 18:53:06 +0000499
drh75897232000-05-29 14:26:00 +0000500 if( pTable==0 ) return;
drhd9da78a2009-03-24 15:08:09 +0000501 db = pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000502 testcase( db==0 );
drhc2eef3b2002-08-31 18:53:06 +0000503
drhed8a3bb2005-06-06 21:19:56 +0000504 /* Do not delete the table until the reference count reaches zero. */
505 pTable->nRef--;
506 if( pTable->nRef>0 ){
507 return;
508 }
509 assert( pTable->nRef==0 );
510
drhc2eef3b2002-08-31 18:53:06 +0000511 /* Delete all indices associated with this table
512 */
513 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
514 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000515 assert( pIndex->pSchema==pTable->pSchema );
drh03881232009-02-13 03:43:31 +0000516 sqlite3DeleteIndex(pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000517 }
518
danielk1977576ec6b2005-01-21 11:55:25 +0000519#ifndef SQLITE_OMIT_FOREIGN_KEY
drhe61922a2009-05-02 13:29:37 +0000520 /* Delete all foreign keys associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000521 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
522 pNextFKey = pFKey->pNextFrom;
drh633e6d52008-07-28 19:34:53 +0000523 sqlite3DbFree(db, pFKey);
drhc2eef3b2002-08-31 18:53:06 +0000524 }
danielk1977576ec6b2005-01-21 11:55:25 +0000525#endif
drhc2eef3b2002-08-31 18:53:06 +0000526
527 /* Delete the Table structure itself.
528 */
drh956bc922004-07-24 17:38:29 +0000529 sqliteResetColumnNames(pTable);
drh633e6d52008-07-28 19:34:53 +0000530 sqlite3DbFree(db, pTable->zName);
531 sqlite3DbFree(db, pTable->zColAff);
532 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000533#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000534 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000535#endif
drhb9bb7c12006-06-11 23:41:55 +0000536 sqlite3VtabClear(pTable);
drh633e6d52008-07-28 19:34:53 +0000537 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000538}
539
540/*
drh5edc3122001-09-13 21:53:09 +0000541** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000542** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000543*/
drh9bb575f2004-09-06 17:24:11 +0000544void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000545 Table *p;
drh956bc922004-07-24 17:38:29 +0000546 Db *pDb;
547
drhd229ca92002-01-09 13:30:41 +0000548 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000549 assert( iDb>=0 && iDb<db->nDb );
550 assert( zTabName && zTabName[0] );
551 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000552 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000553 sqlite3Strlen30(zTabName),0);
drhe61922a2009-05-02 13:29:37 +0000554 sqlite3DeleteTable(p);
drh956bc922004-07-24 17:38:29 +0000555 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000556}
557
558/*
drha99db3b2004-06-19 14:49:12 +0000559** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000560** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000561** is obtained from sqliteMalloc() and must be freed by the calling
562** function.
drh75897232000-05-29 14:26:00 +0000563**
drh24fb6272009-05-01 21:13:36 +0000564** Any quotation marks (ex: "name", 'name', [name], or `name`) that
565** surround the body of the token are removed.
566**
drhc96d8532005-05-03 12:30:33 +0000567** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000568** are not \000 terminated and are not persistent. The returned string
569** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000570*/
drh17435752007-08-16 04:30:38 +0000571char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000572 char *zName;
573 if( pName ){
drh17435752007-08-16 04:30:38 +0000574 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000575 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000576 }else{
577 zName = 0;
578 }
drh75897232000-05-29 14:26:00 +0000579 return zName;
580}
581
582/*
danielk1977cbb18d22004-05-28 11:37:27 +0000583** Open the sqlite_master table stored in database number iDb for
584** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000585*/
danielk1977c00da102006-01-07 13:21:04 +0000586void sqlite3OpenMasterTable(Parse *p, int iDb){
587 Vdbe *v = sqlite3GetVdbe(p);
588 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000589 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000590 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000591 if( p->nTab==0 ){
592 p->nTab = 1;
593 }
drhe0bc4042002-06-25 01:09:11 +0000594}
595
596/*
danielk197704103022009-02-03 16:51:24 +0000597** Parameter zName points to a nul-terminated buffer containing the name
598** of a database ("main", "temp" or the name of an attached db). This
599** function returns the index of the named database in db->aDb[], or
600** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000601*/
danielk197704103022009-02-03 16:51:24 +0000602int sqlite3FindDbName(sqlite3 *db, const char *zName){
603 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000604 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000605 Db *pDb;
606 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000607 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000608 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000609 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000610 break;
drh73c42a12004-11-20 18:13:10 +0000611 }
danielk1977cbb18d22004-05-28 11:37:27 +0000612 }
613 }
danielk1977576ec6b2005-01-21 11:55:25 +0000614 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000615}
616
danielk197704103022009-02-03 16:51:24 +0000617/*
618** The token *pName contains the name of a database (either "main" or
619** "temp" or the name of an attached db). This routine returns the
620** index of the named database in db->aDb[], or -1 if the named db
621** does not exist.
622*/
623int sqlite3FindDb(sqlite3 *db, Token *pName){
624 int i; /* Database number */
625 char *zName; /* Name we are searching for */
626 zName = sqlite3NameFromToken(db, pName);
627 i = sqlite3FindDbName(db, zName);
628 sqlite3DbFree(db, zName);
629 return i;
630}
631
drh0e3d7472004-06-19 17:33:07 +0000632/* The table or view or trigger name is passed to this routine via tokens
633** pName1 and pName2. If the table name was fully qualified, for example:
634**
635** CREATE TABLE xxx.yyy (...);
636**
637** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
638** the table name is not fully qualified, i.e.:
639**
640** CREATE TABLE yyy(...);
641**
642** Then pName1 is set to "yyy" and pName2 is "".
643**
644** This routine sets the *ppUnqual pointer to point at the token (pName1 or
645** pName2) that stores the unqualified table name. The index of the
646** database "xxx" is returned.
647*/
danielk1977ef2cb632004-05-29 02:37:19 +0000648int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000649 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000650 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000651 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
652 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000653){
drh0e3d7472004-06-19 17:33:07 +0000654 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000655 sqlite3 *db = pParse->db;
656
drhc4a64fa2009-05-11 20:53:28 +0000657 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000658 if( db->init.busy ) {
659 sqlite3ErrorMsg(pParse, "corrupt database");
660 pParse->nErr++;
661 return -1;
662 }
danielk1977cbb18d22004-05-28 11:37:27 +0000663 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000664 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000665 if( iDb<0 ){
666 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
667 pParse->nErr++;
668 return -1;
669 }
670 }else{
671 assert( db->init.iDb==0 || db->init.busy );
672 iDb = db->init.iDb;
673 *pUnqual = pName1;
674 }
675 return iDb;
676}
677
678/*
danielk1977d8123362004-06-12 09:25:12 +0000679** This routine is used to check if the UTF-8 string zName is a legal
680** unqualified name for a new schema object (table, index, view or
681** trigger). All names are legal except those that begin with the string
682** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
683** is reserved for internal use.
684*/
685int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000686 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000687 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000688 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000689 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
690 return SQLITE_ERROR;
691 }
692 return SQLITE_OK;
693}
694
695/*
drh75897232000-05-29 14:26:00 +0000696** Begin constructing a new table representation in memory. This is
697** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000698** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000699** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000700** flag is true if the table should be stored in the auxiliary database
701** file instead of in the main database file. This is normally the case
702** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000703** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000704**
drhf57b3392001-10-08 13:22:32 +0000705** The new table record is initialized and put in pParse->pNewTable.
706** As more of the CREATE TABLE statement is parsed, additional action
707** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000708** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000709** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000710*/
danielk19774adee202004-05-08 08:23:19 +0000711void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000712 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000713 Token *pName1, /* First part of the name of the table or view */
714 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000715 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000716 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000717 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000718 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000719){
drh75897232000-05-29 14:26:00 +0000720 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000721 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000722 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000723 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000724 int iDb; /* Database number to create the table in */
725 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000726
danielk1977cbb18d22004-05-28 11:37:27 +0000727 /* The table or view name to create is passed to this routine via tokens
728 ** pName1 and pName2. If the table name was fully qualified, for example:
729 **
730 ** CREATE TABLE xxx.yyy (...);
731 **
732 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
733 ** the table name is not fully qualified, i.e.:
734 **
735 ** CREATE TABLE yyy(...);
736 **
737 ** Then pName1 is set to "yyy" and pName2 is "".
738 **
739 ** The call below sets the pName pointer to point at the token (pName1 or
740 ** pName2) that stores the unqualified table name. The variable iDb is
741 ** set to the index of the database that the table or view is to be
742 ** created in.
743 */
danielk1977ef2cb632004-05-29 02:37:19 +0000744 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000745 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000746 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000747 /* If creating a temp table, the name may not be qualified */
748 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000749 return;
750 }
danielk197753c0f742005-03-29 03:10:59 +0000751 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000752
753 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000754 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000755 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000756 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000757 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000758 }
drh1d85d932004-02-14 23:05:52 +0000759 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000760#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000761 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000762 {
763 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000764 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000765 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000766 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000767 }
drhe5f9c642003-01-13 23:27:31 +0000768 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000769 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000770 code = SQLITE_CREATE_TEMP_VIEW;
771 }else{
772 code = SQLITE_CREATE_VIEW;
773 }
774 }else{
danielk197753c0f742005-03-29 03:10:59 +0000775 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000776 code = SQLITE_CREATE_TEMP_TABLE;
777 }else{
778 code = SQLITE_CREATE_TABLE;
779 }
780 }
danielk1977f1a381e2006-06-16 08:01:02 +0000781 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000782 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000783 }
784 }
785#endif
drhf57b3392001-10-08 13:22:32 +0000786
drhf57b3392001-10-08 13:22:32 +0000787 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000788 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000789 ** it does. The exception is if the statement being parsed was passed
790 ** to an sqlite3_declare_vtab() call. In that case only the column names
791 ** and types will be used, so there is no need to test for namespace
792 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000793 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000794 if( !IN_DECLARE_VTAB ){
795 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
796 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000797 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000798 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
799 if( pTable ){
800 if( !noErr ){
801 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
802 }
803 goto begin_table_error;
804 }
805 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
806 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
807 goto begin_table_error;
808 }
drh75897232000-05-29 14:26:00 +0000809 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000810
danielk197726783a52007-08-29 14:06:22 +0000811 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000812 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000813 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000814 pParse->rc = SQLITE_NOMEM;
815 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000816 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000817 }
drh75897232000-05-29 14:26:00 +0000818 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000819 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000820 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000821 pTable->nRef = 1;
drhc4a64fa2009-05-11 20:53:28 +0000822 pTable->dbMem = 0;
823 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000824 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000825
drh4794f732004-11-05 17:17:50 +0000826 /* If this is the magic sqlite_sequence table used by autoincrement,
827 ** then record a pointer to this table in the main database structure
828 ** so that INSERT can find the table easily.
829 */
830#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000831 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000832 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000833 }
834#endif
835
drh17f71932002-02-21 12:01:27 +0000836 /* Begin generating the code that will insert the table record into
837 ** the SQLITE_MASTER table. Note in particular that we must go ahead
838 ** and allocate the record number for the table entry now. Before any
839 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
840 ** indices to be created and the table record must come before the
841 ** indices. Hence, the record number for the table must be allocated
842 ** now.
843 */
danielk19774adee202004-05-08 08:23:19 +0000844 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000845 int j1;
drhe321c292006-01-12 01:56:43 +0000846 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000847 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000848 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000849
danielk197720b1eaf2006-07-26 16:22:14 +0000850#ifndef SQLITE_OMIT_VIRTUALTABLE
851 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000852 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000853 }
854#endif
855
danielk197736963fd2005-02-19 08:18:05 +0000856 /* If the file format and encoding in the database have not been set,
857 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000858 */
drhb7654112008-01-12 12:48:07 +0000859 reg1 = pParse->regRowid = ++pParse->nMem;
860 reg2 = pParse->regRoot = ++pParse->nMem;
861 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000862 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000863 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000864 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000865 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000866 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000867 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000868 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000869 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000870 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000871 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000872
drh4794f732004-11-05 17:17:50 +0000873 /* This just creates a place-holder record in the sqlite_master table.
874 ** The record created does not contain anything yet. It will be replaced
875 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000876 **
drh0fa991b2009-03-21 16:19:26 +0000877 ** The rowid for the new entry is left in register pParse->regRowid.
878 ** The root page number of the new table is left in reg pParse->regRoot.
879 ** The rowid and root page number values are needed by the code that
880 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000881 */
danielk1977f1a381e2006-06-16 08:01:02 +0000882#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
883 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000884 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000885 }else
886#endif
887 {
drhb7654112008-01-12 12:48:07 +0000888 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000889 }
danielk1977c00da102006-01-07 13:21:04 +0000890 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000891 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
892 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
893 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
894 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000895 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000896 }
drh23bf66d2004-12-14 03:34:34 +0000897
898 /* Normal (non-error) return. */
899 return;
900
901 /* If an error occurs, we jump here */
902begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000903 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000904 return;
drh75897232000-05-29 14:26:00 +0000905}
906
907/*
danielk1977c60e9b82005-01-31 12:42:29 +0000908** This macro is used to compare two strings in a case-insensitive manner.
909** It is slightly faster than calling sqlite3StrICmp() directly, but
910** produces larger code.
911**
912** WARNING: This macro is not compatible with the strcmp() family. It
913** returns true if the two strings are equal, otherwise false.
914*/
915#define STRICMP(x, y) (\
916sqlite3UpperToLower[*(unsigned char *)(x)]== \
917sqlite3UpperToLower[*(unsigned char *)(y)] \
918&& sqlite3StrICmp((x)+1,(y)+1)==0 )
919
920/*
drh75897232000-05-29 14:26:00 +0000921** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000922**
923** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000924** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000925** first to get things going. Then this routine is called for each
926** column.
drh75897232000-05-29 14:26:00 +0000927*/
danielk19774adee202004-05-08 08:23:19 +0000928void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000929 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000930 int i;
drha99db3b2004-06-19 14:49:12 +0000931 char *z;
drhc9b84a12002-06-20 11:36:48 +0000932 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000933 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000934 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000935#if SQLITE_MAX_COLUMN
936 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000937 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
938 return;
939 }
drhbb4957f2008-03-20 14:03:29 +0000940#endif
danielk1977ae74e032008-12-23 11:11:51 +0000941 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000942 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000943 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000944 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000945 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000946 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000947 return;
948 }
949 }
drh75897232000-05-29 14:26:00 +0000950 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000951 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000952 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000953 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000954 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000955 return;
956 }
drh6d4abfb2001-10-22 02:58:08 +0000957 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000958 }
drhc9b84a12002-06-20 11:36:48 +0000959 pCol = &p->aCol[p->nCol];
960 memset(pCol, 0, sizeof(p->aCol[0]));
961 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000962
963 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000964 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
965 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000966 */
danielk19774f057f92004-06-08 00:02:33 +0000967 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000968 p->nCol++;
drh75897232000-05-29 14:26:00 +0000969}
970
971/*
drh382c0242001-10-06 16:33:02 +0000972** This routine is called by the parser while in the middle of
973** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
974** been seen on a column. This routine sets the notNull flag on
975** the column currently under construction.
976*/
danielk19774adee202004-05-08 08:23:19 +0000977void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000978 Table *p;
drhc4a64fa2009-05-11 20:53:28 +0000979 p = pParse->pNewTable;
980 if( p==0 || NEVER(p->nCol<1) ) return;
981 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000982}
983
984/*
danielk197752a83fb2005-01-31 12:56:44 +0000985** Scan the column type name zType (length nType) and return the
986** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000987**
988** This routine does a case-independent search of zType for the
989** substrings in the following table. If one of the substrings is
990** found, the corresponding affinity is returned. If zType contains
991** more than one of the substrings, entries toward the top of
992** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000993** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000994**
995** Substring | Affinity
996** --------------------------------
997** 'INT' | SQLITE_AFF_INTEGER
998** 'CHAR' | SQLITE_AFF_TEXT
999** 'CLOB' | SQLITE_AFF_TEXT
1000** 'TEXT' | SQLITE_AFF_TEXT
1001** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001002** 'REAL' | SQLITE_AFF_REAL
1003** 'FLOA' | SQLITE_AFF_REAL
1004** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001005**
1006** If none of the substrings in the above table are found,
1007** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001008*/
drhb7916a72009-05-27 10:31:29 +00001009char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +00001010 u32 h = 0;
1011 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +00001012
drhb7916a72009-05-27 10:31:29 +00001013 if( zIn ) while( zIn[0] ){
1014 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001015 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001016 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1017 aff = SQLITE_AFF_TEXT;
1018 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1019 aff = SQLITE_AFF_TEXT;
1020 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1021 aff = SQLITE_AFF_TEXT;
1022 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001023 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001024 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001025#ifndef SQLITE_OMIT_FLOATING_POINT
1026 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1027 && aff==SQLITE_AFF_NUMERIC ){
1028 aff = SQLITE_AFF_REAL;
1029 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1030 && aff==SQLITE_AFF_NUMERIC ){
1031 aff = SQLITE_AFF_REAL;
1032 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1033 && aff==SQLITE_AFF_NUMERIC ){
1034 aff = SQLITE_AFF_REAL;
1035#endif
danielk1977201f7162005-02-01 02:13:29 +00001036 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001037 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001038 break;
danielk197752a83fb2005-01-31 12:56:44 +00001039 }
1040 }
danielk1977b3dff962005-02-01 01:21:55 +00001041
1042 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001043}
1044
1045/*
drh382c0242001-10-06 16:33:02 +00001046** This routine is called by the parser while in the middle of
1047** parsing a CREATE TABLE statement. The pFirst token is the first
1048** token in the sequence of tokens that describe the type of the
1049** column currently under construction. pLast is the last token
1050** in the sequence. Use this information to construct a string
1051** that contains the typename of the column and store that string
1052** in zType.
1053*/
drh487e2622005-06-25 18:42:14 +00001054void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001055 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001056 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001057
drhc4a64fa2009-05-11 20:53:28 +00001058 p = pParse->pNewTable;
1059 if( p==0 || NEVER(p->nCol<1) ) return;
1060 pCol = &p->aCol[p->nCol-1];
1061 assert( pCol->zType==0 );
1062 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001063 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001064}
1065
1066/*
danielk19777977a172004-11-09 12:44:37 +00001067** The expression is the default value for the most recently added column
1068** of the table currently under construction.
1069**
1070** Default value expressions must be constant. Raise an exception if this
1071** is not the case.
drhd9b02572001-04-15 00:37:09 +00001072**
1073** This routine is called by the parser while in the middle of
1074** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001075*/
drhb7916a72009-05-27 10:31:29 +00001076void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001077 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001078 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001079 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001080 p = pParse->pNewTable;
1081 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001082 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001083 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001084 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1085 pCol->zName);
1086 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001087 /* A copy of pExpr is used instead of the original, as pExpr contains
1088 ** tokens that point to volatile memory. The 'span' of the expression
1089 ** is required by pragma table_info.
1090 */
drh633e6d52008-07-28 19:34:53 +00001091 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001092 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1093 sqlite3DbFree(db, pCol->zDflt);
1094 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001095 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001096 }
danielk19777977a172004-11-09 12:44:37 +00001097 }
drhb7916a72009-05-27 10:31:29 +00001098 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001099}
1100
1101/*
drh4a324312001-12-21 14:30:42 +00001102** Designate the PRIMARY KEY for the table. pList is a list of names
1103** of columns that form the primary key. If pList is NULL, then the
1104** most recently added column of the table is the primary key.
1105**
1106** A table can have at most one primary key. If the table already has
1107** a primary key (and this is the second primary key) then create an
1108** error.
1109**
1110** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001111** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001112** field of the table under construction to be the index of the
1113** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1114** no INTEGER PRIMARY KEY.
1115**
1116** If the key is not an INTEGER PRIMARY KEY, then create a unique
1117** index for the key. No index is created for INTEGER PRIMARY KEYs.
1118*/
drh205f48e2004-11-05 00:43:11 +00001119void sqlite3AddPrimaryKey(
1120 Parse *pParse, /* Parsing context */
1121 ExprList *pList, /* List of field names to be indexed */
1122 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001123 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1124 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001125){
drh4a324312001-12-21 14:30:42 +00001126 Table *pTab = pParse->pNewTable;
1127 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001128 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001129 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001130 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001131 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001132 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001133 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001134 }
drh7d10d5a2008-08-20 16:35:10 +00001135 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001136 if( pList==0 ){
1137 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001138 pTab->aCol[iCol].isPrimKey = 1;
1139 }else{
danielk19770202b292004-06-09 09:55:16 +00001140 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001141 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001142 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1143 break;
1144 }
drh78100cc2003-08-23 22:40:53 +00001145 }
drh6e4fc2c2005-09-15 21:24:51 +00001146 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001147 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001148 }
drh4a324312001-12-21 14:30:42 +00001149 }
danielk19770202b292004-06-09 09:55:16 +00001150 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001151 }
1152 if( iCol>=0 && iCol<pTab->nCol ){
1153 zType = pTab->aCol[iCol].zType;
1154 }
drhfdd6e852005-12-16 01:06:16 +00001155 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1156 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001157 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001158 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001159 assert( autoInc==0 || autoInc==1 );
1160 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001161 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001162#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001163 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1164 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001165#endif
drh4a324312001-12-21 14:30:42 +00001166 }else{
drh4d91a702006-01-04 15:54:36 +00001167 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001168 pList = 0;
drh4a324312001-12-21 14:30:42 +00001169 }
drhe0194f22003-02-26 13:52:51 +00001170
1171primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001172 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001173 return;
drh4a324312001-12-21 14:30:42 +00001174}
1175
1176/*
drhffe07b22005-11-03 00:41:17 +00001177** Add a new CHECK constraint to the table currently under construction.
1178*/
1179void sqlite3AddCheckConstraint(
1180 Parse *pParse, /* Parsing context */
1181 Expr *pCheckExpr /* The check expression */
1182){
drh633e6d52008-07-28 19:34:53 +00001183 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001184#ifndef SQLITE_OMIT_CHECK
1185 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001186 if( pTab && !IN_DECLARE_VTAB ){
drh33e619f2009-05-28 01:00:55 +00001187 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1188 }else
drhffe07b22005-11-03 00:41:17 +00001189#endif
drh33e619f2009-05-28 01:00:55 +00001190 {
1191 sqlite3ExprDelete(db, pCheckExpr);
1192 }
drhffe07b22005-11-03 00:41:17 +00001193}
1194
1195/*
drhd3d39e92004-05-20 22:16:29 +00001196** Set the collation function of the most recently parsed table column
1197** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001198*/
danielk197739002502007-11-12 09:50:26 +00001199void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001200 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001201 int i;
danielk197739002502007-11-12 09:50:26 +00001202 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001203 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001204
danielk1977b8cbb872006-06-19 05:33:45 +00001205 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001206 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001207 db = pParse->db;
1208 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001209 if( !zColl ) return;
1210
drhc4a64fa2009-05-11 20:53:28 +00001211 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001212 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001213 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001214
1215 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1216 ** then an index may have been created on this column before the
1217 ** collation type was added. Correct this if it is the case.
1218 */
1219 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1220 assert( pIdx->nColumn==1 );
1221 if( pIdx->aiColumn[0]==i ){
1222 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001223 }
1224 }
danielk197739002502007-11-12 09:50:26 +00001225 }else{
drh633e6d52008-07-28 19:34:53 +00001226 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001227 }
danielk19777cedc8d2004-06-10 10:50:08 +00001228}
1229
danielk1977466be562004-06-10 02:16:01 +00001230/*
1231** This function returns the collation sequence for database native text
1232** encoding identified by the string zName, length nName.
1233**
1234** If the requested collation sequence is not available, or not available
1235** in the database native encoding, the collation factory is invoked to
1236** request it. If the collation factory does not supply such a sequence,
1237** and the sequence is available in another text encoding, then that is
1238** returned instead.
1239**
1240** If no versions of the requested collations sequence are available, or
1241** another error occurs, NULL is returned and an error message written into
1242** pParse.
drha34001c2007-02-02 12:44:37 +00001243**
1244** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1245** invokes the collation factory if the named collation cannot be found
1246** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001247**
1248** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001249*/
drhc4a64fa2009-05-11 20:53:28 +00001250CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001251 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001252 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001253 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001254 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001255
drhc4a64fa2009-05-11 20:53:28 +00001256 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001257 if( !initbusy && (!pColl || !pColl->xCmp) ){
drhc4a64fa2009-05-11 20:53:28 +00001258 pColl = sqlite3GetCollSeq(db, pColl, zName);
danielk19774dade032005-05-25 10:45:10 +00001259 if( !pColl ){
drhc4a64fa2009-05-11 20:53:28 +00001260 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
danielk1977466be562004-06-10 02:16:01 +00001261 }
1262 }
1263
danielk19770202b292004-06-09 09:55:16 +00001264 return pColl;
1265}
1266
1267
drh8e2ca022002-06-17 17:07:19 +00001268/*
drh3f7d4e42004-07-24 14:35:58 +00001269** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001270**
1271** The schema cookie is used to determine when the schema for the
1272** database changes. After each schema change, the cookie value
1273** changes. When a process first reads the schema it records the
1274** cookie. Thereafter, whenever it goes to access the database,
1275** it checks the cookie to make sure the schema has not changed
1276** since it was last read.
1277**
1278** This plan is not completely bullet-proof. It is possible for
1279** the schema to change multiple times and for the cookie to be
1280** set back to prior value. But schema changes are infrequent
1281** and the probability of hitting the same cookie value is only
1282** 1 chance in 2^32. So we're safe enough.
1283*/
drh9cbf3422008-01-17 16:22:13 +00001284void sqlite3ChangeCookie(Parse *pParse, int iDb){
1285 int r1 = sqlite3GetTempReg(pParse);
1286 sqlite3 *db = pParse->db;
1287 Vdbe *v = pParse->pVdbe;
1288 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001289 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001290 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001291}
1292
1293/*
drh969fa7c2002-02-18 18:30:32 +00001294** Measure the number of characters needed to output the given
1295** identifier. The number returned includes any quotes used
1296** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001297**
1298** The estimate is conservative. It might be larger that what is
1299** really needed.
drh969fa7c2002-02-18 18:30:32 +00001300*/
1301static int identLength(const char *z){
1302 int n;
drh17f71932002-02-21 12:01:27 +00001303 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001304 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001305 }
drh234c39d2004-07-24 03:30:47 +00001306 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001307}
1308
1309/*
danielk19771b870de2009-03-14 08:37:23 +00001310** The first parameter is a pointer to an output buffer. The second
1311** parameter is a pointer to an integer that contains the offset at
1312** which to write into the output buffer. This function copies the
1313** nul-terminated string pointed to by the third parameter, zSignedIdent,
1314** to the specified offset in the buffer and updates *pIdx to refer
1315** to the first byte after the last byte written before returning.
1316**
1317** If the string zSignedIdent consists entirely of alpha-numeric
1318** characters, does not begin with a digit and is not an SQL keyword,
1319** then it is copied to the output buffer exactly as it is. Otherwise,
1320** it is quoted using double-quotes.
1321*/
drhc4a64fa2009-05-11 20:53:28 +00001322static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001323 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001324 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001325 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001326
drh17f71932002-02-21 12:01:27 +00001327 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001328 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001329 }
danielk19771b870de2009-03-14 08:37:23 +00001330 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1331 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001332 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001333 }
1334
drh234c39d2004-07-24 03:30:47 +00001335 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001336 for(j=0; zIdent[j]; j++){
1337 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001338 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001339 }
drh234c39d2004-07-24 03:30:47 +00001340 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001341 z[i] = 0;
1342 *pIdx = i;
1343}
1344
1345/*
1346** Generate a CREATE TABLE statement appropriate for the given
1347** table. Memory to hold the text of the statement is obtained
1348** from sqliteMalloc() and must be freed by the calling function.
1349*/
drh1d34fde2009-02-03 15:50:33 +00001350static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001351 int i, k, n;
1352 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001353 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001354 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001355 n = 0;
drh234c39d2004-07-24 03:30:47 +00001356 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001357 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001358 }
1359 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001360 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001361 zSep = "";
1362 zSep2 = ",";
1363 zEnd = ")";
1364 }else{
1365 zSep = "\n ";
1366 zSep2 = ",\n ";
1367 zEnd = "\n)";
1368 }
drhe0bc4042002-06-25 01:09:11 +00001369 n += 35 + 6*p->nCol;
drhe5ae5732008-06-15 02:51:47 +00001370 zStmt = sqlite3Malloc( n );
drh820a9062008-01-31 13:35:48 +00001371 if( zStmt==0 ){
1372 db->mallocFailed = 1;
1373 return 0;
1374 }
drhbdb339f2009-02-02 18:03:21 +00001375 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001376 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001377 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001378 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001379 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001380 static const char * const azType[] = {
1381 /* SQLITE_AFF_TEXT */ " TEXT",
1382 /* SQLITE_AFF_NONE */ "",
1383 /* SQLITE_AFF_NUMERIC */ " NUM",
1384 /* SQLITE_AFF_INTEGER */ " INT",
1385 /* SQLITE_AFF_REAL */ " REAL"
1386 };
1387 int len;
1388 const char *zType;
1389
drh5bb3eb92007-05-04 13:15:55 +00001390 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001391 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001392 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001393 identPut(zStmt, &k, pCol->zName);
1394 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1395 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
1396 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1397 testcase( pCol->affinity==SQLITE_AFF_NONE );
1398 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1399 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1400 testcase( pCol->affinity==SQLITE_AFF_REAL );
1401
1402 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1403 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001404 assert( pCol->affinity==SQLITE_AFF_NONE
1405 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001406 memcpy(&zStmt[k], zType, len);
1407 k += len;
1408 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001409 }
drh5bb3eb92007-05-04 13:15:55 +00001410 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001411 return zStmt;
1412}
1413
1414/*
drh75897232000-05-29 14:26:00 +00001415** This routine is called to report the final ")" that terminates
1416** a CREATE TABLE statement.
1417**
drhf57b3392001-10-08 13:22:32 +00001418** The table structure that other action routines have been building
1419** is added to the internal hash tables, assuming no errors have
1420** occurred.
drh75897232000-05-29 14:26:00 +00001421**
drh1d85d932004-02-14 23:05:52 +00001422** An entry for the table is made in the master table on disk, unless
1423** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001424** it means we are reading the sqlite_master table because we just
1425** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001426** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001427** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001428**
1429** If the pSelect argument is not NULL, it means that this routine
1430** was called to create a table generated from a
1431** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1432** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001433*/
danielk197719a8e7e2005-03-17 05:03:38 +00001434void sqlite3EndTable(
1435 Parse *pParse, /* Parse context */
1436 Token *pCons, /* The ',' token after the last column defn. */
1437 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1438 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1439){
drh75897232000-05-29 14:26:00 +00001440 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001441 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001442 int iDb;
drh75897232000-05-29 14:26:00 +00001443
drh8af73d42009-05-13 22:58:28 +00001444 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001445 return;
1446 }
drh28037572000-08-02 13:47:41 +00001447 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001448 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001449
danielk1977517eb642004-06-07 10:00:31 +00001450 assert( !db->init.busy || !pSelect );
1451
drhb9bb7c12006-06-11 23:41:55 +00001452 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001453
drhffe07b22005-11-03 00:41:17 +00001454#ifndef SQLITE_OMIT_CHECK
1455 /* Resolve names in all CHECK constraint expressions.
1456 */
1457 if( p->pCheck ){
1458 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1459 NameContext sNC; /* Name context for pParse->pNewTable */
1460
1461 memset(&sNC, 0, sizeof(sNC));
1462 memset(&sSrc, 0, sizeof(sSrc));
1463 sSrc.nSrc = 1;
1464 sSrc.a[0].zName = p->zName;
1465 sSrc.a[0].pTab = p;
1466 sSrc.a[0].iCursor = -1;
1467 sNC.pParse = pParse;
1468 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001469 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001470 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001471 return;
1472 }
1473 }
1474#endif /* !defined(SQLITE_OMIT_CHECK) */
1475
drh1d85d932004-02-14 23:05:52 +00001476 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001477 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1478 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001479 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001480 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001481 */
drh1d85d932004-02-14 23:05:52 +00001482 if( db->init.busy ){
1483 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001484 }
1485
drhe3c41372001-09-17 20:25:58 +00001486 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001487 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001488 **
drhe0bc4042002-06-25 01:09:11 +00001489 ** If this is a TEMPORARY table, write the entry into the auxiliary
1490 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001491 */
drh1d85d932004-02-14 23:05:52 +00001492 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001493 int n;
drhd8bc7082000-06-07 23:51:50 +00001494 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001495 char *zType; /* "view" or "table" */
1496 char *zType2; /* "VIEW" or "TABLE" */
1497 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001498
danielk19774adee202004-05-08 08:23:19 +00001499 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001500 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001501
drh66a51672008-01-03 00:01:23 +00001502 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001503
drh0fa991b2009-03-21 16:19:26 +00001504 /*
1505 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001506 */
drh4ff6dfa2002-03-03 23:06:00 +00001507 if( p->pSelect==0 ){
1508 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001509 zType = "table";
1510 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001511#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001512 }else{
1513 /* A view */
drh4794f732004-11-05 17:17:50 +00001514 zType = "view";
1515 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001516#endif
drh4ff6dfa2002-03-03 23:06:00 +00001517 }
danielk1977517eb642004-06-07 10:00:31 +00001518
danielk1977517eb642004-06-07 10:00:31 +00001519 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1520 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001521 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001522 **
1523 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1524 ** suitable state to query for the column names and types to be used
1525 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001526 **
1527 ** A shared-cache write-lock is not required to write to the new table,
1528 ** as a schema-lock must have already been obtained to create it. Since
1529 ** a schema-lock excludes all other database users, the write-lock would
1530 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001531 */
1532 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001533 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001534 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001535
danielk19776ab3a2e2009-02-19 14:39:25 +00001536 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001537 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001538 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001539 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001540 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001541 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001542 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001543 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001544 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001545 if( pSelTab==0 ) return;
1546 assert( p->aCol==0 );
1547 p->nCol = pSelTab->nCol;
1548 p->aCol = pSelTab->aCol;
1549 pSelTab->nCol = 0;
1550 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001551 sqlite3DeleteTable(pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001552 }
1553 }
drh4794f732004-11-05 17:17:50 +00001554
drh4794f732004-11-05 17:17:50 +00001555 /* Compute the complete text of the CREATE statement */
1556 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001557 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001558 }else{
drh1bd10f82008-12-10 21:19:56 +00001559 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001560 zStmt = sqlite3MPrintf(db,
1561 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1562 );
drh4794f732004-11-05 17:17:50 +00001563 }
1564
1565 /* A slot for the record has already been allocated in the
1566 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001567 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001568 */
1569 sqlite3NestedParse(pParse,
1570 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001571 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1572 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001573 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001574 zType,
1575 p->zName,
1576 p->zName,
drhb7654112008-01-12 12:48:07 +00001577 pParse->regRoot,
1578 zStmt,
1579 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001580 );
drh633e6d52008-07-28 19:34:53 +00001581 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001582 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001583
1584#ifndef SQLITE_OMIT_AUTOINCREMENT
1585 /* Check to see if we need to create an sqlite_sequence table for
1586 ** keeping track of autoincrement keys.
1587 */
drh7d10d5a2008-08-20 16:35:10 +00001588 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001589 Db *pDb = &db->aDb[iDb];
1590 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001591 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001592 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1593 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001594 );
1595 }
1596 }
1597#endif
drh4794f732004-11-05 17:17:50 +00001598
1599 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001600 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1601 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001602 }
drh17e9e292003-02-01 13:53:28 +00001603
drh2958a4e2004-11-12 03:56:15 +00001604
drh17e9e292003-02-01 13:53:28 +00001605 /* Add the table to the in-memory representation of the database.
1606 */
drh8af73d42009-05-13 22:58:28 +00001607 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001608 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001609 Schema *pSchema = p->pSchema;
drhea678832008-12-10 19:26:22 +00001610 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001611 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001612 if( pOld ){
1613 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001614 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001615 return;
1616 }
drh17e9e292003-02-01 13:53:28 +00001617 pParse->pNewTable = 0;
1618 db->nTable++;
1619 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001620
1621#ifndef SQLITE_OMIT_ALTERTABLE
1622 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001623 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001624 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001625 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001626 if( pCons->z==0 ){
1627 pCons = pEnd;
1628 }
drh1bd10f82008-12-10 21:19:56 +00001629 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001630 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001631 }
1632#endif
drh17e9e292003-02-01 13:53:28 +00001633 }
drh75897232000-05-29 14:26:00 +00001634}
1635
drhb7f91642004-10-31 02:22:47 +00001636#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001637/*
drha76b5df2002-02-23 02:32:10 +00001638** The parser calls this routine in order to create a new VIEW
1639*/
danielk19774adee202004-05-08 08:23:19 +00001640void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001641 Parse *pParse, /* The parsing context */
1642 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001643 Token *pName1, /* The token that holds the name of the view */
1644 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001645 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001646 int isTemp, /* TRUE for a TEMPORARY view */
1647 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001648){
drha76b5df2002-02-23 02:32:10 +00001649 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001650 int n;
drhb7916a72009-05-27 10:31:29 +00001651 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001652 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001653 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001654 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001655 int iDb;
drh17435752007-08-16 04:30:38 +00001656 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001657
drh7c3d64f2005-06-06 15:32:08 +00001658 if( pParse->nVar>0 ){
1659 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001660 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001661 return;
1662 }
drhfdd48a72006-09-11 23:45:48 +00001663 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001664 p = pParse->pNewTable;
drh8af73d42009-05-13 22:58:28 +00001665 if( p==0 ){
drh633e6d52008-07-28 19:34:53 +00001666 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001667 return;
1668 }
drh8af73d42009-05-13 22:58:28 +00001669 assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
1670 ** there could not have been an error */
danielk1977ef2cb632004-05-29 02:37:19 +00001671 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001672 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001673 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001674 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001675 ){
drh633e6d52008-07-28 19:34:53 +00001676 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001677 return;
1678 }
drh174b6192002-12-03 02:22:52 +00001679
drh4b59ab52002-08-24 18:24:51 +00001680 /* Make a copy of the entire SELECT statement that defines the view.
1681 ** This will force all the Expr.token.z values to be dynamically
1682 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001683 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001684 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001685 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001686 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001687 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001688 return;
1689 }
drh17435752007-08-16 04:30:38 +00001690 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001691 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001692 }
drh4b59ab52002-08-24 18:24:51 +00001693
1694 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1695 ** the end.
1696 */
drha76b5df2002-02-23 02:32:10 +00001697 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001698 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001699 sEnd.z += sEnd.n;
1700 }
1701 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001702 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001703 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001704 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001705 sEnd.z = &z[n-1];
1706 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001707
danielk19774adee202004-05-08 08:23:19 +00001708 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001709 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001710 return;
drh417be792002-03-03 18:59:40 +00001711}
drhb7f91642004-10-31 02:22:47 +00001712#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001713
danielk1977fe3fcbe22006-06-12 12:08:45 +00001714#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001715/*
1716** The Table structure pTable is really a VIEW. Fill in the names of
1717** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001718** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001719*/
danielk19774adee202004-05-08 08:23:19 +00001720int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001721 Table *pSelTab; /* A fake table from which we get the result set */
1722 Select *pSel; /* Copy of the SELECT that implements the view */
1723 int nErr = 0; /* Number of errors encountered */
1724 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001725 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001726 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001727
1728 assert( pTable );
1729
danielk1977fe3fcbe22006-06-12 12:08:45 +00001730#ifndef SQLITE_OMIT_VIRTUALTABLE
1731 if( sqlite3VtabCallConnect(pParse, pTable) ){
1732 return SQLITE_ERROR;
1733 }
drh4cbdda92006-06-14 19:00:20 +00001734 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001735#endif
1736
1737#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001738 /* A positive nCol means the columns names for this view are
1739 ** already known.
1740 */
1741 if( pTable->nCol>0 ) return 0;
1742
1743 /* A negative nCol is a special marker meaning that we are currently
1744 ** trying to compute the column names. If we enter this routine with
1745 ** a negative nCol, it means two or more views form a loop, like this:
1746 **
1747 ** CREATE VIEW one AS SELECT * FROM two;
1748 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001749 **
drh768578e2009-05-12 00:40:12 +00001750 ** Actually, the error above is now caught prior to reaching this point.
1751 ** But the following test is still important as it does come up
1752 ** in the following:
1753 **
1754 ** CREATE TABLE main.ex1(a);
1755 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1756 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001757 */
1758 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001759 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001760 return 1;
1761 }
drh85c23c62005-08-20 03:03:04 +00001762 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001763
1764 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001765 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1766 ** "*" elements in the results set of the view and will assign cursors
1767 ** to the elements of the FROM clause. But we do not want these changes
1768 ** to be permanent. So the computation is done on a copy of the SELECT
1769 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001770 */
drh9b3187e2005-01-18 14:45:47 +00001771 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001772 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001773 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001774 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001775 n = pParse->nTab;
1776 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1777 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001778 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001779#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001780 xAuth = db->xAuth;
1781 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001782 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001783 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001784#else
drh7d10d5a2008-08-20 16:35:10 +00001785 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001786#endif
drhd9da78a2009-03-24 15:08:09 +00001787 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001788 pParse->nTab = n;
1789 if( pSelTab ){
1790 assert( pTable->aCol==0 );
1791 pTable->nCol = pSelTab->nCol;
1792 pTable->aCol = pSelTab->aCol;
1793 pSelTab->nCol = 0;
1794 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001795 sqlite3DeleteTable(pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001796 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001797 }else{
1798 pTable->nCol = 0;
1799 nErr++;
1800 }
drh633e6d52008-07-28 19:34:53 +00001801 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001802 } else {
drh417be792002-03-03 18:59:40 +00001803 nErr++;
1804 }
drhb7f91642004-10-31 02:22:47 +00001805#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001806 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001807}
1808#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001809
drhb7f91642004-10-31 02:22:47 +00001810#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001811/*
drh8bf8dc92003-05-17 17:35:10 +00001812** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001813*/
drh9bb575f2004-09-06 17:24:11 +00001814static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001815 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001816 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001817 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001818 Table *pTab = sqliteHashData(i);
1819 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001820 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001821 }
1822 }
drh8bf8dc92003-05-17 17:35:10 +00001823 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001824}
drhb7f91642004-10-31 02:22:47 +00001825#else
1826# define sqliteViewResetAll(A,B)
1827#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001828
drh75897232000-05-29 14:26:00 +00001829/*
danielk1977a0bf2652004-11-04 14:30:04 +00001830** This function is called by the VDBE to adjust the internal schema
1831** used by SQLite when the btree layer moves a table root page. The
1832** root-page of a table or index in database iDb has changed from iFrom
1833** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001834**
1835** Ticket #1728: The symbol table might still contain information
1836** on tables and/or indices that are the process of being deleted.
1837** If you are unlucky, one of those deleted indices or tables might
1838** have the same rootpage number as the real table or index that is
1839** being moved. So we cannot stop searching after the first match
1840** because the first match might be for one of the deleted indices
1841** or tables and not the table/index that is actually being moved.
1842** We must continue looping until all tables and indices with
1843** rootpage==iFrom have been converted to have a rootpage of iTo
1844** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001845*/
1846#ifndef SQLITE_OMIT_AUTOVACUUM
1847void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1848 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001849 Hash *pHash;
1850
1851 pHash = &pDb->pSchema->tblHash;
1852 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001853 Table *pTab = sqliteHashData(pElem);
1854 if( pTab->tnum==iFrom ){
1855 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001856 }
1857 }
danielk1977da184232006-01-05 11:34:32 +00001858 pHash = &pDb->pSchema->idxHash;
1859 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001860 Index *pIdx = sqliteHashData(pElem);
1861 if( pIdx->tnum==iFrom ){
1862 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001863 }
1864 }
danielk1977a0bf2652004-11-04 14:30:04 +00001865}
1866#endif
1867
1868/*
1869** Write code to erase the table with root-page iTable from database iDb.
1870** Also write code to modify the sqlite_master table and internal schema
1871** if a root-page of another table is moved by the btree-layer whilst
1872** erasing iTable (this can happen with an auto-vacuum database).
1873*/
drh4e0cff62004-11-05 05:10:28 +00001874static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1875 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001876 int r1 = sqlite3GetTempReg(pParse);
1877 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
drh40e016e2004-11-04 14:47:11 +00001878#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001879 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001880 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001881 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001882 ** reflect this.
1883 **
drh0fa991b2009-03-21 16:19:26 +00001884 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001885 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1886 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001887 */
danielk197763e3e9f2004-11-05 09:19:27 +00001888 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001889 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1890 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001891#endif
drhb7654112008-01-12 12:48:07 +00001892 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001893}
1894
1895/*
1896** Write VDBE code to erase table pTab and all associated indices on disk.
1897** Code to update the sqlite_master tables and internal schema definitions
1898** in case a root-page belonging to another table is moved by the btree layer
1899** is also added (this can happen with an auto-vacuum database).
1900*/
drh4e0cff62004-11-05 05:10:28 +00001901static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001902#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001903 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001904 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1905 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001906 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001907 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001908 }
1909#else
1910 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1911 ** is not defined), then it is important to call OP_Destroy on the
1912 ** table and index root-pages in order, starting with the numerically
1913 ** largest root-page number. This guarantees that none of the root-pages
1914 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1915 ** following were coded:
1916 **
1917 ** OP_Destroy 4 0
1918 ** ...
1919 ** OP_Destroy 5 0
1920 **
1921 ** and root page 5 happened to be the largest root-page number in the
1922 ** database, then root page 5 would be moved to page 4 by the
1923 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1924 ** a free-list page.
1925 */
1926 int iTab = pTab->tnum;
1927 int iDestroyed = 0;
1928
1929 while( 1 ){
1930 Index *pIdx;
1931 int iLargest = 0;
1932
1933 if( iDestroyed==0 || iTab<iDestroyed ){
1934 iLargest = iTab;
1935 }
1936 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1937 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001938 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001939 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1940 iLargest = iIdx;
1941 }
1942 }
danielk1977da184232006-01-05 11:34:32 +00001943 if( iLargest==0 ){
1944 return;
1945 }else{
1946 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1947 destroyRootPage(pParse, iLargest, iDb);
1948 iDestroyed = iLargest;
1949 }
danielk1977a0bf2652004-11-04 14:30:04 +00001950 }
1951#endif
1952}
1953
1954/*
drh75897232000-05-29 14:26:00 +00001955** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001956** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001957*/
drha0733842005-12-29 01:11:36 +00001958void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001959 Table *pTab;
drh75897232000-05-29 14:26:00 +00001960 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001961 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001962 int iDb;
drh75897232000-05-29 14:26:00 +00001963
drh8af73d42009-05-13 22:58:28 +00001964 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001965 goto exit_drop_table;
1966 }
drh8af73d42009-05-13 22:58:28 +00001967 assert( pParse->nErr==0 );
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 );
drh8af73d42009-05-13 22:58:28 +00002152 if( p==0 || 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 */
drh8af73d42009-05-13 22:58:28 +00002373 assert( pParse->nErr==0 ); /* Never called with prior errors */
2374 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002375 goto exit_create_index;
2376 }
2377 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002378 goto exit_create_index;
2379 }
drhdaffd0e2001-04-11 14:28:42 +00002380
drh75897232000-05-29 14:26:00 +00002381 /*
2382 ** Find the table that is to be indexed. Return early if not found.
2383 */
danielk1977cbb18d22004-05-28 11:37:27 +00002384 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002385
2386 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002387 ** to search for the table. 'Fix' the table name to this db
2388 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002389 */
2390 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002391 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002392 if( iDb<0 ) goto exit_create_index;
2393
danielk197753c0f742005-03-29 03:10:59 +00002394#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002395 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002396 ** is a temp table. If so, set the database to 1. Do not do this
2397 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002398 */
danielk1977fe910332007-12-02 11:46:34 +00002399 if( !db->init.busy ){
2400 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002401 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002402 iDb = 1;
2403 }
danielk1977ef2cb632004-05-29 02:37:19 +00002404 }
danielk197753c0f742005-03-29 03:10:59 +00002405#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002406
2407 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2408 sqlite3FixSrcList(&sFix, pTblName)
2409 ){
drh85c23c62005-08-20 03:03:04 +00002410 /* Because the parser constructs pTblName from a single identifier,
2411 ** sqlite3FixSrcList can never fail. */
2412 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002413 }
drhca424112008-01-25 15:04:48 +00002414 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002415 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002416 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002417 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002418 }else{
drhe3c41372001-09-17 20:25:58 +00002419 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002420 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002421 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002422 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002423 }
drhfdd6e852005-12-16 01:06:16 +00002424 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002425
drhd3001712009-05-12 17:46:53 +00002426 assert( pTab!=0 );
2427 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002428 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2429 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002430 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002431 goto exit_create_index;
2432 }
danielk1977576ec6b2005-01-21 11:55:25 +00002433#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002434 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002435 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002436 goto exit_create_index;
2437 }
danielk1977576ec6b2005-01-21 11:55:25 +00002438#endif
danielk19775ee9d692006-06-21 12:36:25 +00002439#ifndef SQLITE_OMIT_VIRTUALTABLE
2440 if( IsVirtual(pTab) ){
2441 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2442 goto exit_create_index;
2443 }
2444#endif
drh75897232000-05-29 14:26:00 +00002445
2446 /*
2447 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002448 ** index or table with the same name.
2449 **
2450 ** Exception: If we are reading the names of permanent indices from the
2451 ** sqlite_master table (because some other process changed the schema) and
2452 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002453 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002454 **
2455 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002456 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2457 ** own name.
drh75897232000-05-29 14:26:00 +00002458 */
danielk1977d8123362004-06-12 09:25:12 +00002459 if( pName ){
drh17435752007-08-16 04:30:38 +00002460 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002461 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002462 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002463 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002464 }
danielk1977d8123362004-06-12 09:25:12 +00002465 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002466 if( sqlite3FindTable(db, zName, 0)!=0 ){
2467 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2468 goto exit_create_index;
2469 }
2470 }
danielk197759a33f92007-03-17 10:26:59 +00002471 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2472 if( !ifNotExist ){
2473 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002474 }
danielk197759a33f92007-03-17 10:26:59 +00002475 goto exit_create_index;
2476 }
danielk1977a21c6b62005-01-24 10:25:59 +00002477 }else{
drhadbca9c2001-09-27 15:11:53 +00002478 int n;
2479 Index *pLoop;
2480 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002481 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002482 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002483 goto exit_create_index;
2484 }
drh75897232000-05-29 14:26:00 +00002485 }
2486
drhe5f9c642003-01-13 23:27:31 +00002487 /* Check for authorization to create an index.
2488 */
2489#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002490 {
drhfdd6e852005-12-16 01:06:16 +00002491 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002492 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002493 goto exit_create_index;
2494 }
2495 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002496 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002497 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002498 goto exit_create_index;
2499 }
drhe5f9c642003-01-13 23:27:31 +00002500 }
2501#endif
2502
drh75897232000-05-29 14:26:00 +00002503 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002504 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002505 ** So create a fake list to simulate this.
2506 */
2507 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002508 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002509 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002510 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002511 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002512 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002513 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002514 }
2515
danielk1977b3bf5562006-01-10 17:58:23 +00002516 /* Figure out how many bytes of space are required to store explicitly
2517 ** specified collation sequence names.
2518 */
2519 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002520 Expr *pExpr = pList->a[i].pExpr;
2521 if( pExpr ){
2522 CollSeq *pColl = pExpr->pColl;
2523 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2524 ** failure we have quit before reaching this point. */
2525 if( ALWAYS(pColl) ){
2526 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2527 }
danielk1977b3bf5562006-01-10 17:58:23 +00002528 }
2529 }
2530
drh75897232000-05-29 14:26:00 +00002531 /*
2532 ** Allocate the index structure.
2533 */
drhea678832008-12-10 19:26:22 +00002534 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002535 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002536 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002537 sizeof(Index) + /* Index structure */
2538 sizeof(int)*nCol + /* Index.aiColumn */
2539 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2540 sizeof(char *)*nCol + /* Index.azColl */
2541 sizeof(u8)*nCol + /* Index.aSortOrder */
2542 nName + 1 + /* Index.zName */
2543 nExtra /* Collation sequence names */
2544 );
drh17435752007-08-16 04:30:38 +00002545 if( db->mallocFailed ){
2546 goto exit_create_index;
2547 }
drh78aecb72006-02-10 18:08:09 +00002548 pIndex->azColl = (char**)(&pIndex[1]);
2549 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002550 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002551 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002552 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2553 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002554 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002555 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002556 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002557 pIndex->onError = (u8)onError;
2558 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002559 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002560
drhfdd6e852005-12-16 01:06:16 +00002561 /* Check to see if we should honor DESC requests on index columns
2562 */
danielk1977da184232006-01-05 11:34:32 +00002563 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002564 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002565 }else{
2566 sortOrderMask = 0; /* Ignore DESC */
2567 }
2568
drh1ccde152000-06-17 13:12:39 +00002569 /* Scan the names of the columns of the table to be indexed and
2570 ** load the column indices into the Index structure. Report an error
2571 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002572 **
2573 ** TODO: Add a test to make sure that the same column is not named
2574 ** more than once within the same index. Only the first instance of
2575 ** the column will ever be used by the optimizer. Note that using the
2576 ** same column more than once cannot be an error because that would
2577 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002578 */
drhfdd6e852005-12-16 01:06:16 +00002579 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2580 const char *zColName = pListItem->zName;
2581 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002582 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002583 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002584
drhfdd6e852005-12-16 01:06:16 +00002585 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2586 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002587 }
2588 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002589 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002590 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002591 goto exit_create_index;
2592 }
drh967e8b72000-06-21 13:59:10 +00002593 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002594 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2595 ** the way the "idxlist" non-terminal is constructed by the parser,
2596 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2597 ** must exist or else there must have been an OOM error. But if there
2598 ** was an OOM error, we would never reach this point. */
2599 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2600 int nColl;
2601 zColl = pListItem->pExpr->pColl->zName;
2602 nColl = sqlite3Strlen30(zColl) + 1;
2603 assert( nExtra>=nColl );
2604 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002605 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002606 zExtra += nColl;
2607 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002608 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002609 zColl = pTab->aCol[j].zColl;
2610 if( !zColl ){
2611 zColl = db->pDfltColl->zName;
2612 }
danielk19770202b292004-06-09 09:55:16 +00002613 }
drhb7f24de2009-05-13 17:35:23 +00002614 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002615 goto exit_create_index;
2616 }
danielk1977b3bf5562006-01-10 17:58:23 +00002617 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002618 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002619 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002620 }
drh51147ba2005-07-23 22:59:55 +00002621 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002622
danielk1977d8123362004-06-12 09:25:12 +00002623 if( pTab==pParse->pNewTable ){
2624 /* This routine has been called to create an automatic index as a
2625 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2626 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2627 ** i.e. one of:
2628 **
2629 ** CREATE TABLE t(x PRIMARY KEY, y);
2630 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2631 **
2632 ** Either way, check to see if the table already has such an index. If
2633 ** so, don't bother creating this one. This only applies to
2634 ** automatically created indices. Users can do as they wish with
2635 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002636 **
2637 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2638 ** (and thus suppressing the second one) even if they have different
2639 ** sort orders.
2640 **
2641 ** If there are different collating sequences or if the columns of
2642 ** the constraint occur in different orders, then the constraints are
2643 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002644 */
2645 Index *pIdx;
2646 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2647 int k;
2648 assert( pIdx->onError!=OE_None );
2649 assert( pIdx->autoIndex );
2650 assert( pIndex->onError!=OE_None );
2651
2652 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2653 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002654 const char *z1;
2655 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002656 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002657 z1 = pIdx->azColl[k];
2658 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002659 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002660 }
2661 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002662 if( pIdx->onError!=pIndex->onError ){
2663 /* This constraint creates the same index as a previous
2664 ** constraint specified somewhere in the CREATE TABLE statement.
2665 ** However the ON CONFLICT clauses are different. If both this
2666 ** constraint and the previous equivalent constraint have explicit
2667 ** ON CONFLICT clauses this is an error. Otherwise, use the
2668 ** explicitly specified behaviour for the index.
2669 */
2670 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2671 sqlite3ErrorMsg(pParse,
2672 "conflicting ON CONFLICT clauses specified", 0);
2673 }
2674 if( pIdx->onError==OE_Default ){
2675 pIdx->onError = pIndex->onError;
2676 }
2677 }
danielk1977d8123362004-06-12 09:25:12 +00002678 goto exit_create_index;
2679 }
2680 }
2681 }
2682
drh75897232000-05-29 14:26:00 +00002683 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002684 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002685 */
drh234c39d2004-07-24 03:30:47 +00002686 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002687 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002688 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002689 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002690 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002691 if( p ){
2692 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002693 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002694 goto exit_create_index;
2695 }
drh5e00f6c2001-09-13 13:46:56 +00002696 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002697 if( pTblName!=0 ){
2698 pIndex->tnum = db->init.newTnum;
2699 }
drhd78eeee2001-09-13 16:18:53 +00002700 }
2701
drh1d85d932004-02-14 23:05:52 +00002702 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002703 ** involves writing the index into the master table and filling in the
2704 ** index with the current table contents.
2705 **
drh1d85d932004-02-14 23:05:52 +00002706 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2707 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002708 ** CREATE INDEX statements are read out of the master table. In
2709 ** the latter case the index already exists on disk, which is why
2710 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002711 **
danielk1977cbb18d22004-05-28 11:37:27 +00002712 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002713 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2714 ** has just been created, it contains no data and the index initialization
2715 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002716 */
drhd3001712009-05-12 17:46:53 +00002717 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002718 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002719 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002720 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002721
danielk19774adee202004-05-08 08:23:19 +00002722 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002723 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002724
drhfdd6e852005-12-16 01:06:16 +00002725
drh063336a2004-11-05 20:58:39 +00002726 /* Create the rootpage for the index
2727 */
drhaee128d2005-02-14 20:48:18 +00002728 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002729 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002730
2731 /* Gather the complete text of the CREATE INDEX statement into
2732 ** the zStmt variable
2733 */
drhd3001712009-05-12 17:46:53 +00002734 if( pStart ){
2735 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002736 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002737 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002738 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002739 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002740 pName->z);
2741 }else{
2742 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002743 /* zStmt = sqlite3MPrintf(""); */
2744 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002745 }
drh063336a2004-11-05 20:58:39 +00002746
2747 /* Add an entry in sqlite_master for this index
2748 */
2749 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002750 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002751 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2752 pIndex->zName,
2753 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002754 iMem,
drh063336a2004-11-05 20:58:39 +00002755 zStmt
2756 );
drh633e6d52008-07-28 19:34:53 +00002757 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002758
danielk1977a21c6b62005-01-24 10:25:59 +00002759 /* Fill the index with data and reparse the schema. Code an OP_Expire
2760 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002761 */
danielk1977cbb18d22004-05-28 11:37:27 +00002762 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002763 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002764 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002765 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2766 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2767 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002768 }
drh75897232000-05-29 14:26:00 +00002769 }
2770
danielk1977d8123362004-06-12 09:25:12 +00002771 /* When adding an index to the list of indices for a table, make
2772 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002773 ** OE_Ignore. This is necessary for the correct constraint check
2774 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2775 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002776 */
drh234c39d2004-07-24 03:30:47 +00002777 if( db->init.busy || pTblName==0 ){
2778 if( onError!=OE_Replace || pTab->pIndex==0
2779 || pTab->pIndex->onError==OE_Replace){
2780 pIndex->pNext = pTab->pIndex;
2781 pTab->pIndex = pIndex;
2782 }else{
2783 Index *pOther = pTab->pIndex;
2784 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2785 pOther = pOther->pNext;
2786 }
2787 pIndex->pNext = pOther->pNext;
2788 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002789 }
drh234c39d2004-07-24 03:30:47 +00002790 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002791 }
danielk1977d8123362004-06-12 09:25:12 +00002792
drh75897232000-05-29 14:26:00 +00002793 /* Clean up before exiting */
2794exit_create_index:
drh956bc922004-07-24 17:38:29 +00002795 if( pIndex ){
danielk1977cb9d8d82009-03-18 18:43:36 +00002796 sqlite3_free(pIndex->zColAff);
2797 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002798 }
drh633e6d52008-07-28 19:34:53 +00002799 sqlite3ExprListDelete(db, pList);
2800 sqlite3SrcListDelete(db, pTblName);
2801 sqlite3DbFree(db, zName);
drh75897232000-05-29 14:26:00 +00002802 return;
2803}
2804
2805/*
drh51147ba2005-07-23 22:59:55 +00002806** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002807** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002808**
2809** aiRowEst[0] is suppose to contain the number of elements in the index.
2810** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2811** number of rows in the table that match any particular value of the
2812** first column of the index. aiRowEst[2] is an estimate of the number
2813** of rows that match any particular combiniation of the first 2 columns
2814** of the index. And so forth. It must always be the case that
2815*
2816** aiRowEst[N]<=aiRowEst[N-1]
2817** aiRowEst[N]>=1
2818**
2819** Apart from that, we have little to go on besides intuition as to
2820** how aiRowEst[] should be initialized. The numbers generated here
2821** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002822*/
2823void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002824 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002825 int i;
drh28c4cf42005-07-27 20:41:43 +00002826 assert( a!=0 );
2827 a[0] = 1000000;
drhdb513882006-05-11 23:14:59 +00002828 for(i=pIdx->nColumn; i>=5; i--){
2829 a[i] = 5;
2830 }
2831 while( i>=1 ){
2832 a[i] = 11 - i;
2833 i--;
drh28c4cf42005-07-27 20:41:43 +00002834 }
2835 if( pIdx->onError!=OE_None ){
2836 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002837 }
2838}
2839
2840/*
drh74e24cd2002-01-09 03:19:59 +00002841** This routine will drop an existing named index. This routine
2842** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002843*/
drh4d91a702006-01-04 15:54:36 +00002844void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002845 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002846 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002847 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002848 int iDb;
drh75897232000-05-29 14:26:00 +00002849
drh8af73d42009-05-13 22:58:28 +00002850 assert( pParse->nErr==0 ); /* Never called with prior errors */
2851 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002852 goto exit_drop_index;
2853 }
drhd24cc422003-03-27 12:51:24 +00002854 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002855 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2856 goto exit_drop_index;
2857 }
danielk19774adee202004-05-08 08:23:19 +00002858 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002859 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002860 if( !ifExists ){
2861 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2862 }
drha6ecd332004-06-10 00:29:09 +00002863 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002864 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002865 }
drh485b39b2002-07-13 03:11:52 +00002866 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002867 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002868 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002869 goto exit_drop_index;
2870 }
danielk1977da184232006-01-05 11:34:32 +00002871 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002872#ifndef SQLITE_OMIT_AUTHORIZATION
2873 {
2874 int code = SQLITE_DROP_INDEX;
2875 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002876 const char *zDb = db->aDb[iDb].zName;
2877 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002878 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002879 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002880 }
danielk1977da184232006-01-05 11:34:32 +00002881 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002882 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002883 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002884 }
drhed6c8672003-01-12 18:02:16 +00002885 }
drhe5f9c642003-01-13 23:27:31 +00002886#endif
drh75897232000-05-29 14:26:00 +00002887
2888 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002889 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002890 if( v ){
drh77658e22007-12-04 16:54:52 +00002891 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002892 sqlite3NestedParse(pParse,
2893 "DELETE FROM %Q.%s WHERE name=%Q",
2894 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2895 pIndex->zName
2896 );
danielk1977006015d2008-04-11 17:11:26 +00002897 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2898 sqlite3NestedParse(pParse,
2899 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2900 db->aDb[iDb].zName, pIndex->zName
2901 );
2902 }
drh9cbf3422008-01-17 16:22:13 +00002903 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002904 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002905 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002906 }
2907
drhd24cc422003-03-27 12:51:24 +00002908exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002909 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002910}
2911
2912/*
drhcf643722007-03-27 13:36:37 +00002913** pArray is a pointer to an array of objects. Each object in the
2914** array is szEntry bytes in size. This routine allocates a new
2915** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002916**
drhcf643722007-03-27 13:36:37 +00002917** *pnEntry is the number of entries already in use. *pnAlloc is
2918** the previously allocated size of the array. initSize is the
2919** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002920**
drhcf643722007-03-27 13:36:37 +00002921** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002922**
drhcf643722007-03-27 13:36:37 +00002923** This routine returns a pointer to the array of objects. This
2924** might be the same as the pArray parameter or it might be a different
2925** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002926*/
drhcf643722007-03-27 13:36:37 +00002927void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002928 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002929 void *pArray, /* Array of objects. Might be reallocated */
2930 int szEntry, /* Size of each object in the array */
2931 int initSize, /* Suggested initial allocation, in elements */
2932 int *pnEntry, /* Number of objects currently in use */
2933 int *pnAlloc, /* Current size of the allocation, in elements */
2934 int *pIdx /* Write the index of a new slot here */
2935){
2936 char *z;
2937 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002938 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002939 int newSize;
drhcf643722007-03-27 13:36:37 +00002940 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002941 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002942 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002943 *pIdx = -1;
2944 return pArray;
drh13449892005-09-07 21:22:45 +00002945 }
drh6a1e0712008-12-05 15:24:15 +00002946 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002947 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002948 }
drhcf643722007-03-27 13:36:37 +00002949 z = (char*)pArray;
2950 memset(&z[*pnEntry * szEntry], 0, szEntry);
2951 *pIdx = *pnEntry;
2952 ++*pnEntry;
2953 return pArray;
drh13449892005-09-07 21:22:45 +00002954}
2955
2956/*
drh75897232000-05-29 14:26:00 +00002957** Append a new element to the given IdList. Create a new IdList if
2958** need be.
drhdaffd0e2001-04-11 14:28:42 +00002959**
2960** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002961*/
drh17435752007-08-16 04:30:38 +00002962IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002963 int i;
drh75897232000-05-29 14:26:00 +00002964 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002965 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002966 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002967 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002968 }
drhcf643722007-03-27 13:36:37 +00002969 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002970 db,
drhcf643722007-03-27 13:36:37 +00002971 pList->a,
2972 sizeof(pList->a[0]),
2973 5,
2974 &pList->nId,
2975 &pList->nAlloc,
2976 &i
2977 );
drh13449892005-09-07 21:22:45 +00002978 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002979 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002980 return 0;
drh75897232000-05-29 14:26:00 +00002981 }
drh17435752007-08-16 04:30:38 +00002982 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002983 return pList;
2984}
2985
2986/*
drhfe05af82005-07-21 03:14:59 +00002987** Delete an IdList.
2988*/
drh633e6d52008-07-28 19:34:53 +00002989void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00002990 int i;
2991 if( pList==0 ) return;
2992 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00002993 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00002994 }
drh633e6d52008-07-28 19:34:53 +00002995 sqlite3DbFree(db, pList->a);
2996 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00002997}
2998
2999/*
3000** Return the index in pList of the identifier named zId. Return -1
3001** if not found.
3002*/
3003int sqlite3IdListIndex(IdList *pList, const char *zName){
3004 int i;
3005 if( pList==0 ) return -1;
3006 for(i=0; i<pList->nId; i++){
3007 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3008 }
3009 return -1;
3010}
3011
3012/*
drha78c22c2008-11-11 18:28:58 +00003013** Expand the space allocated for the given SrcList object by
3014** creating nExtra new slots beginning at iStart. iStart is zero based.
3015** New slots are zeroed.
3016**
3017** For example, suppose a SrcList initially contains two entries: A,B.
3018** To append 3 new entries onto the end, do this:
3019**
3020** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3021**
3022** After the call above it would contain: A, B, nil, nil, nil.
3023** If the iStart argument had been 1 instead of 2, then the result
3024** would have been: A, nil, nil, nil, B. To prepend the new slots,
3025** the iStart value would be 0. The result then would
3026** be: nil, nil, nil, A, B.
3027**
3028** If a memory allocation fails the SrcList is unchanged. The
3029** db->mallocFailed flag will be set to true.
3030*/
3031SrcList *sqlite3SrcListEnlarge(
3032 sqlite3 *db, /* Database connection to notify of OOM errors */
3033 SrcList *pSrc, /* The SrcList to be enlarged */
3034 int nExtra, /* Number of new slots to add to pSrc->a[] */
3035 int iStart /* Index in pSrc->a[] of first new slot */
3036){
3037 int i;
3038
3039 /* Sanity checking on calling parameters */
3040 assert( iStart>=0 );
3041 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003042 assert( pSrc!=0 );
3043 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003044
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
drhb7916a72009-05-27 10:31:29 +00003081** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003082**
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);
drhb7916a72009-05-27 10:31:29 +00003109**
3110** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3111** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003112*/
drh17435752007-08-16 04:30:38 +00003113SrcList *sqlite3SrcListAppend(
3114 sqlite3 *db, /* Connection to notify of malloc failures */
3115 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3116 Token *pTable, /* Table to append */
3117 Token *pDatabase /* Database of the table */
3118){
drha99db3b2004-06-19 14:49:12 +00003119 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003120 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003121 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003122 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003123 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003124 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003125 }
drha78c22c2008-11-11 18:28:58 +00003126 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3127 if( db->mallocFailed ){
3128 sqlite3SrcListDelete(db, pList);
3129 return 0;
drhad3cab52002-05-24 02:04:32 +00003130 }
drha78c22c2008-11-11 18:28:58 +00003131 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003132 if( pDatabase && pDatabase->z==0 ){
3133 pDatabase = 0;
3134 }
drhd3001712009-05-12 17:46:53 +00003135 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003136 Token *pTemp = pDatabase;
3137 pDatabase = pTable;
3138 pTable = pTemp;
3139 }
drh17435752007-08-16 04:30:38 +00003140 pItem->zName = sqlite3NameFromToken(db, pTable);
3141 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003142 return pList;
3143}
3144
3145/*
drhdfe88ec2008-11-03 20:55:06 +00003146** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003147*/
danielk19774adee202004-05-08 08:23:19 +00003148void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003149 int i;
drh9b3187e2005-01-18 14:45:47 +00003150 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003151 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003152 if( pList ){
3153 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3154 if( pItem->iCursor>=0 ) break;
3155 pItem->iCursor = pParse->nTab++;
3156 if( pItem->pSelect ){
3157 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3158 }
drh63eb5f22003-04-29 16:20:44 +00003159 }
3160 }
3161}
3162
3163/*
drhad3cab52002-05-24 02:04:32 +00003164** Delete an entire SrcList including all its substructure.
3165*/
drh633e6d52008-07-28 19:34:53 +00003166void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003167 int i;
drhbe5c89a2004-07-26 00:31:09 +00003168 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003169 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003170 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003171 sqlite3DbFree(db, pItem->zDatabase);
3172 sqlite3DbFree(db, pItem->zName);
3173 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003174 sqlite3DbFree(db, pItem->zIndex);
danielk1977a04a34f2007-04-16 15:06:25 +00003175 sqlite3DeleteTable(pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003176 sqlite3SelectDelete(db, pItem->pSelect);
3177 sqlite3ExprDelete(db, pItem->pOn);
3178 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003179 }
drh633e6d52008-07-28 19:34:53 +00003180 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003181}
3182
drh982cef72000-05-30 16:27:03 +00003183/*
drh61dfc312006-12-16 16:25:15 +00003184** This routine is called by the parser to add a new term to the
3185** end of a growing FROM clause. The "p" parameter is the part of
3186** the FROM clause that has already been constructed. "p" is NULL
3187** if this is the first term of the FROM clause. pTable and pDatabase
3188** are the name of the table and database named in the FROM clause term.
3189** pDatabase is NULL if the database name qualifier is missing - the
3190** usual case. If the term has a alias, then pAlias points to the
3191** alias token. If the term is a subquery, then pSubquery is the
3192** SELECT statement that the subquery encodes. The pTable and
3193** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3194** parameters are the content of the ON and USING clauses.
3195**
3196** Return a new SrcList which encodes is the FROM with the new
3197** term added.
3198*/
3199SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003200 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003201 SrcList *p, /* The left part of the FROM clause already seen */
3202 Token *pTable, /* Name of the table to add to the FROM clause */
3203 Token *pDatabase, /* Name of the database containing pTable */
3204 Token *pAlias, /* The right-hand side of the AS subexpression */
3205 Select *pSubquery, /* A subquery used in place of a table name */
3206 Expr *pOn, /* The ON clause of a join */
3207 IdList *pUsing /* The USING clause of a join */
3208){
3209 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003210 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003211 if( !p && (pOn || pUsing) ){
3212 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3213 (pOn ? "ON" : "USING")
3214 );
3215 goto append_from_error;
3216 }
drh17435752007-08-16 04:30:38 +00003217 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003218 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003219 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003220 }
3221 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003222 assert( pAlias!=0 );
3223 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003224 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003225 }
3226 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003227 pItem->pOn = pOn;
3228 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003229 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003230
3231 append_from_error:
3232 assert( p==0 );
3233 sqlite3ExprDelete(db, pOn);
3234 sqlite3IdListDelete(db, pUsing);
3235 sqlite3SelectDelete(db, pSubquery);
3236 return 0;
drh61dfc312006-12-16 16:25:15 +00003237}
3238
3239/*
danielk1977b1c685b2008-10-06 16:18:39 +00003240** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3241** element of the source-list passed as the second argument.
3242*/
3243void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003244 assert( pIndexedBy!=0 );
3245 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003246 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3247 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3248 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3249 /* A "NOT INDEXED" clause was supplied. See parse.y
3250 ** construct "indexed_opt" for details. */
3251 pItem->notIndexed = 1;
3252 }else{
3253 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3254 }
3255 }
3256}
3257
3258/*
drh61dfc312006-12-16 16:25:15 +00003259** When building up a FROM clause in the parser, the join operator
3260** is initially attached to the left operand. But the code generator
3261** expects the join operator to be on the right operand. This routine
3262** Shifts all join operators from left to right for an entire FROM
3263** clause.
3264**
3265** Example: Suppose the join is like this:
3266**
3267** A natural cross join B
3268**
3269** The operator is "natural cross join". The A and B operands are stored
3270** in p->a[0] and p->a[1], respectively. The parser initially stores the
3271** operator with A. This routine shifts that operator over to B.
3272*/
3273void sqlite3SrcListShiftJoinType(SrcList *p){
3274 if( p && p->a ){
3275 int i;
3276 for(i=p->nSrc-1; i>0; i--){
3277 p->a[i].jointype = p->a[i-1].jointype;
3278 }
3279 p->a[0].jointype = 0;
3280 }
3281}
3282
3283/*
drhc4a3c772001-04-04 11:48:57 +00003284** Begin a transaction
3285*/
drh684917c2004-10-05 02:41:42 +00003286void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003287 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003288 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003289 int i;
drh5e00f6c2001-09-13 13:46:56 +00003290
drhd3001712009-05-12 17:46:53 +00003291 assert( pParse!=0 );
3292 db = pParse->db;
3293 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003294/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003295 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3296 return;
3297 }
danielk19771d850a72004-05-31 08:26:49 +00003298 v = sqlite3GetVdbe(pParse);
3299 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003300 if( type!=TK_DEFERRED ){
3301 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003302 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003303 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003304 }
3305 }
drh66a51672008-01-03 00:01:23 +00003306 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003307}
3308
3309/*
3310** Commit a transaction
3311*/
danielk19774adee202004-05-08 08:23:19 +00003312void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003313 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003314 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003315
drhd3001712009-05-12 17:46:53 +00003316 assert( pParse!=0 );
3317 db = pParse->db;
3318 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003319/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003320 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3321 return;
3322 }
danielk19771d850a72004-05-31 08:26:49 +00003323 v = sqlite3GetVdbe(pParse);
3324 if( v ){
drh66a51672008-01-03 00:01:23 +00003325 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003326 }
drhc4a3c772001-04-04 11:48:57 +00003327}
3328
3329/*
3330** Rollback a transaction
3331*/
danielk19774adee202004-05-08 08:23:19 +00003332void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003333 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003334 Vdbe *v;
3335
drhd3001712009-05-12 17:46:53 +00003336 assert( pParse!=0 );
3337 db = pParse->db;
3338 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003339/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003340 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3341 return;
3342 }
danielk19774adee202004-05-08 08:23:19 +00003343 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003344 if( v ){
drh66a51672008-01-03 00:01:23 +00003345 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003346 }
drhc4a3c772001-04-04 11:48:57 +00003347}
drhf57b14a2001-09-14 18:54:08 +00003348
3349/*
danielk1977fd7f0452008-12-17 17:30:26 +00003350** This function is called by the parser when it parses a command to create,
3351** release or rollback an SQL savepoint.
3352*/
3353void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003354 char *zName = sqlite3NameFromToken(pParse->db, pName);
3355 if( zName ){
3356 Vdbe *v = sqlite3GetVdbe(pParse);
3357#ifndef SQLITE_OMIT_AUTHORIZATION
3358 static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3359 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3360#endif
3361 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3362 sqlite3DbFree(pParse->db, zName);
3363 return;
3364 }
3365 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003366 }
3367}
3368
3369/*
drhdc3ff9c2004-08-18 02:10:15 +00003370** Make sure the TEMP database is open and available for use. Return
3371** the number of errors. Leave any error messages in the pParse structure.
3372*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003373int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003374 sqlite3 *db = pParse->db;
3375 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003376 int rc;
3377 static const int flags =
3378 SQLITE_OPEN_READWRITE |
3379 SQLITE_OPEN_CREATE |
3380 SQLITE_OPEN_EXCLUSIVE |
3381 SQLITE_OPEN_DELETEONCLOSE |
3382 SQLITE_OPEN_TEMP_DB;
3383
3384 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
drhc797d4d2007-05-08 01:08:49 +00003385 &db->aDb[1].pBt);
drhdc3ff9c2004-08-18 02:10:15 +00003386 if( rc!=SQLITE_OK ){
3387 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3388 "file for storing temporary tables");
3389 pParse->rc = rc;
3390 return 1;
3391 }
drh60a713c2008-01-21 16:22:45 +00003392 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
danielk197714db2662006-01-09 16:12:04 +00003393 assert( db->aDb[1].pSchema );
drhfdc40e92008-04-17 20:59:37 +00003394 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
3395 db->dfltJournalMode);
drhdc3ff9c2004-08-18 02:10:15 +00003396 }
3397 return 0;
3398}
3399
3400/*
drh80242052004-06-09 00:48:12 +00003401** Generate VDBE code that will verify the schema cookie and start
3402** a read-transaction for all named database files.
3403**
3404** It is important that all schema cookies be verified and all
3405** read transactions be started before anything else happens in
3406** the VDBE program. But this routine can be called after much other
3407** code has been generated. So here is what we do:
3408**
drhc275b4e2004-07-19 17:25:24 +00003409** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003410** will jump to a subroutine at the end of the program. Then we
3411** record every database that needs its schema verified in the
3412** pParse->cookieMask field. Later, after all other code has been
3413** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003414** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003415** will be made to point to that subroutine. The generation of the
3416** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003417**
3418** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3419** schema on any databases. This can be used to position the OP_Goto
3420** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003421*/
danielk19774adee202004-05-08 08:23:19 +00003422void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003423 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003424 Vdbe *v;
3425 int mask;
3426
3427 v = sqlite3GetVdbe(pParse);
3428 if( v==0 ) return; /* This only happens if there was a prior error */
3429 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003430 if( pParse->cookieGoto==0 ){
drh66a51672008-01-03 00:01:23 +00003431 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003432 }
drhc275b4e2004-07-19 17:25:24 +00003433 if( iDb>=0 ){
3434 assert( iDb<db->nDb );
3435 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003436 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003437 mask = 1<<iDb;
3438 if( (pParse->cookieMask & mask)==0 ){
3439 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003440 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003441 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003442 sqlite3OpenTempDatabase(pParse);
3443 }
drhc275b4e2004-07-19 17:25:24 +00003444 }
drh001bbcb2003-03-19 03:14:00 +00003445 }
drh001bbcb2003-03-19 03:14:00 +00003446}
3447
3448/*
drh1c928532002-01-31 15:54:21 +00003449** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003450** might change the database.
3451**
3452** This routine starts a new transaction if we are not already within
3453** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003454** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003455** be set for operations that might fail (due to a constraint) part of
3456** the way through and which will need to undo some writes without having to
3457** rollback the whole transaction. For operations where all constraints
3458** can be checked before any changes are made to the database, it is never
3459** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003460*/
drh7f0f12e2004-05-21 13:39:50 +00003461void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
drh80242052004-06-09 00:48:12 +00003462 sqlite3CodeVerifySchema(pParse, iDb);
3463 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003464 if( setStatement && pParse->nested==0 ){
drh8af73d42009-05-13 22:58:28 +00003465 /* Every place where this routine is called with setStatement!=0 has
3466 ** already successfully created a VDBE. */
3467 assert( pParse->pVdbe );
3468 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Statement, iDb);
danielk19771d850a72004-05-31 08:26:49 +00003469 }
drh663fc632002-02-02 18:49:19 +00003470}
3471
drh4343fea2004-11-05 23:46:15 +00003472/*
3473** Check to see if pIndex uses the collating sequence pColl. Return
3474** true if it does and false if it does not.
3475*/
3476#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003477static int collationMatch(const char *zColl, Index *pIndex){
3478 int i;
drh04491712009-05-13 17:21:13 +00003479 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003480 for(i=0; i<pIndex->nColumn; i++){
3481 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003482 assert( z!=0 );
3483 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003484 return 1;
3485 }
drh4343fea2004-11-05 23:46:15 +00003486 }
3487 return 0;
3488}
3489#endif
3490
3491/*
3492** Recompute all indices of pTab that use the collating sequence pColl.
3493** If pColl==0 then recompute all indices of pTab.
3494*/
3495#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003496static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003497 Index *pIndex; /* An index associated with pTab */
3498
3499 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003500 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003501 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3502 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003503 sqlite3RefillIndex(pParse, pIndex, -1);
3504 }
3505 }
3506}
3507#endif
3508
3509/*
3510** Recompute all indices of all tables in all databases where the
3511** indices use the collating sequence pColl. If pColl==0 then recompute
3512** all indices everywhere.
3513*/
3514#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003515static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003516 Db *pDb; /* A single database */
3517 int iDb; /* The database index number */
3518 sqlite3 *db = pParse->db; /* The database connection */
3519 HashElem *k; /* For looping over tables in pDb */
3520 Table *pTab; /* A table in the database */
3521
3522 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003523 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003524 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003525 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003526 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003527 }
3528 }
3529}
3530#endif
3531
3532/*
drheee46cf2004-11-06 00:02:48 +00003533** Generate code for the REINDEX command.
3534**
3535** REINDEX -- 1
3536** REINDEX <collation> -- 2
3537** REINDEX ?<database>.?<tablename> -- 3
3538** REINDEX ?<database>.?<indexname> -- 4
3539**
3540** Form 1 causes all indices in all attached databases to be rebuilt.
3541** Form 2 rebuilds all indices in all databases that use the named
3542** collating function. Forms 3 and 4 rebuild the named index or all
3543** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003544*/
3545#ifndef SQLITE_OMIT_REINDEX
3546void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3547 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3548 char *z; /* Name of a table or index */
3549 const char *zDb; /* Name of the database */
3550 Table *pTab; /* A table in the database */
3551 Index *pIndex; /* An index associated with pTab */
3552 int iDb; /* The database index number */
3553 sqlite3 *db = pParse->db; /* The database connection */
3554 Token *pObjName; /* Name of the table or index to be reindexed */
3555
danielk197733a5edc2005-01-27 00:22:02 +00003556 /* Read the database schema. If an error occurs, leave an error message
3557 ** and code in pParse and return NULL. */
3558 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003559 return;
danielk197733a5edc2005-01-27 00:22:02 +00003560 }
3561
drh8af73d42009-05-13 22:58:28 +00003562 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003563 reindexDatabases(pParse, 0);
3564 return;
drhd3001712009-05-12 17:46:53 +00003565 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003566 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003567 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003568 zColl = sqlite3NameFromToken(pParse->db, pName1);
3569 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003570 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003571 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003572 reindexDatabases(pParse, zColl);
3573 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003574 return;
3575 }
drh633e6d52008-07-28 19:34:53 +00003576 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003577 }
3578 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3579 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003580 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003581 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003582 zDb = db->aDb[iDb].zName;
3583 pTab = sqlite3FindTable(db, z, zDb);
3584 if( pTab ){
3585 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003586 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003587 return;
3588 }
3589 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003590 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003591 if( pIndex ){
3592 sqlite3BeginWriteOperation(pParse, 0, iDb);
3593 sqlite3RefillIndex(pParse, pIndex, -1);
3594 return;
3595 }
3596 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3597}
3598#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003599
3600/*
3601** Return a dynamicly allocated KeyInfo structure that can be used
3602** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3603**
3604** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003605** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003606** pointer. If an error occurs (out of memory or missing collation
3607** sequence), NULL is returned and the state of pParse updated to reflect
3608** the error.
3609*/
3610KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3611 int i;
3612 int nCol = pIdx->nColumn;
3613 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003614 sqlite3 *db = pParse->db;
3615 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003616
3617 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003618 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003619 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3620 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3621 for(i=0; i<nCol; i++){
3622 char *zColl = pIdx->azColl[i];
3623 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003624 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003625 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3626 }
drh1bd10f82008-12-10 21:19:56 +00003627 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003628 }
3629
3630 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003631 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003632 pKey = 0;
3633 }
3634 return pKey;
3635}