blob: c23d92fb9bb2c97404ca6cf02bdd378e2547e98b [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**
danielk1977595a5232009-07-24 17:58:53 +000025** $Id: build.c,v 1.557 2009/07/24 17:58:53 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){
dan65a7cd12009-09-01 12:16:01 +000067 Parse *pToplevel = sqlite3ParseToplevel(pParse);
danielk1977c00da102006-01-07 13:21:04 +000068 int i;
69 int nBytes;
70 TableLock *p;
drh8af73d42009-05-13 22:58:28 +000071 assert( iDb>=0 );
dan165921a2009-08-28 18:53:45 +000072
dan65a7cd12009-09-01 12:16:01 +000073 for(i=0; i<pToplevel->nTableLock; i++){
74 p = &pToplevel->aTableLock[i];
danielk1977c00da102006-01-07 13:21:04 +000075 if( p->iDb==iDb && p->iTab==iTab ){
76 p->isWriteLock = (p->isWriteLock || isWriteLock);
77 return;
78 }
79 }
80
dan65a7cd12009-09-01 12:16:01 +000081 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
82 pToplevel->aTableLock =
83 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
84 if( pToplevel->aTableLock ){
85 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
danielk1977c00da102006-01-07 13:21:04 +000086 p->iDb = iDb;
87 p->iTab = iTab;
88 p->isWriteLock = isWriteLock;
89 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000090 }else{
dan65a7cd12009-09-01 12:16:01 +000091 pToplevel->nTableLock = 0;
92 pToplevel->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000093 }
94}
95
96/*
97** Code an OP_TableLock instruction for each table locked by the
98** statement (configured by calls to sqlite3TableLock()).
99*/
100static void codeTableLocks(Parse *pParse){
101 int i;
102 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000103
drh04491712009-05-13 17:21:13 +0000104 pVdbe = sqlite3GetVdbe(pParse);
105 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
danielk1977c00da102006-01-07 13:21:04 +0000106
107 for(i=0; i<pParse->nTableLock; i++){
108 TableLock *p = &pParse->aTableLock[i];
109 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000110 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
111 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000112 }
113}
114#else
115 #define codeTableLocks(x)
116#endif
117
drhe0bc4042002-06-25 01:09:11 +0000118/*
drh75897232000-05-29 14:26:00 +0000119** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000120** parsed and a VDBE program to execute that statement has been
121** prepared. This routine puts the finishing touches on the
122** VDBE program and resets the pParse structure for the next
123** parse.
drh75897232000-05-29 14:26:00 +0000124**
125** Note that if an error occurred, it might be the case that
126** no VDBE code was generated.
127*/
drh80242052004-06-09 00:48:12 +0000128void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000129 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000130 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000131
drh17435752007-08-16 04:30:38 +0000132 db = pParse->db;
133 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000134 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000135 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000136
drh80242052004-06-09 00:48:12 +0000137 /* Begin by generating some termination code at the end of the
138 ** vdbe program
139 */
drh80242052004-06-09 00:48:12 +0000140 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000141 assert( !pParse->isMultiWrite
142 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000143 if( v ){
drh66a51672008-01-03 00:01:23 +0000144 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000145
146 /* The cookie mask contains one bit for each database file open.
147 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
148 ** set for each database that is used. Generate code to start a
149 ** transaction on each used database and to verify the schema cookie
150 ** on each used database.
151 */
drhc275b4e2004-07-19 17:25:24 +0000152 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000153 u32 mask;
drh26e4a8b2008-05-01 17:16:52 +0000154 int iDb;
drhd654be82005-09-20 17:42:23 +0000155 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000156 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
157 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000158 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000159 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drh8a939192009-04-20 17:43:03 +0000160 if( db->init.busy==0 ){
161 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
162 }
drh80242052004-06-09 00:48:12 +0000163 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000164#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000165 {
166 int i;
167 for(i=0; i<pParse->nVtabLock; i++){
danielk1977595a5232009-07-24 17:58:53 +0000168 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
drh26e4a8b2008-05-01 17:16:52 +0000169 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
170 }
171 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000172 }
173#endif
danielk1977c00da102006-01-07 13:21:04 +0000174
175 /* Once all the cookies have been verified and transactions opened,
176 ** obtain the required table-locks. This is a no-op unless the
177 ** shared-cache feature is enabled.
178 */
179 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000180
181 /* Initialize any AUTOINCREMENT data structures required.
182 */
183 sqlite3AutoincrementBegin(pParse);
184
185 /* Finally, jump back to the beginning of the executable code. */
drh66a51672008-01-03 00:01:23 +0000186 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000187 }
drh71c697e2004-08-08 23:39:19 +0000188 }
189
drh3f7d4e42004-07-24 14:35:58 +0000190
drh80242052004-06-09 00:48:12 +0000191 /* Get the VDBE program ready for execution
192 */
drh04491712009-05-13 17:21:13 +0000193 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000194#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000195 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000196 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000197#endif
drhceea3322009-04-23 13:22:42 +0000198 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000199 /* A minimum of one cursor is required if autoincrement is used
200 * See ticket [a696379c1f08866] */
201 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
danielk19776ab3a2e2009-02-19 14:39:25 +0000202 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
dane0af83a2009-09-08 19:15:01 +0000203 pParse->nTab, pParse->nMaxArg, pParse->explain,
204 pParse->isMultiWrite && pParse->mayAbort);
danielk1977441daf62005-02-01 03:46:43 +0000205 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000206 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000207 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000208 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000209 }
drha226d052002-09-25 19:04:07 +0000210 pParse->nTab = 0;
211 pParse->nMem = 0;
212 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000213 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000214 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000215 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000216}
217
218/*
drh205f48e2004-11-05 00:43:11 +0000219** Run the parser and code generator recursively in order to generate
220** code for the SQL statement given onto the end of the pParse context
221** currently under construction. When the parser is run recursively
222** this way, the final OP_Halt is not appended and other initialization
223** and finalization steps are omitted because those are handling by the
224** outermost parser.
225**
226** Not everything is nestable. This facility is designed to permit
227** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000228** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000229*/
230void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
231 va_list ap;
232 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000233 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000234 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000235# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
236 char saveBuf[SAVE_SZ];
237
drh205f48e2004-11-05 00:43:11 +0000238 if( pParse->nErr ) return;
239 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
240 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000241 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000242 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000243 if( zSql==0 ){
244 return; /* A malloc must have failed */
245 }
drh205f48e2004-11-05 00:43:11 +0000246 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000247 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
248 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000249 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000250 sqlite3DbFree(db, zErrMsg);
251 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000252 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000253 pParse->nested--;
254}
255
256/*
danielk19778a414492004-06-29 08:59:35 +0000257** Locate the in-memory structure that describes a particular database
258** table given the name of that table and (optionally) the name of the
259** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000260**
danielk19778a414492004-06-29 08:59:35 +0000261** If zDatabase is 0, all databases are searched for the table and the
262** first matching table is returned. (No checking for duplicate table
263** names is done.) The search order is TEMP first, then MAIN, then any
264** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000265**
danielk19774adee202004-05-08 08:23:19 +0000266** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000267*/
drh9bb575f2004-09-06 17:24:11 +0000268Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000269 Table *p = 0;
270 int i;
drh0a687d12008-07-08 14:52:07 +0000271 int nName;
drh645f63e2004-06-22 13:22:40 +0000272 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000273 nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000274 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000275 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000276 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh0a687d12008-07-08 14:52:07 +0000277 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000278 if( p ) break;
279 }
drh74e24cd2002-01-09 03:19:59 +0000280 return p;
drh75897232000-05-29 14:26:00 +0000281}
282
283/*
danielk19778a414492004-06-29 08:59:35 +0000284** Locate the in-memory structure that describes a particular database
285** table given the name of that table and (optionally) the name of the
286** database containing the table. Return NULL if not found. Also leave an
287** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000288**
danielk19778a414492004-06-29 08:59:35 +0000289** The difference between this routine and sqlite3FindTable() is that this
290** routine leaves an error message in pParse->zErrMsg where
291** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000292*/
drhca424112008-01-25 15:04:48 +0000293Table *sqlite3LocateTable(
294 Parse *pParse, /* context in which to report errors */
295 int isView, /* True if looking for a VIEW rather than a TABLE */
296 const char *zName, /* Name of the table we are looking for */
297 const char *zDbase /* Name of the database. Might be NULL */
298){
drha69d9162003-04-17 22:57:53 +0000299 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000300
danielk19778a414492004-06-29 08:59:35 +0000301 /* Read the database schema. If an error occurs, leave an error message
302 ** and code in pParse and return NULL. */
303 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
304 return 0;
305 }
306
danielk19774adee202004-05-08 08:23:19 +0000307 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000308 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000309 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000310 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000311 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000312 }else{
drhca424112008-01-25 15:04:48 +0000313 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000314 }
drha6ecd332004-06-10 00:29:09 +0000315 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000316 }
317 return p;
318}
319
320/*
321** Locate the in-memory structure that describes
322** a particular index given the name of that index
323** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000324** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000325**
326** If zDatabase is 0, all databases are searched for the
327** table and the first matching index is returned. (No checking
328** for duplicate index names is done.) The search order is
329** TEMP first, then MAIN, then any auxiliary databases added
330** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000331*/
drh9bb575f2004-09-06 17:24:11 +0000332Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000333 Index *p = 0;
334 int i;
drhdee0e402009-05-03 20:23:53 +0000335 int nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000336 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000337 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000338 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000339 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000340 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh04491712009-05-13 17:21:13 +0000341 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000342 if( p ) break;
343 }
drh74e24cd2002-01-09 03:19:59 +0000344 return p;
drh75897232000-05-29 14:26:00 +0000345}
346
347/*
drh956bc922004-07-24 17:38:29 +0000348** Reclaim the memory used by an index
349*/
350static void freeIndex(Index *p){
drhd9da78a2009-03-24 15:08:09 +0000351 sqlite3 *db = p->pTable->dbMem;
drh92aa5ea2009-09-11 14:05:06 +0000352#ifndef SQLITE_OMIT_ANALYZE
dan85c165c2009-08-19 14:34:54 +0000353 sqlite3DeleteIndexSamples(p);
drh92aa5ea2009-09-11 14:05:06 +0000354#endif
drh633e6d52008-07-28 19:34:53 +0000355 sqlite3DbFree(db, p->zColAff);
356 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000357}
358
359/*
drh75897232000-05-29 14:26:00 +0000360** Remove the given index from the index hash table, and free
361** its memory structures.
362**
drhd229ca92002-01-09 13:30:41 +0000363** The index is removed from the database hash tables but
364** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000365** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000366*/
drh03881232009-02-13 03:43:31 +0000367static void sqlite3DeleteIndex(Index *p){
drhd229ca92002-01-09 13:30:41 +0000368 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000369 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000370
drhea678832008-12-10 19:26:22 +0000371 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
drha83ccca2009-04-28 13:01:09 +0000372 sqlite3Strlen30(zName), 0);
drh85c23c62005-08-20 03:03:04 +0000373 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000374 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000375}
376
377/*
drhc96d8532005-05-03 12:30:33 +0000378** For the index called zIdxName which is found in the database iDb,
379** unlike that index from its Table then remove the index from
380** the index hash table and free all memory structures associated
381** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000382*/
drh9bb575f2004-09-06 17:24:11 +0000383void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000384 Index *pIndex;
385 int len;
danielk1977da184232006-01-05 11:34:32 +0000386 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000387
drhdee0e402009-05-03 20:23:53 +0000388 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000389 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh9635cc72009-06-25 11:50:21 +0000390 if( pIndex ){
drh956bc922004-07-24 17:38:29 +0000391 if( pIndex->pTable->pIndex==pIndex ){
392 pIndex->pTable->pIndex = pIndex->pNext;
393 }else{
394 Index *p;
drh04491712009-05-13 17:21:13 +0000395 /* Justification of ALWAYS(); The index must be on the list of
396 ** indices. */
397 p = pIndex->pTable->pIndex;
398 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
399 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000400 p->pNext = pIndex->pNext;
401 }
drh5e00f6c2001-09-13 13:46:56 +0000402 }
drh956bc922004-07-24 17:38:29 +0000403 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000404 }
drh956bc922004-07-24 17:38:29 +0000405 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000406}
407
408/*
drhe0bc4042002-06-25 01:09:11 +0000409** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000410** a single database. This routine is called to reclaim memory
411** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000412** if there were schema changes during the transaction or if a
413** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000414**
drh62312862009-02-03 22:17:42 +0000415** If iDb==0 then reset the internal schema tables for all database
416** files. If iDb>=1 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000417** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000418*/
drh9bb575f2004-09-06 17:24:11 +0000419void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000420 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000421 assert( iDb>=0 && iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000422
423 if( iDb==0 ){
424 sqlite3BtreeEnterAll(db);
425 }
drh1c2d8412003-03-31 00:30:47 +0000426 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000427 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000428 if( pDb->pSchema ){
danielk19774eab8b72007-12-27 15:12:16 +0000429 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
danielk1977de0fe3e2006-01-06 06:33:12 +0000430 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000431 }
drh1c2d8412003-03-31 00:30:47 +0000432 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000433 }
drh1c2d8412003-03-31 00:30:47 +0000434 assert( iDb==0 );
435 db->flags &= ~SQLITE_InternChanges;
danielk1977595a5232009-07-24 17:58:53 +0000436 sqlite3VtabUnlockList(db);
danielk19774eab8b72007-12-27 15:12:16 +0000437 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000438
439 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000440 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000441 ** opportunity to do this here since we have just deleted all of the
442 ** schema hash tables and therefore do not have to make any changes
443 ** to any of those tables.
444 */
445 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000446 struct Db *pDb = &db->aDb[i];
447 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000448 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000449 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000450 continue;
451 }
452 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000453 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000454 }
drh8bf8dc92003-05-17 17:35:10 +0000455 j++;
drh1c2d8412003-03-31 00:30:47 +0000456 }
457 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
458 db->nDb = j;
459 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
460 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000461 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000462 db->aDb = db->aDbStatic;
463 }
drhe0bc4042002-06-25 01:09:11 +0000464}
465
466/*
drhe0bc4042002-06-25 01:09:11 +0000467** This routine is called when a commit occurs.
468*/
drh9bb575f2004-09-06 17:24:11 +0000469void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000470 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000471}
472
473/*
drh956bc922004-07-24 17:38:29 +0000474** Clear the column names from a table or view.
475*/
476static void sqliteResetColumnNames(Table *pTable){
477 int i;
478 Column *pCol;
drhd9da78a2009-03-24 15:08:09 +0000479 sqlite3 *db = pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000480 testcase( db==0 );
drh956bc922004-07-24 17:38:29 +0000481 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000482 if( (pCol = pTable->aCol)!=0 ){
483 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000484 sqlite3DbFree(db, pCol->zName);
485 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000486 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000487 sqlite3DbFree(db, pCol->zType);
488 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000489 }
drh633e6d52008-07-28 19:34:53 +0000490 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000491 }
drh956bc922004-07-24 17:38:29 +0000492 pTable->aCol = 0;
493 pTable->nCol = 0;
494}
495
496/*
drh75897232000-05-29 14:26:00 +0000497** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000498** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000499**
500** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000501** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000502** memory structures of the indices and foreign keys associated with
503** the table.
drh75897232000-05-29 14:26:00 +0000504*/
danielk1977a04a34f2007-04-16 15:06:25 +0000505void sqlite3DeleteTable(Table *pTable){
drh75897232000-05-29 14:26:00 +0000506 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000507 FKey *pFKey, *pNextFKey;
drh633e6d52008-07-28 19:34:53 +0000508 sqlite3 *db;
drhc2eef3b2002-08-31 18:53:06 +0000509
drh75897232000-05-29 14:26:00 +0000510 if( pTable==0 ) return;
drhd9da78a2009-03-24 15:08:09 +0000511 db = pTable->dbMem;
drhc4a64fa2009-05-11 20:53:28 +0000512 testcase( db==0 );
drhc2eef3b2002-08-31 18:53:06 +0000513
drhed8a3bb2005-06-06 21:19:56 +0000514 /* Do not delete the table until the reference count reaches zero. */
515 pTable->nRef--;
516 if( pTable->nRef>0 ){
517 return;
518 }
519 assert( pTable->nRef==0 );
520
drhc2eef3b2002-08-31 18:53:06 +0000521 /* Delete all indices associated with this table
522 */
523 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
524 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000525 assert( pIndex->pSchema==pTable->pSchema );
drh03881232009-02-13 03:43:31 +0000526 sqlite3DeleteIndex(pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000527 }
528
danielk1977576ec6b2005-01-21 11:55:25 +0000529#ifndef SQLITE_OMIT_FOREIGN_KEY
drhe61922a2009-05-02 13:29:37 +0000530 /* Delete all foreign keys associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000531 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
532 pNextFKey = pFKey->pNextFrom;
drh633e6d52008-07-28 19:34:53 +0000533 sqlite3DbFree(db, pFKey);
drhc2eef3b2002-08-31 18:53:06 +0000534 }
danielk1977576ec6b2005-01-21 11:55:25 +0000535#endif
drhc2eef3b2002-08-31 18:53:06 +0000536
537 /* Delete the Table structure itself.
538 */
drh956bc922004-07-24 17:38:29 +0000539 sqliteResetColumnNames(pTable);
drh633e6d52008-07-28 19:34:53 +0000540 sqlite3DbFree(db, pTable->zName);
541 sqlite3DbFree(db, pTable->zColAff);
542 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000543#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000544 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000545#endif
drhb9bb7c12006-06-11 23:41:55 +0000546 sqlite3VtabClear(pTable);
drh633e6d52008-07-28 19:34:53 +0000547 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000548}
549
550/*
drh5edc3122001-09-13 21:53:09 +0000551** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000552** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000553*/
drh9bb575f2004-09-06 17:24:11 +0000554void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000555 Table *p;
drh956bc922004-07-24 17:38:29 +0000556 Db *pDb;
557
drhd229ca92002-01-09 13:30:41 +0000558 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000559 assert( iDb>=0 && iDb<db->nDb );
560 assert( zTabName && zTabName[0] );
561 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000562 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000563 sqlite3Strlen30(zTabName),0);
drhe61922a2009-05-02 13:29:37 +0000564 sqlite3DeleteTable(p);
drh956bc922004-07-24 17:38:29 +0000565 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000566}
567
568/*
drha99db3b2004-06-19 14:49:12 +0000569** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000570** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000571** is obtained from sqliteMalloc() and must be freed by the calling
572** function.
drh75897232000-05-29 14:26:00 +0000573**
drh24fb6272009-05-01 21:13:36 +0000574** Any quotation marks (ex: "name", 'name', [name], or `name`) that
575** surround the body of the token are removed.
576**
drhc96d8532005-05-03 12:30:33 +0000577** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000578** are not \000 terminated and are not persistent. The returned string
579** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000580*/
drh17435752007-08-16 04:30:38 +0000581char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000582 char *zName;
583 if( pName ){
drh17435752007-08-16 04:30:38 +0000584 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000585 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000586 }else{
587 zName = 0;
588 }
drh75897232000-05-29 14:26:00 +0000589 return zName;
590}
591
592/*
danielk1977cbb18d22004-05-28 11:37:27 +0000593** Open the sqlite_master table stored in database number iDb for
594** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000595*/
danielk1977c00da102006-01-07 13:21:04 +0000596void sqlite3OpenMasterTable(Parse *p, int iDb){
597 Vdbe *v = sqlite3GetVdbe(p);
598 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000599 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000600 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000601 if( p->nTab==0 ){
602 p->nTab = 1;
603 }
drhe0bc4042002-06-25 01:09:11 +0000604}
605
606/*
danielk197704103022009-02-03 16:51:24 +0000607** Parameter zName points to a nul-terminated buffer containing the name
608** of a database ("main", "temp" or the name of an attached db). This
609** function returns the index of the named database in db->aDb[], or
610** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000611*/
danielk197704103022009-02-03 16:51:24 +0000612int sqlite3FindDbName(sqlite3 *db, const char *zName){
613 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000614 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000615 Db *pDb;
616 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000617 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000618 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000619 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000620 break;
drh73c42a12004-11-20 18:13:10 +0000621 }
danielk1977cbb18d22004-05-28 11:37:27 +0000622 }
623 }
danielk1977576ec6b2005-01-21 11:55:25 +0000624 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000625}
626
danielk197704103022009-02-03 16:51:24 +0000627/*
628** The token *pName contains the name of a database (either "main" or
629** "temp" or the name of an attached db). This routine returns the
630** index of the named database in db->aDb[], or -1 if the named db
631** does not exist.
632*/
633int sqlite3FindDb(sqlite3 *db, Token *pName){
634 int i; /* Database number */
635 char *zName; /* Name we are searching for */
636 zName = sqlite3NameFromToken(db, pName);
637 i = sqlite3FindDbName(db, zName);
638 sqlite3DbFree(db, zName);
639 return i;
640}
641
drh0e3d7472004-06-19 17:33:07 +0000642/* The table or view or trigger name is passed to this routine via tokens
643** pName1 and pName2. If the table name was fully qualified, for example:
644**
645** CREATE TABLE xxx.yyy (...);
646**
647** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
648** the table name is not fully qualified, i.e.:
649**
650** CREATE TABLE yyy(...);
651**
652** Then pName1 is set to "yyy" and pName2 is "".
653**
654** This routine sets the *ppUnqual pointer to point at the token (pName1 or
655** pName2) that stores the unqualified table name. The index of the
656** database "xxx" is returned.
657*/
danielk1977ef2cb632004-05-29 02:37:19 +0000658int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000659 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000660 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000661 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
662 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000663){
drh0e3d7472004-06-19 17:33:07 +0000664 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000665 sqlite3 *db = pParse->db;
666
drhc4a64fa2009-05-11 20:53:28 +0000667 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000668 if( db->init.busy ) {
669 sqlite3ErrorMsg(pParse, "corrupt database");
670 pParse->nErr++;
671 return -1;
672 }
danielk1977cbb18d22004-05-28 11:37:27 +0000673 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000674 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000675 if( iDb<0 ){
676 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
677 pParse->nErr++;
678 return -1;
679 }
680 }else{
681 assert( db->init.iDb==0 || db->init.busy );
682 iDb = db->init.iDb;
683 *pUnqual = pName1;
684 }
685 return iDb;
686}
687
688/*
danielk1977d8123362004-06-12 09:25:12 +0000689** This routine is used to check if the UTF-8 string zName is a legal
690** unqualified name for a new schema object (table, index, view or
691** trigger). All names are legal except those that begin with the string
692** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
693** is reserved for internal use.
694*/
695int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000696 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000697 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000698 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000699 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
700 return SQLITE_ERROR;
701 }
702 return SQLITE_OK;
703}
704
705/*
drh75897232000-05-29 14:26:00 +0000706** Begin constructing a new table representation in memory. This is
707** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000708** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000709** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000710** flag is true if the table should be stored in the auxiliary database
711** file instead of in the main database file. This is normally the case
712** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000713** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000714**
drhf57b3392001-10-08 13:22:32 +0000715** The new table record is initialized and put in pParse->pNewTable.
716** As more of the CREATE TABLE statement is parsed, additional action
717** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000718** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000719** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000720*/
danielk19774adee202004-05-08 08:23:19 +0000721void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000722 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000723 Token *pName1, /* First part of the name of the table or view */
724 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000725 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000726 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000727 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000728 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000729){
drh75897232000-05-29 14:26:00 +0000730 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000731 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000732 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000733 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000734 int iDb; /* Database number to create the table in */
735 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000736
danielk1977cbb18d22004-05-28 11:37:27 +0000737 /* The table or view name to create is passed to this routine via tokens
738 ** pName1 and pName2. If the table name was fully qualified, for example:
739 **
740 ** CREATE TABLE xxx.yyy (...);
741 **
742 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
743 ** the table name is not fully qualified, i.e.:
744 **
745 ** CREATE TABLE yyy(...);
746 **
747 ** Then pName1 is set to "yyy" and pName2 is "".
748 **
749 ** The call below sets the pName pointer to point at the token (pName1 or
750 ** pName2) that stores the unqualified table name. The variable iDb is
751 ** set to the index of the database that the table or view is to be
752 ** created in.
753 */
danielk1977ef2cb632004-05-29 02:37:19 +0000754 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000755 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000756 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000757 /* If creating a temp table, the name may not be qualified */
758 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000759 return;
760 }
danielk197753c0f742005-03-29 03:10:59 +0000761 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000762
763 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000764 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000765 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000766 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000767 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000768 }
drh1d85d932004-02-14 23:05:52 +0000769 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000770#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000771 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000772 {
773 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000774 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000775 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000776 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000777 }
drhe5f9c642003-01-13 23:27:31 +0000778 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000779 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000780 code = SQLITE_CREATE_TEMP_VIEW;
781 }else{
782 code = SQLITE_CREATE_VIEW;
783 }
784 }else{
danielk197753c0f742005-03-29 03:10:59 +0000785 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000786 code = SQLITE_CREATE_TEMP_TABLE;
787 }else{
788 code = SQLITE_CREATE_TABLE;
789 }
790 }
danielk1977f1a381e2006-06-16 08:01:02 +0000791 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000792 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000793 }
794 }
795#endif
drhf57b3392001-10-08 13:22:32 +0000796
drhf57b3392001-10-08 13:22:32 +0000797 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000798 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000799 ** it does. The exception is if the statement being parsed was passed
800 ** to an sqlite3_declare_vtab() call. In that case only the column names
801 ** and types will be used, so there is no need to test for namespace
802 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000803 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000804 if( !IN_DECLARE_VTAB ){
805 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
806 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000807 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000808 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
809 if( pTable ){
810 if( !noErr ){
811 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
812 }
813 goto begin_table_error;
814 }
815 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
816 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
817 goto begin_table_error;
818 }
drh75897232000-05-29 14:26:00 +0000819 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000820
danielk197726783a52007-08-29 14:06:22 +0000821 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000822 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000823 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000824 pParse->rc = SQLITE_NOMEM;
825 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000826 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000827 }
drh75897232000-05-29 14:26:00 +0000828 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000829 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000830 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000831 pTable->nRef = 1;
drhc4a64fa2009-05-11 20:53:28 +0000832 pTable->dbMem = 0;
833 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000834 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000835
drh4794f732004-11-05 17:17:50 +0000836 /* If this is the magic sqlite_sequence table used by autoincrement,
837 ** then record a pointer to this table in the main database structure
838 ** so that INSERT can find the table easily.
839 */
840#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000841 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000842 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000843 }
844#endif
845
drh17f71932002-02-21 12:01:27 +0000846 /* Begin generating the code that will insert the table record into
847 ** the SQLITE_MASTER table. Note in particular that we must go ahead
848 ** and allocate the record number for the table entry now. Before any
849 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
850 ** indices to be created and the table record must come before the
851 ** indices. Hence, the record number for the table must be allocated
852 ** now.
853 */
danielk19774adee202004-05-08 08:23:19 +0000854 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000855 int j1;
drhe321c292006-01-12 01:56:43 +0000856 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000857 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000858 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000859
danielk197720b1eaf2006-07-26 16:22:14 +0000860#ifndef SQLITE_OMIT_VIRTUALTABLE
861 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000862 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000863 }
864#endif
865
danielk197736963fd2005-02-19 08:18:05 +0000866 /* If the file format and encoding in the database have not been set,
867 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000868 */
drhb7654112008-01-12 12:48:07 +0000869 reg1 = pParse->regRowid = ++pParse->nMem;
870 reg2 = pParse->regRoot = ++pParse->nMem;
871 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000872 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000873 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000874 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000875 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000876 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000877 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000878 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000879 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000880 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000881 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000882
drh4794f732004-11-05 17:17:50 +0000883 /* This just creates a place-holder record in the sqlite_master table.
884 ** The record created does not contain anything yet. It will be replaced
885 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000886 **
drh0fa991b2009-03-21 16:19:26 +0000887 ** The rowid for the new entry is left in register pParse->regRowid.
888 ** The root page number of the new table is left in reg pParse->regRoot.
889 ** The rowid and root page number values are needed by the code that
890 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000891 */
danielk1977f1a381e2006-06-16 08:01:02 +0000892#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
893 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000894 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000895 }else
896#endif
897 {
drhb7654112008-01-12 12:48:07 +0000898 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000899 }
danielk1977c00da102006-01-07 13:21:04 +0000900 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000901 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
902 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
903 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
904 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000905 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000906 }
drh23bf66d2004-12-14 03:34:34 +0000907
908 /* Normal (non-error) return. */
909 return;
910
911 /* If an error occurs, we jump here */
912begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000913 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000914 return;
drh75897232000-05-29 14:26:00 +0000915}
916
917/*
danielk1977c60e9b82005-01-31 12:42:29 +0000918** This macro is used to compare two strings in a case-insensitive manner.
919** It is slightly faster than calling sqlite3StrICmp() directly, but
920** produces larger code.
921**
922** WARNING: This macro is not compatible with the strcmp() family. It
923** returns true if the two strings are equal, otherwise false.
924*/
925#define STRICMP(x, y) (\
926sqlite3UpperToLower[*(unsigned char *)(x)]== \
927sqlite3UpperToLower[*(unsigned char *)(y)] \
928&& sqlite3StrICmp((x)+1,(y)+1)==0 )
929
930/*
drh75897232000-05-29 14:26:00 +0000931** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000932**
933** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000934** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000935** first to get things going. Then this routine is called for each
936** column.
drh75897232000-05-29 14:26:00 +0000937*/
danielk19774adee202004-05-08 08:23:19 +0000938void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000939 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000940 int i;
drha99db3b2004-06-19 14:49:12 +0000941 char *z;
drhc9b84a12002-06-20 11:36:48 +0000942 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000943 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000944 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000945#if SQLITE_MAX_COLUMN
946 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000947 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
948 return;
949 }
drhbb4957f2008-03-20 14:03:29 +0000950#endif
danielk1977ae74e032008-12-23 11:11:51 +0000951 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000952 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000953 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000954 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000955 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000956 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000957 return;
958 }
959 }
drh75897232000-05-29 14:26:00 +0000960 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000961 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000962 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000963 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000964 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000965 return;
966 }
drh6d4abfb2001-10-22 02:58:08 +0000967 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000968 }
drhc9b84a12002-06-20 11:36:48 +0000969 pCol = &p->aCol[p->nCol];
970 memset(pCol, 0, sizeof(p->aCol[0]));
971 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000972
973 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000974 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
975 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000976 */
danielk19774f057f92004-06-08 00:02:33 +0000977 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000978 p->nCol++;
drh75897232000-05-29 14:26:00 +0000979}
980
981/*
drh382c0242001-10-06 16:33:02 +0000982** This routine is called by the parser while in the middle of
983** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
984** been seen on a column. This routine sets the notNull flag on
985** the column currently under construction.
986*/
danielk19774adee202004-05-08 08:23:19 +0000987void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000988 Table *p;
drhc4a64fa2009-05-11 20:53:28 +0000989 p = pParse->pNewTable;
990 if( p==0 || NEVER(p->nCol<1) ) return;
991 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000992}
993
994/*
danielk197752a83fb2005-01-31 12:56:44 +0000995** Scan the column type name zType (length nType) and return the
996** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000997**
998** This routine does a case-independent search of zType for the
999** substrings in the following table. If one of the substrings is
1000** found, the corresponding affinity is returned. If zType contains
1001** more than one of the substrings, entries toward the top of
1002** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001003** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001004**
1005** Substring | Affinity
1006** --------------------------------
1007** 'INT' | SQLITE_AFF_INTEGER
1008** 'CHAR' | SQLITE_AFF_TEXT
1009** 'CLOB' | SQLITE_AFF_TEXT
1010** 'TEXT' | SQLITE_AFF_TEXT
1011** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001012** 'REAL' | SQLITE_AFF_REAL
1013** 'FLOA' | SQLITE_AFF_REAL
1014** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001015**
1016** If none of the substrings in the above table are found,
1017** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001018*/
drhb7916a72009-05-27 10:31:29 +00001019char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +00001020 u32 h = 0;
1021 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +00001022
drhb7916a72009-05-27 10:31:29 +00001023 if( zIn ) while( zIn[0] ){
1024 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001025 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001026 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1027 aff = SQLITE_AFF_TEXT;
1028 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1029 aff = SQLITE_AFF_TEXT;
1030 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1031 aff = SQLITE_AFF_TEXT;
1032 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001033 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001034 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001035#ifndef SQLITE_OMIT_FLOATING_POINT
1036 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1037 && aff==SQLITE_AFF_NUMERIC ){
1038 aff = SQLITE_AFF_REAL;
1039 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1040 && aff==SQLITE_AFF_NUMERIC ){
1041 aff = SQLITE_AFF_REAL;
1042 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1043 && aff==SQLITE_AFF_NUMERIC ){
1044 aff = SQLITE_AFF_REAL;
1045#endif
danielk1977201f7162005-02-01 02:13:29 +00001046 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001047 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001048 break;
danielk197752a83fb2005-01-31 12:56:44 +00001049 }
1050 }
danielk1977b3dff962005-02-01 01:21:55 +00001051
1052 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001053}
1054
1055/*
drh382c0242001-10-06 16:33:02 +00001056** This routine is called by the parser while in the middle of
1057** parsing a CREATE TABLE statement. The pFirst token is the first
1058** token in the sequence of tokens that describe the type of the
1059** column currently under construction. pLast is the last token
1060** in the sequence. Use this information to construct a string
1061** that contains the typename of the column and store that string
1062** in zType.
1063*/
drh487e2622005-06-25 18:42:14 +00001064void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001065 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001066 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001067
drhc4a64fa2009-05-11 20:53:28 +00001068 p = pParse->pNewTable;
1069 if( p==0 || NEVER(p->nCol<1) ) return;
1070 pCol = &p->aCol[p->nCol-1];
1071 assert( pCol->zType==0 );
1072 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001073 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001074}
1075
1076/*
danielk19777977a172004-11-09 12:44:37 +00001077** The expression is the default value for the most recently added column
1078** of the table currently under construction.
1079**
1080** Default value expressions must be constant. Raise an exception if this
1081** is not the case.
drhd9b02572001-04-15 00:37:09 +00001082**
1083** This routine is called by the parser while in the middle of
1084** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001085*/
drhb7916a72009-05-27 10:31:29 +00001086void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001087 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001088 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001089 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001090 p = pParse->pNewTable;
1091 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001092 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001093 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001094 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1095 pCol->zName);
1096 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001097 /* A copy of pExpr is used instead of the original, as pExpr contains
1098 ** tokens that point to volatile memory. The 'span' of the expression
1099 ** is required by pragma table_info.
1100 */
drh633e6d52008-07-28 19:34:53 +00001101 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001102 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1103 sqlite3DbFree(db, pCol->zDflt);
1104 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001105 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001106 }
danielk19777977a172004-11-09 12:44:37 +00001107 }
drhb7916a72009-05-27 10:31:29 +00001108 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001109}
1110
1111/*
drh4a324312001-12-21 14:30:42 +00001112** Designate the PRIMARY KEY for the table. pList is a list of names
1113** of columns that form the primary key. If pList is NULL, then the
1114** most recently added column of the table is the primary key.
1115**
1116** A table can have at most one primary key. If the table already has
1117** a primary key (and this is the second primary key) then create an
1118** error.
1119**
1120** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001121** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001122** field of the table under construction to be the index of the
1123** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1124** no INTEGER PRIMARY KEY.
1125**
1126** If the key is not an INTEGER PRIMARY KEY, then create a unique
1127** index for the key. No index is created for INTEGER PRIMARY KEYs.
1128*/
drh205f48e2004-11-05 00:43:11 +00001129void sqlite3AddPrimaryKey(
1130 Parse *pParse, /* Parsing context */
1131 ExprList *pList, /* List of field names to be indexed */
1132 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001133 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1134 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001135){
drh4a324312001-12-21 14:30:42 +00001136 Table *pTab = pParse->pNewTable;
1137 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001138 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001139 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001140 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001141 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001142 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001143 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001144 }
drh7d10d5a2008-08-20 16:35:10 +00001145 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001146 if( pList==0 ){
1147 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001148 pTab->aCol[iCol].isPrimKey = 1;
1149 }else{
danielk19770202b292004-06-09 09:55:16 +00001150 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001151 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001152 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1153 break;
1154 }
drh78100cc2003-08-23 22:40:53 +00001155 }
drh6e4fc2c2005-09-15 21:24:51 +00001156 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001157 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001158 }
drh4a324312001-12-21 14:30:42 +00001159 }
danielk19770202b292004-06-09 09:55:16 +00001160 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001161 }
1162 if( iCol>=0 && iCol<pTab->nCol ){
1163 zType = pTab->aCol[iCol].zType;
1164 }
drhfdd6e852005-12-16 01:06:16 +00001165 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1166 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001167 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001168 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001169 assert( autoInc==0 || autoInc==1 );
1170 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001171 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001172#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001173 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1174 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001175#endif
drh4a324312001-12-21 14:30:42 +00001176 }else{
drh4d91a702006-01-04 15:54:36 +00001177 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001178 pList = 0;
drh4a324312001-12-21 14:30:42 +00001179 }
drhe0194f22003-02-26 13:52:51 +00001180
1181primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001182 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001183 return;
drh4a324312001-12-21 14:30:42 +00001184}
1185
1186/*
drhffe07b22005-11-03 00:41:17 +00001187** Add a new CHECK constraint to the table currently under construction.
1188*/
1189void sqlite3AddCheckConstraint(
1190 Parse *pParse, /* Parsing context */
1191 Expr *pCheckExpr /* The check expression */
1192){
drh633e6d52008-07-28 19:34:53 +00001193 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001194#ifndef SQLITE_OMIT_CHECK
1195 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001196 if( pTab && !IN_DECLARE_VTAB ){
drh33e619f2009-05-28 01:00:55 +00001197 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1198 }else
drhffe07b22005-11-03 00:41:17 +00001199#endif
drh33e619f2009-05-28 01:00:55 +00001200 {
1201 sqlite3ExprDelete(db, pCheckExpr);
1202 }
drhffe07b22005-11-03 00:41:17 +00001203}
1204
1205/*
drhd3d39e92004-05-20 22:16:29 +00001206** Set the collation function of the most recently parsed table column
1207** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001208*/
danielk197739002502007-11-12 09:50:26 +00001209void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001210 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001211 int i;
danielk197739002502007-11-12 09:50:26 +00001212 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001213 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001214
danielk1977b8cbb872006-06-19 05:33:45 +00001215 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001216 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001217 db = pParse->db;
1218 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001219 if( !zColl ) return;
1220
drhc4a64fa2009-05-11 20:53:28 +00001221 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001222 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001223 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001224
1225 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1226 ** then an index may have been created on this column before the
1227 ** collation type was added. Correct this if it is the case.
1228 */
1229 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1230 assert( pIdx->nColumn==1 );
1231 if( pIdx->aiColumn[0]==i ){
1232 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001233 }
1234 }
danielk197739002502007-11-12 09:50:26 +00001235 }else{
drh633e6d52008-07-28 19:34:53 +00001236 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001237 }
danielk19777cedc8d2004-06-10 10:50:08 +00001238}
1239
danielk1977466be562004-06-10 02:16:01 +00001240/*
1241** This function returns the collation sequence for database native text
1242** encoding identified by the string zName, length nName.
1243**
1244** If the requested collation sequence is not available, or not available
1245** in the database native encoding, the collation factory is invoked to
1246** request it. If the collation factory does not supply such a sequence,
1247** and the sequence is available in another text encoding, then that is
1248** returned instead.
1249**
1250** If no versions of the requested collations sequence are available, or
1251** another error occurs, NULL is returned and an error message written into
1252** pParse.
drha34001c2007-02-02 12:44:37 +00001253**
1254** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1255** invokes the collation factory if the named collation cannot be found
1256** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001257**
1258** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001259*/
drhc4a64fa2009-05-11 20:53:28 +00001260CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001261 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001262 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001263 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001264 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001265
drhc4a64fa2009-05-11 20:53:28 +00001266 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001267 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh9aeda792009-08-20 02:34:15 +00001268 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
danielk19774dade032005-05-25 10:45:10 +00001269 if( !pColl ){
drhc4a64fa2009-05-11 20:53:28 +00001270 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
danielk1977466be562004-06-10 02:16:01 +00001271 }
1272 }
1273
danielk19770202b292004-06-09 09:55:16 +00001274 return pColl;
1275}
1276
1277
drh8e2ca022002-06-17 17:07:19 +00001278/*
drh3f7d4e42004-07-24 14:35:58 +00001279** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001280**
1281** The schema cookie is used to determine when the schema for the
1282** database changes. After each schema change, the cookie value
1283** changes. When a process first reads the schema it records the
1284** cookie. Thereafter, whenever it goes to access the database,
1285** it checks the cookie to make sure the schema has not changed
1286** since it was last read.
1287**
1288** This plan is not completely bullet-proof. It is possible for
1289** the schema to change multiple times and for the cookie to be
1290** set back to prior value. But schema changes are infrequent
1291** and the probability of hitting the same cookie value is only
1292** 1 chance in 2^32. So we're safe enough.
1293*/
drh9cbf3422008-01-17 16:22:13 +00001294void sqlite3ChangeCookie(Parse *pParse, int iDb){
1295 int r1 = sqlite3GetTempReg(pParse);
1296 sqlite3 *db = pParse->db;
1297 Vdbe *v = pParse->pVdbe;
1298 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001299 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001300 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001301}
1302
1303/*
drh969fa7c2002-02-18 18:30:32 +00001304** Measure the number of characters needed to output the given
1305** identifier. The number returned includes any quotes used
1306** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001307**
1308** The estimate is conservative. It might be larger that what is
1309** really needed.
drh969fa7c2002-02-18 18:30:32 +00001310*/
1311static int identLength(const char *z){
1312 int n;
drh17f71932002-02-21 12:01:27 +00001313 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001314 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001315 }
drh234c39d2004-07-24 03:30:47 +00001316 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001317}
1318
1319/*
danielk19771b870de2009-03-14 08:37:23 +00001320** The first parameter is a pointer to an output buffer. The second
1321** parameter is a pointer to an integer that contains the offset at
1322** which to write into the output buffer. This function copies the
1323** nul-terminated string pointed to by the third parameter, zSignedIdent,
1324** to the specified offset in the buffer and updates *pIdx to refer
1325** to the first byte after the last byte written before returning.
1326**
1327** If the string zSignedIdent consists entirely of alpha-numeric
1328** characters, does not begin with a digit and is not an SQL keyword,
1329** then it is copied to the output buffer exactly as it is. Otherwise,
1330** it is quoted using double-quotes.
1331*/
drhc4a64fa2009-05-11 20:53:28 +00001332static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001333 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001334 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001335 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001336
drh17f71932002-02-21 12:01:27 +00001337 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001338 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001339 }
danielk19771b870de2009-03-14 08:37:23 +00001340 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1341 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001342 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001343 }
1344
drh234c39d2004-07-24 03:30:47 +00001345 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001346 for(j=0; zIdent[j]; j++){
1347 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001348 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001349 }
drh234c39d2004-07-24 03:30:47 +00001350 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001351 z[i] = 0;
1352 *pIdx = i;
1353}
1354
1355/*
1356** Generate a CREATE TABLE statement appropriate for the given
1357** table. Memory to hold the text of the statement is obtained
1358** from sqliteMalloc() and must be freed by the calling function.
1359*/
drh1d34fde2009-02-03 15:50:33 +00001360static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001361 int i, k, n;
1362 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001363 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001364 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001365 n = 0;
drh234c39d2004-07-24 03:30:47 +00001366 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001367 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001368 }
1369 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001370 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001371 zSep = "";
1372 zSep2 = ",";
1373 zEnd = ")";
1374 }else{
1375 zSep = "\n ";
1376 zSep2 = ",\n ";
1377 zEnd = "\n)";
1378 }
drhe0bc4042002-06-25 01:09:11 +00001379 n += 35 + 6*p->nCol;
drhe5ae5732008-06-15 02:51:47 +00001380 zStmt = sqlite3Malloc( n );
drh820a9062008-01-31 13:35:48 +00001381 if( zStmt==0 ){
1382 db->mallocFailed = 1;
1383 return 0;
1384 }
drhbdb339f2009-02-02 18:03:21 +00001385 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001386 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001387 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001388 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001389 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001390 static const char * const azType[] = {
1391 /* SQLITE_AFF_TEXT */ " TEXT",
1392 /* SQLITE_AFF_NONE */ "",
1393 /* SQLITE_AFF_NUMERIC */ " NUM",
1394 /* SQLITE_AFF_INTEGER */ " INT",
1395 /* SQLITE_AFF_REAL */ " REAL"
1396 };
1397 int len;
1398 const char *zType;
1399
drh5bb3eb92007-05-04 13:15:55 +00001400 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001401 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001402 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001403 identPut(zStmt, &k, pCol->zName);
1404 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1405 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
1406 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1407 testcase( pCol->affinity==SQLITE_AFF_NONE );
1408 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1409 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1410 testcase( pCol->affinity==SQLITE_AFF_REAL );
1411
1412 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1413 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001414 assert( pCol->affinity==SQLITE_AFF_NONE
1415 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001416 memcpy(&zStmt[k], zType, len);
1417 k += len;
1418 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001419 }
drh5bb3eb92007-05-04 13:15:55 +00001420 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001421 return zStmt;
1422}
1423
1424/*
drh75897232000-05-29 14:26:00 +00001425** This routine is called to report the final ")" that terminates
1426** a CREATE TABLE statement.
1427**
drhf57b3392001-10-08 13:22:32 +00001428** The table structure that other action routines have been building
1429** is added to the internal hash tables, assuming no errors have
1430** occurred.
drh75897232000-05-29 14:26:00 +00001431**
drh1d85d932004-02-14 23:05:52 +00001432** An entry for the table is made in the master table on disk, unless
1433** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001434** it means we are reading the sqlite_master table because we just
1435** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001436** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001437** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001438**
1439** If the pSelect argument is not NULL, it means that this routine
1440** was called to create a table generated from a
1441** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1442** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001443*/
danielk197719a8e7e2005-03-17 05:03:38 +00001444void sqlite3EndTable(
1445 Parse *pParse, /* Parse context */
1446 Token *pCons, /* The ',' token after the last column defn. */
1447 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1448 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1449){
drh75897232000-05-29 14:26:00 +00001450 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001451 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001452 int iDb;
drh75897232000-05-29 14:26:00 +00001453
drh8af73d42009-05-13 22:58:28 +00001454 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001455 return;
1456 }
drh28037572000-08-02 13:47:41 +00001457 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001458 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001459
danielk1977517eb642004-06-07 10:00:31 +00001460 assert( !db->init.busy || !pSelect );
1461
drhb9bb7c12006-06-11 23:41:55 +00001462 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001463
drhffe07b22005-11-03 00:41:17 +00001464#ifndef SQLITE_OMIT_CHECK
1465 /* Resolve names in all CHECK constraint expressions.
1466 */
1467 if( p->pCheck ){
1468 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1469 NameContext sNC; /* Name context for pParse->pNewTable */
1470
1471 memset(&sNC, 0, sizeof(sNC));
1472 memset(&sSrc, 0, sizeof(sSrc));
1473 sSrc.nSrc = 1;
1474 sSrc.a[0].zName = p->zName;
1475 sSrc.a[0].pTab = p;
1476 sSrc.a[0].iCursor = -1;
1477 sNC.pParse = pParse;
1478 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001479 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001480 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001481 return;
1482 }
1483 }
1484#endif /* !defined(SQLITE_OMIT_CHECK) */
1485
drh1d85d932004-02-14 23:05:52 +00001486 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001487 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1488 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001489 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001490 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001491 */
drh1d85d932004-02-14 23:05:52 +00001492 if( db->init.busy ){
1493 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001494 }
1495
drhe3c41372001-09-17 20:25:58 +00001496 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001497 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001498 **
drhe0bc4042002-06-25 01:09:11 +00001499 ** If this is a TEMPORARY table, write the entry into the auxiliary
1500 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001501 */
drh1d85d932004-02-14 23:05:52 +00001502 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001503 int n;
drhd8bc7082000-06-07 23:51:50 +00001504 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001505 char *zType; /* "view" or "table" */
1506 char *zType2; /* "VIEW" or "TABLE" */
1507 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001508
danielk19774adee202004-05-08 08:23:19 +00001509 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001510 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001511
drh66a51672008-01-03 00:01:23 +00001512 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001513
drh0fa991b2009-03-21 16:19:26 +00001514 /*
1515 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001516 */
drh4ff6dfa2002-03-03 23:06:00 +00001517 if( p->pSelect==0 ){
1518 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001519 zType = "table";
1520 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001521#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001522 }else{
1523 /* A view */
drh4794f732004-11-05 17:17:50 +00001524 zType = "view";
1525 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001526#endif
drh4ff6dfa2002-03-03 23:06:00 +00001527 }
danielk1977517eb642004-06-07 10:00:31 +00001528
danielk1977517eb642004-06-07 10:00:31 +00001529 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1530 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001531 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001532 **
1533 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1534 ** suitable state to query for the column names and types to be used
1535 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001536 **
1537 ** A shared-cache write-lock is not required to write to the new table,
1538 ** as a schema-lock must have already been obtained to create it. Since
1539 ** a schema-lock excludes all other database users, the write-lock would
1540 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001541 */
1542 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001543 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001544 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001545
danielk19776ab3a2e2009-02-19 14:39:25 +00001546 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001547 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001548 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001549 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001550 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001551 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001552 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001553 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001554 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001555 if( pSelTab==0 ) return;
1556 assert( p->aCol==0 );
1557 p->nCol = pSelTab->nCol;
1558 p->aCol = pSelTab->aCol;
1559 pSelTab->nCol = 0;
1560 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001561 sqlite3DeleteTable(pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001562 }
1563 }
drh4794f732004-11-05 17:17:50 +00001564
drh4794f732004-11-05 17:17:50 +00001565 /* Compute the complete text of the CREATE statement */
1566 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001567 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001568 }else{
drh1bd10f82008-12-10 21:19:56 +00001569 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001570 zStmt = sqlite3MPrintf(db,
1571 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1572 );
drh4794f732004-11-05 17:17:50 +00001573 }
1574
1575 /* A slot for the record has already been allocated in the
1576 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001577 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001578 */
1579 sqlite3NestedParse(pParse,
1580 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001581 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1582 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001583 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001584 zType,
1585 p->zName,
1586 p->zName,
drhb7654112008-01-12 12:48:07 +00001587 pParse->regRoot,
1588 zStmt,
1589 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001590 );
drh633e6d52008-07-28 19:34:53 +00001591 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001592 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001593
1594#ifndef SQLITE_OMIT_AUTOINCREMENT
1595 /* Check to see if we need to create an sqlite_sequence table for
1596 ** keeping track of autoincrement keys.
1597 */
drh7d10d5a2008-08-20 16:35:10 +00001598 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001599 Db *pDb = &db->aDb[iDb];
1600 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001601 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001602 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1603 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001604 );
1605 }
1606 }
1607#endif
drh4794f732004-11-05 17:17:50 +00001608
1609 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001610 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1611 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001612 }
drh17e9e292003-02-01 13:53:28 +00001613
drh2958a4e2004-11-12 03:56:15 +00001614
drh17e9e292003-02-01 13:53:28 +00001615 /* Add the table to the in-memory representation of the database.
1616 */
drh8af73d42009-05-13 22:58:28 +00001617 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001618 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001619 Schema *pSchema = p->pSchema;
drhea678832008-12-10 19:26:22 +00001620 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001621 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001622 if( pOld ){
1623 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001624 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001625 return;
1626 }
drh17e9e292003-02-01 13:53:28 +00001627 pParse->pNewTable = 0;
1628 db->nTable++;
1629 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001630
1631#ifndef SQLITE_OMIT_ALTERTABLE
1632 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001633 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001634 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001635 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001636 if( pCons->z==0 ){
1637 pCons = pEnd;
1638 }
drh1bd10f82008-12-10 21:19:56 +00001639 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001640 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001641 }
1642#endif
drh17e9e292003-02-01 13:53:28 +00001643 }
drh75897232000-05-29 14:26:00 +00001644}
1645
drhb7f91642004-10-31 02:22:47 +00001646#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001647/*
drha76b5df2002-02-23 02:32:10 +00001648** The parser calls this routine in order to create a new VIEW
1649*/
danielk19774adee202004-05-08 08:23:19 +00001650void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001651 Parse *pParse, /* The parsing context */
1652 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001653 Token *pName1, /* The token that holds the name of the view */
1654 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001655 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001656 int isTemp, /* TRUE for a TEMPORARY view */
1657 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001658){
drha76b5df2002-02-23 02:32:10 +00001659 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001660 int n;
drhb7916a72009-05-27 10:31:29 +00001661 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001662 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001663 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001664 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001665 int iDb;
drh17435752007-08-16 04:30:38 +00001666 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001667
drh7c3d64f2005-06-06 15:32:08 +00001668 if( pParse->nVar>0 ){
1669 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001670 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001671 return;
1672 }
drhfdd48a72006-09-11 23:45:48 +00001673 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001674 p = pParse->pNewTable;
drh8af73d42009-05-13 22:58:28 +00001675 if( p==0 ){
drh633e6d52008-07-28 19:34:53 +00001676 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001677 return;
1678 }
drh8af73d42009-05-13 22:58:28 +00001679 assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
1680 ** there could not have been an error */
danielk1977ef2cb632004-05-29 02:37:19 +00001681 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001682 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001683 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001684 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001685 ){
drh633e6d52008-07-28 19:34:53 +00001686 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001687 return;
1688 }
drh174b6192002-12-03 02:22:52 +00001689
drh4b59ab52002-08-24 18:24:51 +00001690 /* Make a copy of the entire SELECT statement that defines the view.
1691 ** This will force all the Expr.token.z values to be dynamically
1692 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001693 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001694 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001695 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001696 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001697 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001698 return;
1699 }
drh17435752007-08-16 04:30:38 +00001700 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001701 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001702 }
drh4b59ab52002-08-24 18:24:51 +00001703
1704 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1705 ** the end.
1706 */
drha76b5df2002-02-23 02:32:10 +00001707 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001708 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001709 sEnd.z += sEnd.n;
1710 }
1711 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001712 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001713 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001714 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001715 sEnd.z = &z[n-1];
1716 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001717
danielk19774adee202004-05-08 08:23:19 +00001718 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001719 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001720 return;
drh417be792002-03-03 18:59:40 +00001721}
drhb7f91642004-10-31 02:22:47 +00001722#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001723
danielk1977fe3fcbe22006-06-12 12:08:45 +00001724#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001725/*
1726** The Table structure pTable is really a VIEW. Fill in the names of
1727** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001728** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001729*/
danielk19774adee202004-05-08 08:23:19 +00001730int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001731 Table *pSelTab; /* A fake table from which we get the result set */
1732 Select *pSel; /* Copy of the SELECT that implements the view */
1733 int nErr = 0; /* Number of errors encountered */
1734 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001735 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001736 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001737
1738 assert( pTable );
1739
danielk1977fe3fcbe22006-06-12 12:08:45 +00001740#ifndef SQLITE_OMIT_VIRTUALTABLE
1741 if( sqlite3VtabCallConnect(pParse, pTable) ){
1742 return SQLITE_ERROR;
1743 }
drh4cbdda92006-06-14 19:00:20 +00001744 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001745#endif
1746
1747#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001748 /* A positive nCol means the columns names for this view are
1749 ** already known.
1750 */
1751 if( pTable->nCol>0 ) return 0;
1752
1753 /* A negative nCol is a special marker meaning that we are currently
1754 ** trying to compute the column names. If we enter this routine with
1755 ** a negative nCol, it means two or more views form a loop, like this:
1756 **
1757 ** CREATE VIEW one AS SELECT * FROM two;
1758 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001759 **
drh768578e2009-05-12 00:40:12 +00001760 ** Actually, the error above is now caught prior to reaching this point.
1761 ** But the following test is still important as it does come up
1762 ** in the following:
1763 **
1764 ** CREATE TABLE main.ex1(a);
1765 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1766 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001767 */
1768 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001769 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001770 return 1;
1771 }
drh85c23c62005-08-20 03:03:04 +00001772 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001773
1774 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001775 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1776 ** "*" elements in the results set of the view and will assign cursors
1777 ** to the elements of the FROM clause. But we do not want these changes
1778 ** to be permanent. So the computation is done on a copy of the SELECT
1779 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001780 */
drh9b3187e2005-01-18 14:45:47 +00001781 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001782 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001783 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001784 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001785 n = pParse->nTab;
1786 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1787 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001788 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001789#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001790 xAuth = db->xAuth;
1791 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001792 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001793 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001794#else
drh7d10d5a2008-08-20 16:35:10 +00001795 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001796#endif
drhd9da78a2009-03-24 15:08:09 +00001797 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001798 pParse->nTab = n;
1799 if( pSelTab ){
1800 assert( pTable->aCol==0 );
1801 pTable->nCol = pSelTab->nCol;
1802 pTable->aCol = pSelTab->aCol;
1803 pSelTab->nCol = 0;
1804 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001805 sqlite3DeleteTable(pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001806 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001807 }else{
1808 pTable->nCol = 0;
1809 nErr++;
1810 }
drh633e6d52008-07-28 19:34:53 +00001811 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001812 } else {
drh417be792002-03-03 18:59:40 +00001813 nErr++;
1814 }
drhb7f91642004-10-31 02:22:47 +00001815#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001816 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001817}
1818#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001819
drhb7f91642004-10-31 02:22:47 +00001820#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001821/*
drh8bf8dc92003-05-17 17:35:10 +00001822** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001823*/
drh9bb575f2004-09-06 17:24:11 +00001824static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001825 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001826 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001827 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001828 Table *pTab = sqliteHashData(i);
1829 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001830 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001831 }
1832 }
drh8bf8dc92003-05-17 17:35:10 +00001833 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001834}
drhb7f91642004-10-31 02:22:47 +00001835#else
1836# define sqliteViewResetAll(A,B)
1837#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001838
drh75897232000-05-29 14:26:00 +00001839/*
danielk1977a0bf2652004-11-04 14:30:04 +00001840** This function is called by the VDBE to adjust the internal schema
1841** used by SQLite when the btree layer moves a table root page. The
1842** root-page of a table or index in database iDb has changed from iFrom
1843** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001844**
1845** Ticket #1728: The symbol table might still contain information
1846** on tables and/or indices that are the process of being deleted.
1847** If you are unlucky, one of those deleted indices or tables might
1848** have the same rootpage number as the real table or index that is
1849** being moved. So we cannot stop searching after the first match
1850** because the first match might be for one of the deleted indices
1851** or tables and not the table/index that is actually being moved.
1852** We must continue looping until all tables and indices with
1853** rootpage==iFrom have been converted to have a rootpage of iTo
1854** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001855*/
1856#ifndef SQLITE_OMIT_AUTOVACUUM
1857void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1858 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001859 Hash *pHash;
1860
1861 pHash = &pDb->pSchema->tblHash;
1862 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001863 Table *pTab = sqliteHashData(pElem);
1864 if( pTab->tnum==iFrom ){
1865 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001866 }
1867 }
danielk1977da184232006-01-05 11:34:32 +00001868 pHash = &pDb->pSchema->idxHash;
1869 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001870 Index *pIdx = sqliteHashData(pElem);
1871 if( pIdx->tnum==iFrom ){
1872 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001873 }
1874 }
danielk1977a0bf2652004-11-04 14:30:04 +00001875}
1876#endif
1877
1878/*
1879** Write code to erase the table with root-page iTable from database iDb.
1880** Also write code to modify the sqlite_master table and internal schema
1881** if a root-page of another table is moved by the btree-layer whilst
1882** erasing iTable (this can happen with an auto-vacuum database).
1883*/
drh4e0cff62004-11-05 05:10:28 +00001884static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1885 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001886 int r1 = sqlite3GetTempReg(pParse);
1887 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001888 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001889#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001890 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001891 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001892 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001893 ** reflect this.
1894 **
drh0fa991b2009-03-21 16:19:26 +00001895 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001896 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1897 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001898 */
danielk197763e3e9f2004-11-05 09:19:27 +00001899 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001900 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1901 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001902#endif
drhb7654112008-01-12 12:48:07 +00001903 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001904}
1905
1906/*
1907** Write VDBE code to erase table pTab and all associated indices on disk.
1908** Code to update the sqlite_master tables and internal schema definitions
1909** in case a root-page belonging to another table is moved by the btree layer
1910** is also added (this can happen with an auto-vacuum database).
1911*/
drh4e0cff62004-11-05 05:10:28 +00001912static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001913#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001914 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001915 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1916 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001917 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001918 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001919 }
1920#else
1921 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1922 ** is not defined), then it is important to call OP_Destroy on the
1923 ** table and index root-pages in order, starting with the numerically
1924 ** largest root-page number. This guarantees that none of the root-pages
1925 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1926 ** following were coded:
1927 **
1928 ** OP_Destroy 4 0
1929 ** ...
1930 ** OP_Destroy 5 0
1931 **
1932 ** and root page 5 happened to be the largest root-page number in the
1933 ** database, then root page 5 would be moved to page 4 by the
1934 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1935 ** a free-list page.
1936 */
1937 int iTab = pTab->tnum;
1938 int iDestroyed = 0;
1939
1940 while( 1 ){
1941 Index *pIdx;
1942 int iLargest = 0;
1943
1944 if( iDestroyed==0 || iTab<iDestroyed ){
1945 iLargest = iTab;
1946 }
1947 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1948 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001949 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001950 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1951 iLargest = iIdx;
1952 }
1953 }
danielk1977da184232006-01-05 11:34:32 +00001954 if( iLargest==0 ){
1955 return;
1956 }else{
1957 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1958 destroyRootPage(pParse, iLargest, iDb);
1959 iDestroyed = iLargest;
1960 }
danielk1977a0bf2652004-11-04 14:30:04 +00001961 }
1962#endif
1963}
1964
1965/*
drh75897232000-05-29 14:26:00 +00001966** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001967** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001968*/
drha0733842005-12-29 01:11:36 +00001969void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001970 Table *pTab;
drh75897232000-05-29 14:26:00 +00001971 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001972 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001973 int iDb;
drh75897232000-05-29 14:26:00 +00001974
drh8af73d42009-05-13 22:58:28 +00001975 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001976 goto exit_drop_table;
1977 }
drh8af73d42009-05-13 22:58:28 +00001978 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00001979 assert( pName->nSrc==1 );
drhca424112008-01-25 15:04:48 +00001980 pTab = sqlite3LocateTable(pParse, isView,
1981 pName->a[0].zName, pName->a[0].zDatabase);
danielk1977a8858102004-05-28 12:11:21 +00001982
drha0733842005-12-29 01:11:36 +00001983 if( pTab==0 ){
1984 if( noErr ){
1985 sqlite3ErrorClear(pParse);
1986 }
1987 goto exit_drop_table;
1988 }
danielk1977da184232006-01-05 11:34:32 +00001989 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001990 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00001991
1992 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1993 ** it is initialized.
1994 */
1995 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1996 goto exit_drop_table;
1997 }
drhe5f9c642003-01-13 23:27:31 +00001998#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001999 {
2000 int code;
danielk1977da184232006-01-05 11:34:32 +00002001 const char *zTab = SCHEMA_TABLE(iDb);
2002 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002003 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002004 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002005 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002006 }
drhe5f9c642003-01-13 23:27:31 +00002007 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002008 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002009 code = SQLITE_DROP_TEMP_VIEW;
2010 }else{
2011 code = SQLITE_DROP_VIEW;
2012 }
danielk19774b2688a2006-06-20 11:01:07 +00002013#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002014 }else if( IsVirtual(pTab) ){
2015 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002016 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002017#endif
drhe5f9c642003-01-13 23:27:31 +00002018 }else{
danielk197753c0f742005-03-29 03:10:59 +00002019 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002020 code = SQLITE_DROP_TEMP_TABLE;
2021 }else{
2022 code = SQLITE_DROP_TABLE;
2023 }
2024 }
danielk1977f1a381e2006-06-16 08:01:02 +00002025 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002026 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002027 }
danielk1977a8858102004-05-28 12:11:21 +00002028 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2029 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002030 }
drhe5f9c642003-01-13 23:27:31 +00002031 }
2032#endif
drhc456e572008-08-11 18:44:58 +00002033 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002034 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002035 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002036 }
danielk1977576ec6b2005-01-21 11:55:25 +00002037
2038#ifndef SQLITE_OMIT_VIEW
2039 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2040 ** on a table.
2041 */
danielk1977a8858102004-05-28 12:11:21 +00002042 if( isView && pTab->pSelect==0 ){
2043 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2044 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002045 }
danielk1977a8858102004-05-28 12:11:21 +00002046 if( !isView && pTab->pSelect ){
2047 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2048 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002049 }
danielk1977576ec6b2005-01-21 11:55:25 +00002050#endif
drh75897232000-05-29 14:26:00 +00002051
drh1ccde152000-06-17 13:12:39 +00002052 /* Generate code to remove the table from the master table
2053 ** on disk.
2054 */
danielk19774adee202004-05-08 08:23:19 +00002055 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002056 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002057 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002058 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002059 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002060
danielk197720b1eaf2006-07-26 16:22:14 +00002061#ifndef SQLITE_OMIT_VIRTUALTABLE
2062 if( IsVirtual(pTab) ){
drh768578e2009-05-12 00:40:12 +00002063 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002064 }
2065#endif
2066
danielk19778e227872004-06-07 07:52:17 +00002067 /* Drop all triggers associated with the table being dropped. Code
2068 ** is generated to remove entries from sqlite_master and/or
2069 ** sqlite_temp_master if required.
2070 */
danielk19772f886d12009-02-28 10:47:41 +00002071 pTrigger = sqlite3TriggerList(pParse, pTab);
drhe0bc4042002-06-25 01:09:11 +00002072 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002073 assert( pTrigger->pSchema==pTab->pSchema ||
2074 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002075 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002076 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002077 }
drh8bf8dc92003-05-17 17:35:10 +00002078
danielk19774d36b812004-11-19 07:07:30 +00002079#ifndef SQLITE_OMIT_AUTOINCREMENT
2080 /* Remove any entries of the sqlite_sequence table associated with
2081 ** the table being dropped. This is done before the table is dropped
2082 ** at the btree level, in case the sqlite_sequence table needs to
2083 ** move as a result of the drop (can happen in auto-vacuum mode).
2084 */
drh7d10d5a2008-08-20 16:35:10 +00002085 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002086 sqlite3NestedParse(pParse,
2087 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2088 pDb->zName, pTab->zName
2089 );
2090 }
2091#endif
2092
danielk19778e227872004-06-07 07:52:17 +00002093 /* Drop all SQLITE_MASTER table and index entries that refer to the
2094 ** table. The program name loops through the master table and deletes
2095 ** every row that refers to a table of the same name as the one being
2096 ** dropped. Triggers are handled seperately because a trigger can be
2097 ** created in the temp database that refers to a table in another
2098 ** database.
2099 */
drhf1974842004-11-05 03:56:00 +00002100 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002101 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002102 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002103
2104 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2105 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2106 sqlite3NestedParse(pParse,
2107 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2108 );
2109 }
2110
danielk19774b2688a2006-06-20 11:01:07 +00002111 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002112 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002113 }
drh2958a4e2004-11-12 03:56:15 +00002114
danielk1977a21c6b62005-01-24 10:25:59 +00002115 /* Remove the table entry from SQLite's internal schema and modify
2116 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002117 */
drh4cbdda92006-06-14 19:00:20 +00002118 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002119 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002120 }
drh66a51672008-01-03 00:01:23 +00002121 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002122 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002123 }
drhd24cc422003-03-27 12:51:24 +00002124 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002125
2126exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002127 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002128}
2129
2130/*
drhc2eef3b2002-08-31 18:53:06 +00002131** This routine is called to create a new foreign key on the table
2132** currently under construction. pFromCol determines which columns
2133** in the current table point to the foreign key. If pFromCol==0 then
2134** connect the key to the last column inserted. pTo is the name of
2135** the table referred to. pToCol is a list of tables in the other
2136** pTo table that the foreign key points to. flags contains all
2137** information about the conflict resolution algorithms specified
2138** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2139**
2140** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002141** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002142**
2143** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002144** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002145*/
danielk19774adee202004-05-08 08:23:19 +00002146void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002147 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002148 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002149 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002150 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002151 int flags /* Conflict resolution algorithms. */
2152){
danielk197718576932008-08-06 13:47:40 +00002153 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002154#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002155 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00002156 Table *p = pParse->pNewTable;
2157 int nByte;
2158 int i;
2159 int nCol;
2160 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002161
2162 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002163 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002164 if( pFromCol==0 ){
2165 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002166 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002167 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002168 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002169 " should reference only one column of table %T",
2170 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002171 goto fk_end;
2172 }
2173 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002174 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002175 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002176 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002177 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002178 goto fk_end;
2179 }else{
danielk19770202b292004-06-09 09:55:16 +00002180 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002181 }
drhe61922a2009-05-02 13:29:37 +00002182 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002183 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002184 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002185 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002186 }
2187 }
drh633e6d52008-07-28 19:34:53 +00002188 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002189 if( pFKey==0 ){
2190 goto fk_end;
2191 }
drhc2eef3b2002-08-31 18:53:06 +00002192 pFKey->pFrom = p;
2193 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002194 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002195 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002196 memcpy(z, pTo->z, pTo->n);
2197 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002198 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002199 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002200 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002201 if( pFromCol==0 ){
2202 pFKey->aCol[0].iFrom = p->nCol-1;
2203 }else{
2204 for(i=0; i<nCol; i++){
2205 int j;
2206 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002207 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002208 pFKey->aCol[i].iFrom = j;
2209 break;
2210 }
2211 }
2212 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002213 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002214 "unknown column \"%s\" in foreign key definition",
2215 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002216 goto fk_end;
2217 }
2218 }
2219 }
2220 if( pToCol ){
2221 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002222 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002223 pFKey->aCol[i].zCol = z;
2224 memcpy(z, pToCol->a[i].zName, n);
2225 z[n] = 0;
2226 z += n+1;
2227 }
2228 }
2229 pFKey->isDeferred = 0;
drh1bd10f82008-12-10 21:19:56 +00002230 pFKey->deleteConf = (u8)(flags & 0xff);
2231 pFKey->updateConf = (u8)((flags >> 8 ) & 0xff);
2232 pFKey->insertConf = (u8)((flags >> 16 ) & 0xff);
drhc2eef3b2002-08-31 18:53:06 +00002233
2234 /* Link the foreign key to the table as the last step.
2235 */
2236 p->pFKey = pFKey;
2237 pFKey = 0;
2238
2239fk_end:
drh633e6d52008-07-28 19:34:53 +00002240 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002241#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002242 sqlite3ExprListDelete(db, pFromCol);
2243 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002244}
2245
2246/*
2247** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2248** clause is seen as part of a foreign key definition. The isDeferred
2249** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2250** The behavior of the most recently created foreign key is adjusted
2251** accordingly.
2252*/
danielk19774adee202004-05-08 08:23:19 +00002253void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002254#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002255 Table *pTab;
2256 FKey *pFKey;
2257 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh1bd10f82008-12-10 21:19:56 +00002258 assert( isDeferred==0 || isDeferred==1 );
2259 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002260#endif
drhc2eef3b2002-08-31 18:53:06 +00002261}
2262
2263/*
drh063336a2004-11-05 20:58:39 +00002264** Generate code that will erase and refill index *pIdx. This is
2265** used to initialize a newly created index or to recompute the
2266** content of an index in response to a REINDEX command.
2267**
2268** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002269** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002270** root page number of the index. If memRootPage is negative, then
2271** the index already exists and must be cleared before being refilled and
2272** the root page number of the index is taken from pIndex->tnum.
2273*/
2274static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2275 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002276 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2277 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drh063336a2004-11-05 20:58:39 +00002278 int addr1; /* Address of top of loop */
2279 int tnum; /* Root page of index */
2280 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002281 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002282 int regIdxKey; /* Registers containing the index key */
2283 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002284 sqlite3 *db = pParse->db; /* The database connection */
2285 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002286
danielk19771d54df82004-11-23 15:41:16 +00002287#ifndef SQLITE_OMIT_AUTHORIZATION
2288 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002289 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002290 return;
2291 }
2292#endif
2293
danielk1977c00da102006-01-07 13:21:04 +00002294 /* Require a write-lock on the table to perform this operation */
2295 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2296
drh063336a2004-11-05 20:58:39 +00002297 v = sqlite3GetVdbe(pParse);
2298 if( v==0 ) return;
2299 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002300 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002301 }else{
2302 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002303 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002304 }
danielk1977b3bf5562006-01-10 17:58:23 +00002305 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002306 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002307 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002308 if( memRootPage>=0 ){
2309 sqlite3VdbeChangeP5(v, 1);
2310 }
danielk1977c00da102006-01-07 13:21:04 +00002311 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002312 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002313 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002314 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002315 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002316 const int regRowid = regIdxKey + pIndex->nColumn;
2317 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2318 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002319
danielk1977de630352009-05-04 11:42:29 +00002320 /* The registers accessed by the OP_IsUnique opcode were allocated
2321 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2322 ** call above. Just before that function was freed they were released
2323 ** (made available to the compiler for reuse) using
2324 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2325 ** opcode use the values stored within seems dangerous. However, since
2326 ** we can be sure that no other temp registers have been allocated
2327 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2328 */
2329 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
dane0af83a2009-09-08 19:15:01 +00002330 sqlite3HaltConstraint(
2331 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002332 }
drh2d401ab2008-01-10 23:50:11 +00002333 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
danielk1977de630352009-05-04 11:42:29 +00002334 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002335 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002336 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002337 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002338 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2339 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002340}
2341
2342/*
drh23bf66d2004-12-14 03:34:34 +00002343** Create a new index for an SQL table. pName1.pName2 is the name of the index
2344** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002345** be NULL for a primary key or an index that is created to satisfy a
2346** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002347** as the table to be indexed. pParse->pNewTable is a table that is
2348** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002349**
drh382c0242001-10-06 16:33:02 +00002350** pList is a list of columns to be indexed. pList will be NULL if this
2351** is a primary key or unique-constraint on the most recent column added
2352** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002353*/
danielk19774adee202004-05-08 08:23:19 +00002354void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002355 Parse *pParse, /* All information about this parse */
2356 Token *pName1, /* First part of index name. May be NULL */
2357 Token *pName2, /* Second part of index name. May be NULL */
2358 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002359 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002360 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002361 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002362 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002363 int sortOrder, /* Sort order of primary key when pList==NULL */
2364 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002365){
drhfdd6e852005-12-16 01:06:16 +00002366 Table *pTab = 0; /* Table to be indexed */
2367 Index *pIndex = 0; /* The index to be created */
2368 char *zName = 0; /* Name of the index */
2369 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002370 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002371 Token nullId; /* Fake token for an empty ID list */
2372 DbFixer sFix; /* For assigning database names to pTable */
2373 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002374 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002375 Db *pDb; /* The specific table containing the indexed database */
2376 int iDb; /* Index of the database that is being written */
2377 Token *pName = 0; /* Unqualified name of the index to create */
2378 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002379 int nCol;
2380 int nExtra = 0;
2381 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002382
drhd3001712009-05-12 17:46:53 +00002383 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
drh8af73d42009-05-13 22:58:28 +00002384 assert( pParse->nErr==0 ); /* Never called with prior errors */
2385 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002386 goto exit_create_index;
2387 }
2388 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002389 goto exit_create_index;
2390 }
drhdaffd0e2001-04-11 14:28:42 +00002391
drh75897232000-05-29 14:26:00 +00002392 /*
2393 ** Find the table that is to be indexed. Return early if not found.
2394 */
danielk1977cbb18d22004-05-28 11:37:27 +00002395 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002396
2397 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002398 ** to search for the table. 'Fix' the table name to this db
2399 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002400 */
2401 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002402 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002403 if( iDb<0 ) goto exit_create_index;
2404
danielk197753c0f742005-03-29 03:10:59 +00002405#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002406 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002407 ** is a temp table. If so, set the database to 1. Do not do this
2408 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002409 */
danielk1977fe910332007-12-02 11:46:34 +00002410 if( !db->init.busy ){
2411 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002412 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002413 iDb = 1;
2414 }
danielk1977ef2cb632004-05-29 02:37:19 +00002415 }
danielk197753c0f742005-03-29 03:10:59 +00002416#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002417
2418 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2419 sqlite3FixSrcList(&sFix, pTblName)
2420 ){
drh85c23c62005-08-20 03:03:04 +00002421 /* Because the parser constructs pTblName from a single identifier,
2422 ** sqlite3FixSrcList can never fail. */
2423 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002424 }
drhca424112008-01-25 15:04:48 +00002425 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002426 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002427 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002428 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002429 }else{
drhe3c41372001-09-17 20:25:58 +00002430 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002431 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002432 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002433 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002434 }
drhfdd6e852005-12-16 01:06:16 +00002435 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002436
drhd3001712009-05-12 17:46:53 +00002437 assert( pTab!=0 );
2438 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002439 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2440 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002441 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002442 goto exit_create_index;
2443 }
danielk1977576ec6b2005-01-21 11:55:25 +00002444#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002445 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002446 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002447 goto exit_create_index;
2448 }
danielk1977576ec6b2005-01-21 11:55:25 +00002449#endif
danielk19775ee9d692006-06-21 12:36:25 +00002450#ifndef SQLITE_OMIT_VIRTUALTABLE
2451 if( IsVirtual(pTab) ){
2452 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2453 goto exit_create_index;
2454 }
2455#endif
drh75897232000-05-29 14:26:00 +00002456
2457 /*
2458 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002459 ** index or table with the same name.
2460 **
2461 ** Exception: If we are reading the names of permanent indices from the
2462 ** sqlite_master table (because some other process changed the schema) and
2463 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002464 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002465 **
2466 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002467 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2468 ** own name.
drh75897232000-05-29 14:26:00 +00002469 */
danielk1977d8123362004-06-12 09:25:12 +00002470 if( pName ){
drh17435752007-08-16 04:30:38 +00002471 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002472 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002473 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002474 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002475 }
danielk1977d8123362004-06-12 09:25:12 +00002476 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002477 if( sqlite3FindTable(db, zName, 0)!=0 ){
2478 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2479 goto exit_create_index;
2480 }
2481 }
danielk197759a33f92007-03-17 10:26:59 +00002482 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2483 if( !ifNotExist ){
2484 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002485 }
danielk197759a33f92007-03-17 10:26:59 +00002486 goto exit_create_index;
2487 }
danielk1977a21c6b62005-01-24 10:25:59 +00002488 }else{
drhadbca9c2001-09-27 15:11:53 +00002489 int n;
2490 Index *pLoop;
2491 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002492 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002493 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002494 goto exit_create_index;
2495 }
drh75897232000-05-29 14:26:00 +00002496 }
2497
drhe5f9c642003-01-13 23:27:31 +00002498 /* Check for authorization to create an index.
2499 */
2500#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002501 {
drhfdd6e852005-12-16 01:06:16 +00002502 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002503 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002504 goto exit_create_index;
2505 }
2506 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002507 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002508 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002509 goto exit_create_index;
2510 }
drhe5f9c642003-01-13 23:27:31 +00002511 }
2512#endif
2513
drh75897232000-05-29 14:26:00 +00002514 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002515 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002516 ** So create a fake list to simulate this.
2517 */
2518 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002519 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002520 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002521 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002522 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002523 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002524 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002525 }
2526
danielk1977b3bf5562006-01-10 17:58:23 +00002527 /* Figure out how many bytes of space are required to store explicitly
2528 ** specified collation sequence names.
2529 */
2530 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002531 Expr *pExpr = pList->a[i].pExpr;
2532 if( pExpr ){
2533 CollSeq *pColl = pExpr->pColl;
2534 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2535 ** failure we have quit before reaching this point. */
2536 if( ALWAYS(pColl) ){
2537 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2538 }
danielk1977b3bf5562006-01-10 17:58:23 +00002539 }
2540 }
2541
drh75897232000-05-29 14:26:00 +00002542 /*
2543 ** Allocate the index structure.
2544 */
drhea678832008-12-10 19:26:22 +00002545 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002546 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002547 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002548 sizeof(Index) + /* Index structure */
2549 sizeof(int)*nCol + /* Index.aiColumn */
2550 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2551 sizeof(char *)*nCol + /* Index.azColl */
2552 sizeof(u8)*nCol + /* Index.aSortOrder */
2553 nName + 1 + /* Index.zName */
2554 nExtra /* Collation sequence names */
2555 );
drh17435752007-08-16 04:30:38 +00002556 if( db->mallocFailed ){
2557 goto exit_create_index;
2558 }
drh78aecb72006-02-10 18:08:09 +00002559 pIndex->azColl = (char**)(&pIndex[1]);
2560 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002561 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002562 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002563 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2564 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002565 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002566 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002567 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002568 pIndex->onError = (u8)onError;
2569 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002570 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002571
drhfdd6e852005-12-16 01:06:16 +00002572 /* Check to see if we should honor DESC requests on index columns
2573 */
danielk1977da184232006-01-05 11:34:32 +00002574 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002575 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002576 }else{
2577 sortOrderMask = 0; /* Ignore DESC */
2578 }
2579
drh1ccde152000-06-17 13:12:39 +00002580 /* Scan the names of the columns of the table to be indexed and
2581 ** load the column indices into the Index structure. Report an error
2582 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002583 **
2584 ** TODO: Add a test to make sure that the same column is not named
2585 ** more than once within the same index. Only the first instance of
2586 ** the column will ever be used by the optimizer. Note that using the
2587 ** same column more than once cannot be an error because that would
2588 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002589 */
drhfdd6e852005-12-16 01:06:16 +00002590 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2591 const char *zColName = pListItem->zName;
2592 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002593 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002594 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002595
drhfdd6e852005-12-16 01:06:16 +00002596 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2597 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002598 }
2599 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002600 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002601 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002602 goto exit_create_index;
2603 }
drh967e8b72000-06-21 13:59:10 +00002604 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002605 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2606 ** the way the "idxlist" non-terminal is constructed by the parser,
2607 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2608 ** must exist or else there must have been an OOM error. But if there
2609 ** was an OOM error, we would never reach this point. */
2610 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2611 int nColl;
2612 zColl = pListItem->pExpr->pColl->zName;
2613 nColl = sqlite3Strlen30(zColl) + 1;
2614 assert( nExtra>=nColl );
2615 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002616 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002617 zExtra += nColl;
2618 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002619 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002620 zColl = pTab->aCol[j].zColl;
2621 if( !zColl ){
2622 zColl = db->pDfltColl->zName;
2623 }
danielk19770202b292004-06-09 09:55:16 +00002624 }
drhb7f24de2009-05-13 17:35:23 +00002625 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002626 goto exit_create_index;
2627 }
danielk1977b3bf5562006-01-10 17:58:23 +00002628 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002629 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002630 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002631 }
drh51147ba2005-07-23 22:59:55 +00002632 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002633
danielk1977d8123362004-06-12 09:25:12 +00002634 if( pTab==pParse->pNewTable ){
2635 /* This routine has been called to create an automatic index as a
2636 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2637 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2638 ** i.e. one of:
2639 **
2640 ** CREATE TABLE t(x PRIMARY KEY, y);
2641 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2642 **
2643 ** Either way, check to see if the table already has such an index. If
2644 ** so, don't bother creating this one. This only applies to
2645 ** automatically created indices. Users can do as they wish with
2646 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002647 **
2648 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2649 ** (and thus suppressing the second one) even if they have different
2650 ** sort orders.
2651 **
2652 ** If there are different collating sequences or if the columns of
2653 ** the constraint occur in different orders, then the constraints are
2654 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002655 */
2656 Index *pIdx;
2657 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2658 int k;
2659 assert( pIdx->onError!=OE_None );
2660 assert( pIdx->autoIndex );
2661 assert( pIndex->onError!=OE_None );
2662
2663 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2664 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002665 const char *z1;
2666 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002667 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002668 z1 = pIdx->azColl[k];
2669 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002670 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002671 }
2672 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002673 if( pIdx->onError!=pIndex->onError ){
2674 /* This constraint creates the same index as a previous
2675 ** constraint specified somewhere in the CREATE TABLE statement.
2676 ** However the ON CONFLICT clauses are different. If both this
2677 ** constraint and the previous equivalent constraint have explicit
2678 ** ON CONFLICT clauses this is an error. Otherwise, use the
2679 ** explicitly specified behaviour for the index.
2680 */
2681 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2682 sqlite3ErrorMsg(pParse,
2683 "conflicting ON CONFLICT clauses specified", 0);
2684 }
2685 if( pIdx->onError==OE_Default ){
2686 pIdx->onError = pIndex->onError;
2687 }
2688 }
danielk1977d8123362004-06-12 09:25:12 +00002689 goto exit_create_index;
2690 }
2691 }
2692 }
2693
drh75897232000-05-29 14:26:00 +00002694 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002695 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002696 */
drh234c39d2004-07-24 03:30:47 +00002697 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002698 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002699 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002700 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002701 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002702 if( p ){
2703 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002704 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002705 goto exit_create_index;
2706 }
drh5e00f6c2001-09-13 13:46:56 +00002707 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002708 if( pTblName!=0 ){
2709 pIndex->tnum = db->init.newTnum;
2710 }
drhd78eeee2001-09-13 16:18:53 +00002711 }
2712
drh1d85d932004-02-14 23:05:52 +00002713 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002714 ** involves writing the index into the master table and filling in the
2715 ** index with the current table contents.
2716 **
drh1d85d932004-02-14 23:05:52 +00002717 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2718 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002719 ** CREATE INDEX statements are read out of the master table. In
2720 ** the latter case the index already exists on disk, which is why
2721 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002722 **
danielk1977cbb18d22004-05-28 11:37:27 +00002723 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002724 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2725 ** has just been created, it contains no data and the index initialization
2726 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002727 */
drhd3001712009-05-12 17:46:53 +00002728 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002729 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002730 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002731 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002732
danielk19774adee202004-05-08 08:23:19 +00002733 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002734 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002735
drhfdd6e852005-12-16 01:06:16 +00002736
drh063336a2004-11-05 20:58:39 +00002737 /* Create the rootpage for the index
2738 */
drhaee128d2005-02-14 20:48:18 +00002739 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002740 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002741
2742 /* Gather the complete text of the CREATE INDEX statement into
2743 ** the zStmt variable
2744 */
drhd3001712009-05-12 17:46:53 +00002745 if( pStart ){
2746 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002747 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002748 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002749 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002750 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002751 pName->z);
2752 }else{
2753 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002754 /* zStmt = sqlite3MPrintf(""); */
2755 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002756 }
drh063336a2004-11-05 20:58:39 +00002757
2758 /* Add an entry in sqlite_master for this index
2759 */
2760 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002761 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002762 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2763 pIndex->zName,
2764 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002765 iMem,
drh063336a2004-11-05 20:58:39 +00002766 zStmt
2767 );
drh633e6d52008-07-28 19:34:53 +00002768 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002769
danielk1977a21c6b62005-01-24 10:25:59 +00002770 /* Fill the index with data and reparse the schema. Code an OP_Expire
2771 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002772 */
danielk1977cbb18d22004-05-28 11:37:27 +00002773 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002774 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002775 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002776 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2777 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2778 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002779 }
drh75897232000-05-29 14:26:00 +00002780 }
2781
danielk1977d8123362004-06-12 09:25:12 +00002782 /* When adding an index to the list of indices for a table, make
2783 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002784 ** OE_Ignore. This is necessary for the correct constraint check
2785 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2786 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002787 */
drh234c39d2004-07-24 03:30:47 +00002788 if( db->init.busy || pTblName==0 ){
2789 if( onError!=OE_Replace || pTab->pIndex==0
2790 || pTab->pIndex->onError==OE_Replace){
2791 pIndex->pNext = pTab->pIndex;
2792 pTab->pIndex = pIndex;
2793 }else{
2794 Index *pOther = pTab->pIndex;
2795 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2796 pOther = pOther->pNext;
2797 }
2798 pIndex->pNext = pOther->pNext;
2799 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002800 }
drh234c39d2004-07-24 03:30:47 +00002801 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002802 }
danielk1977d8123362004-06-12 09:25:12 +00002803
drh75897232000-05-29 14:26:00 +00002804 /* Clean up before exiting */
2805exit_create_index:
drh956bc922004-07-24 17:38:29 +00002806 if( pIndex ){
danielk1977cb9d8d82009-03-18 18:43:36 +00002807 sqlite3_free(pIndex->zColAff);
2808 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002809 }
drh633e6d52008-07-28 19:34:53 +00002810 sqlite3ExprListDelete(db, pList);
2811 sqlite3SrcListDelete(db, pTblName);
2812 sqlite3DbFree(db, zName);
drh75897232000-05-29 14:26:00 +00002813 return;
2814}
2815
2816/*
drh51147ba2005-07-23 22:59:55 +00002817** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002818** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002819**
2820** aiRowEst[0] is suppose to contain the number of elements in the index.
2821** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2822** number of rows in the table that match any particular value of the
2823** first column of the index. aiRowEst[2] is an estimate of the number
2824** of rows that match any particular combiniation of the first 2 columns
2825** of the index. And so forth. It must always be the case that
2826*
2827** aiRowEst[N]<=aiRowEst[N-1]
2828** aiRowEst[N]>=1
2829**
2830** Apart from that, we have little to go on besides intuition as to
2831** how aiRowEst[] should be initialized. The numbers generated here
2832** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002833*/
2834void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002835 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002836 int i;
drh28c4cf42005-07-27 20:41:43 +00002837 assert( a!=0 );
2838 a[0] = 1000000;
drhdb513882006-05-11 23:14:59 +00002839 for(i=pIdx->nColumn; i>=5; i--){
2840 a[i] = 5;
2841 }
2842 while( i>=1 ){
2843 a[i] = 11 - i;
2844 i--;
drh28c4cf42005-07-27 20:41:43 +00002845 }
2846 if( pIdx->onError!=OE_None ){
2847 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002848 }
2849}
2850
2851/*
drh74e24cd2002-01-09 03:19:59 +00002852** This routine will drop an existing named index. This routine
2853** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002854*/
drh4d91a702006-01-04 15:54:36 +00002855void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002856 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002857 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002858 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002859 int iDb;
drh75897232000-05-29 14:26:00 +00002860
drh8af73d42009-05-13 22:58:28 +00002861 assert( pParse->nErr==0 ); /* Never called with prior errors */
2862 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002863 goto exit_drop_index;
2864 }
drhd24cc422003-03-27 12:51:24 +00002865 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002866 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2867 goto exit_drop_index;
2868 }
danielk19774adee202004-05-08 08:23:19 +00002869 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002870 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002871 if( !ifExists ){
2872 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2873 }
drha6ecd332004-06-10 00:29:09 +00002874 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002875 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002876 }
drh485b39b2002-07-13 03:11:52 +00002877 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002878 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002879 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002880 goto exit_drop_index;
2881 }
danielk1977da184232006-01-05 11:34:32 +00002882 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002883#ifndef SQLITE_OMIT_AUTHORIZATION
2884 {
2885 int code = SQLITE_DROP_INDEX;
2886 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002887 const char *zDb = db->aDb[iDb].zName;
2888 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002889 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002890 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002891 }
danielk1977da184232006-01-05 11:34:32 +00002892 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002893 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002894 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002895 }
drhed6c8672003-01-12 18:02:16 +00002896 }
drhe5f9c642003-01-13 23:27:31 +00002897#endif
drh75897232000-05-29 14:26:00 +00002898
2899 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002900 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002901 if( v ){
drh77658e22007-12-04 16:54:52 +00002902 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002903 sqlite3NestedParse(pParse,
2904 "DELETE FROM %Q.%s WHERE name=%Q",
2905 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2906 pIndex->zName
2907 );
danielk1977006015d2008-04-11 17:11:26 +00002908 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2909 sqlite3NestedParse(pParse,
2910 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2911 db->aDb[iDb].zName, pIndex->zName
2912 );
2913 }
drh9cbf3422008-01-17 16:22:13 +00002914 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002915 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002916 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002917 }
2918
drhd24cc422003-03-27 12:51:24 +00002919exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002920 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002921}
2922
2923/*
drhcf643722007-03-27 13:36:37 +00002924** pArray is a pointer to an array of objects. Each object in the
2925** array is szEntry bytes in size. This routine allocates a new
2926** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002927**
drhcf643722007-03-27 13:36:37 +00002928** *pnEntry is the number of entries already in use. *pnAlloc is
2929** the previously allocated size of the array. initSize is the
2930** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002931**
drhcf643722007-03-27 13:36:37 +00002932** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002933**
drhcf643722007-03-27 13:36:37 +00002934** This routine returns a pointer to the array of objects. This
2935** might be the same as the pArray parameter or it might be a different
2936** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002937*/
drhcf643722007-03-27 13:36:37 +00002938void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002939 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002940 void *pArray, /* Array of objects. Might be reallocated */
2941 int szEntry, /* Size of each object in the array */
2942 int initSize, /* Suggested initial allocation, in elements */
2943 int *pnEntry, /* Number of objects currently in use */
2944 int *pnAlloc, /* Current size of the allocation, in elements */
2945 int *pIdx /* Write the index of a new slot here */
2946){
2947 char *z;
2948 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002949 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002950 int newSize;
drhcf643722007-03-27 13:36:37 +00002951 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002952 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002953 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002954 *pIdx = -1;
2955 return pArray;
drh13449892005-09-07 21:22:45 +00002956 }
drh6a1e0712008-12-05 15:24:15 +00002957 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002958 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002959 }
drhcf643722007-03-27 13:36:37 +00002960 z = (char*)pArray;
2961 memset(&z[*pnEntry * szEntry], 0, szEntry);
2962 *pIdx = *pnEntry;
2963 ++*pnEntry;
2964 return pArray;
drh13449892005-09-07 21:22:45 +00002965}
2966
2967/*
drh75897232000-05-29 14:26:00 +00002968** Append a new element to the given IdList. Create a new IdList if
2969** need be.
drhdaffd0e2001-04-11 14:28:42 +00002970**
2971** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002972*/
drh17435752007-08-16 04:30:38 +00002973IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002974 int i;
drh75897232000-05-29 14:26:00 +00002975 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002976 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002977 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002978 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002979 }
drhcf643722007-03-27 13:36:37 +00002980 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002981 db,
drhcf643722007-03-27 13:36:37 +00002982 pList->a,
2983 sizeof(pList->a[0]),
2984 5,
2985 &pList->nId,
2986 &pList->nAlloc,
2987 &i
2988 );
drh13449892005-09-07 21:22:45 +00002989 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002990 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002991 return 0;
drh75897232000-05-29 14:26:00 +00002992 }
drh17435752007-08-16 04:30:38 +00002993 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002994 return pList;
2995}
2996
2997/*
drhfe05af82005-07-21 03:14:59 +00002998** Delete an IdList.
2999*/
drh633e6d52008-07-28 19:34:53 +00003000void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003001 int i;
3002 if( pList==0 ) return;
3003 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003004 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003005 }
drh633e6d52008-07-28 19:34:53 +00003006 sqlite3DbFree(db, pList->a);
3007 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003008}
3009
3010/*
3011** Return the index in pList of the identifier named zId. Return -1
3012** if not found.
3013*/
3014int sqlite3IdListIndex(IdList *pList, const char *zName){
3015 int i;
3016 if( pList==0 ) return -1;
3017 for(i=0; i<pList->nId; i++){
3018 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3019 }
3020 return -1;
3021}
3022
3023/*
drha78c22c2008-11-11 18:28:58 +00003024** Expand the space allocated for the given SrcList object by
3025** creating nExtra new slots beginning at iStart. iStart is zero based.
3026** New slots are zeroed.
3027**
3028** For example, suppose a SrcList initially contains two entries: A,B.
3029** To append 3 new entries onto the end, do this:
3030**
3031** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3032**
3033** After the call above it would contain: A, B, nil, nil, nil.
3034** If the iStart argument had been 1 instead of 2, then the result
3035** would have been: A, nil, nil, nil, B. To prepend the new slots,
3036** the iStart value would be 0. The result then would
3037** be: nil, nil, nil, A, B.
3038**
3039** If a memory allocation fails the SrcList is unchanged. The
3040** db->mallocFailed flag will be set to true.
3041*/
3042SrcList *sqlite3SrcListEnlarge(
3043 sqlite3 *db, /* Database connection to notify of OOM errors */
3044 SrcList *pSrc, /* The SrcList to be enlarged */
3045 int nExtra, /* Number of new slots to add to pSrc->a[] */
3046 int iStart /* Index in pSrc->a[] of first new slot */
3047){
3048 int i;
3049
3050 /* Sanity checking on calling parameters */
3051 assert( iStart>=0 );
3052 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003053 assert( pSrc!=0 );
3054 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003055
3056 /* Allocate additional space if needed */
3057 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3058 SrcList *pNew;
3059 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003060 int nGot;
drha78c22c2008-11-11 18:28:58 +00003061 pNew = sqlite3DbRealloc(db, pSrc,
3062 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3063 if( pNew==0 ){
3064 assert( db->mallocFailed );
3065 return pSrc;
3066 }
3067 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003068 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003069 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003070 }
3071
3072 /* Move existing slots that come after the newly inserted slots
3073 ** out of the way */
3074 for(i=pSrc->nSrc-1; i>=iStart; i--){
3075 pSrc->a[i+nExtra] = pSrc->a[i];
3076 }
shane18e526c2008-12-10 22:30:24 +00003077 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003078
3079 /* Zero the newly allocated slots */
3080 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3081 for(i=iStart; i<iStart+nExtra; i++){
3082 pSrc->a[i].iCursor = -1;
3083 }
3084
3085 /* Return a pointer to the enlarged SrcList */
3086 return pSrc;
3087}
3088
3089
3090/*
drhad3cab52002-05-24 02:04:32 +00003091** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003092** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003093**
drha78c22c2008-11-11 18:28:58 +00003094** A SrcList is returned, or NULL if there is an OOM error. The returned
3095** SrcList might be the same as the SrcList that was input or it might be
3096** a new one. If an OOM error does occurs, then the prior value of pList
3097** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003098**
3099** If pDatabase is not null, it means that the table has an optional
3100** database name prefix. Like this: "database.table". The pDatabase
3101** points to the table name and the pTable points to the database name.
3102** The SrcList.a[].zName field is filled with the table name which might
3103** come from pTable (if pDatabase is NULL) or from pDatabase.
3104** SrcList.a[].zDatabase is filled with the database name from pTable,
3105** or with NULL if no database is specified.
3106**
3107** In other words, if call like this:
3108**
drh17435752007-08-16 04:30:38 +00003109** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003110**
3111** Then B is a table name and the database name is unspecified. If called
3112** like this:
3113**
drh17435752007-08-16 04:30:38 +00003114** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003115**
drhd3001712009-05-12 17:46:53 +00003116** Then C is the table name and B is the database name. If C is defined
3117** then so is B. In other words, we never have a case where:
3118**
3119** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003120**
3121** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3122** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003123*/
drh17435752007-08-16 04:30:38 +00003124SrcList *sqlite3SrcListAppend(
3125 sqlite3 *db, /* Connection to notify of malloc failures */
3126 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3127 Token *pTable, /* Table to append */
3128 Token *pDatabase /* Database of the table */
3129){
drha99db3b2004-06-19 14:49:12 +00003130 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003131 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003132 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003133 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003134 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003135 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003136 }
drha78c22c2008-11-11 18:28:58 +00003137 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3138 if( db->mallocFailed ){
3139 sqlite3SrcListDelete(db, pList);
3140 return 0;
drhad3cab52002-05-24 02:04:32 +00003141 }
drha78c22c2008-11-11 18:28:58 +00003142 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003143 if( pDatabase && pDatabase->z==0 ){
3144 pDatabase = 0;
3145 }
drhd3001712009-05-12 17:46:53 +00003146 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003147 Token *pTemp = pDatabase;
3148 pDatabase = pTable;
3149 pTable = pTemp;
3150 }
drh17435752007-08-16 04:30:38 +00003151 pItem->zName = sqlite3NameFromToken(db, pTable);
3152 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003153 return pList;
3154}
3155
3156/*
drhdfe88ec2008-11-03 20:55:06 +00003157** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003158*/
danielk19774adee202004-05-08 08:23:19 +00003159void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003160 int i;
drh9b3187e2005-01-18 14:45:47 +00003161 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003162 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003163 if( pList ){
3164 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3165 if( pItem->iCursor>=0 ) break;
3166 pItem->iCursor = pParse->nTab++;
3167 if( pItem->pSelect ){
3168 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3169 }
drh63eb5f22003-04-29 16:20:44 +00003170 }
3171 }
3172}
3173
3174/*
drhad3cab52002-05-24 02:04:32 +00003175** Delete an entire SrcList including all its substructure.
3176*/
drh633e6d52008-07-28 19:34:53 +00003177void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003178 int i;
drhbe5c89a2004-07-26 00:31:09 +00003179 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003180 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003181 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003182 sqlite3DbFree(db, pItem->zDatabase);
3183 sqlite3DbFree(db, pItem->zName);
3184 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003185 sqlite3DbFree(db, pItem->zIndex);
danielk1977a04a34f2007-04-16 15:06:25 +00003186 sqlite3DeleteTable(pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003187 sqlite3SelectDelete(db, pItem->pSelect);
3188 sqlite3ExprDelete(db, pItem->pOn);
3189 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003190 }
drh633e6d52008-07-28 19:34:53 +00003191 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003192}
3193
drh982cef72000-05-30 16:27:03 +00003194/*
drh61dfc312006-12-16 16:25:15 +00003195** This routine is called by the parser to add a new term to the
3196** end of a growing FROM clause. The "p" parameter is the part of
3197** the FROM clause that has already been constructed. "p" is NULL
3198** if this is the first term of the FROM clause. pTable and pDatabase
3199** are the name of the table and database named in the FROM clause term.
3200** pDatabase is NULL if the database name qualifier is missing - the
3201** usual case. If the term has a alias, then pAlias points to the
3202** alias token. If the term is a subquery, then pSubquery is the
3203** SELECT statement that the subquery encodes. The pTable and
3204** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3205** parameters are the content of the ON and USING clauses.
3206**
3207** Return a new SrcList which encodes is the FROM with the new
3208** term added.
3209*/
3210SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003211 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003212 SrcList *p, /* The left part of the FROM clause already seen */
3213 Token *pTable, /* Name of the table to add to the FROM clause */
3214 Token *pDatabase, /* Name of the database containing pTable */
3215 Token *pAlias, /* The right-hand side of the AS subexpression */
3216 Select *pSubquery, /* A subquery used in place of a table name */
3217 Expr *pOn, /* The ON clause of a join */
3218 IdList *pUsing /* The USING clause of a join */
3219){
3220 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003221 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003222 if( !p && (pOn || pUsing) ){
3223 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3224 (pOn ? "ON" : "USING")
3225 );
3226 goto append_from_error;
3227 }
drh17435752007-08-16 04:30:38 +00003228 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003229 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003230 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003231 }
3232 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003233 assert( pAlias!=0 );
3234 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003235 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003236 }
3237 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003238 pItem->pOn = pOn;
3239 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003240 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003241
3242 append_from_error:
3243 assert( p==0 );
3244 sqlite3ExprDelete(db, pOn);
3245 sqlite3IdListDelete(db, pUsing);
3246 sqlite3SelectDelete(db, pSubquery);
3247 return 0;
drh61dfc312006-12-16 16:25:15 +00003248}
3249
3250/*
danielk1977b1c685b2008-10-06 16:18:39 +00003251** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3252** element of the source-list passed as the second argument.
3253*/
3254void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003255 assert( pIndexedBy!=0 );
3256 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003257 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3258 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3259 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3260 /* A "NOT INDEXED" clause was supplied. See parse.y
3261 ** construct "indexed_opt" for details. */
3262 pItem->notIndexed = 1;
3263 }else{
3264 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3265 }
3266 }
3267}
3268
3269/*
drh61dfc312006-12-16 16:25:15 +00003270** When building up a FROM clause in the parser, the join operator
3271** is initially attached to the left operand. But the code generator
3272** expects the join operator to be on the right operand. This routine
3273** Shifts all join operators from left to right for an entire FROM
3274** clause.
3275**
3276** Example: Suppose the join is like this:
3277**
3278** A natural cross join B
3279**
3280** The operator is "natural cross join". The A and B operands are stored
3281** in p->a[0] and p->a[1], respectively. The parser initially stores the
3282** operator with A. This routine shifts that operator over to B.
3283*/
3284void sqlite3SrcListShiftJoinType(SrcList *p){
3285 if( p && p->a ){
3286 int i;
3287 for(i=p->nSrc-1; i>0; i--){
3288 p->a[i].jointype = p->a[i-1].jointype;
3289 }
3290 p->a[0].jointype = 0;
3291 }
3292}
3293
3294/*
drhc4a3c772001-04-04 11:48:57 +00003295** Begin a transaction
3296*/
drh684917c2004-10-05 02:41:42 +00003297void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003298 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003299 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003300 int i;
drh5e00f6c2001-09-13 13:46:56 +00003301
drhd3001712009-05-12 17:46:53 +00003302 assert( pParse!=0 );
3303 db = pParse->db;
3304 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003305/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003306 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3307 return;
3308 }
danielk19771d850a72004-05-31 08:26:49 +00003309 v = sqlite3GetVdbe(pParse);
3310 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003311 if( type!=TK_DEFERRED ){
3312 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003313 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003314 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003315 }
3316 }
drh66a51672008-01-03 00:01:23 +00003317 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003318}
3319
3320/*
3321** Commit a transaction
3322*/
danielk19774adee202004-05-08 08:23:19 +00003323void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003324 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003325 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003326
drhd3001712009-05-12 17:46:53 +00003327 assert( pParse!=0 );
3328 db = pParse->db;
3329 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003330/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003331 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3332 return;
3333 }
danielk19771d850a72004-05-31 08:26:49 +00003334 v = sqlite3GetVdbe(pParse);
3335 if( v ){
drh66a51672008-01-03 00:01:23 +00003336 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003337 }
drhc4a3c772001-04-04 11:48:57 +00003338}
3339
3340/*
3341** Rollback a transaction
3342*/
danielk19774adee202004-05-08 08:23:19 +00003343void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003344 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003345 Vdbe *v;
3346
drhd3001712009-05-12 17:46:53 +00003347 assert( pParse!=0 );
3348 db = pParse->db;
3349 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003350/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003351 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3352 return;
3353 }
danielk19774adee202004-05-08 08:23:19 +00003354 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003355 if( v ){
drh66a51672008-01-03 00:01:23 +00003356 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003357 }
drhc4a3c772001-04-04 11:48:57 +00003358}
drhf57b14a2001-09-14 18:54:08 +00003359
3360/*
danielk1977fd7f0452008-12-17 17:30:26 +00003361** This function is called by the parser when it parses a command to create,
3362** release or rollback an SQL savepoint.
3363*/
3364void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003365 char *zName = sqlite3NameFromToken(pParse->db, pName);
3366 if( zName ){
3367 Vdbe *v = sqlite3GetVdbe(pParse);
3368#ifndef SQLITE_OMIT_AUTHORIZATION
3369 static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3370 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3371#endif
3372 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3373 sqlite3DbFree(pParse->db, zName);
3374 return;
3375 }
3376 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003377 }
3378}
3379
3380/*
drhdc3ff9c2004-08-18 02:10:15 +00003381** Make sure the TEMP database is open and available for use. Return
3382** the number of errors. Leave any error messages in the pParse structure.
3383*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003384int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003385 sqlite3 *db = pParse->db;
3386 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003387 int rc;
3388 static const int flags =
3389 SQLITE_OPEN_READWRITE |
3390 SQLITE_OPEN_CREATE |
3391 SQLITE_OPEN_EXCLUSIVE |
3392 SQLITE_OPEN_DELETEONCLOSE |
3393 SQLITE_OPEN_TEMP_DB;
3394
3395 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
drhc797d4d2007-05-08 01:08:49 +00003396 &db->aDb[1].pBt);
drhdc3ff9c2004-08-18 02:10:15 +00003397 if( rc!=SQLITE_OK ){
3398 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3399 "file for storing temporary tables");
3400 pParse->rc = rc;
3401 return 1;
3402 }
drh60a713c2008-01-21 16:22:45 +00003403 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
danielk197714db2662006-01-09 16:12:04 +00003404 assert( db->aDb[1].pSchema );
drhfdc40e92008-04-17 20:59:37 +00003405 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
3406 db->dfltJournalMode);
drhdc3ff9c2004-08-18 02:10:15 +00003407 }
3408 return 0;
3409}
3410
3411/*
drh80242052004-06-09 00:48:12 +00003412** Generate VDBE code that will verify the schema cookie and start
3413** a read-transaction for all named database files.
3414**
3415** It is important that all schema cookies be verified and all
3416** read transactions be started before anything else happens in
3417** the VDBE program. But this routine can be called after much other
3418** code has been generated. So here is what we do:
3419**
drhc275b4e2004-07-19 17:25:24 +00003420** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003421** will jump to a subroutine at the end of the program. Then we
3422** record every database that needs its schema verified in the
3423** pParse->cookieMask field. Later, after all other code has been
3424** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003425** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003426** will be made to point to that subroutine. The generation of the
3427** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003428**
3429** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3430** schema on any databases. This can be used to position the OP_Goto
3431** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003432*/
danielk19774adee202004-05-08 08:23:19 +00003433void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003434 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003435
dan65a7cd12009-09-01 12:16:01 +00003436 if( pToplevel->cookieGoto==0 ){
3437 Vdbe *v = sqlite3GetVdbe(pToplevel);
3438 if( v==0 ) return; /* This only happens if there was a prior error */
3439 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003440 }
drhc275b4e2004-07-19 17:25:24 +00003441 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003442 sqlite3 *db = pToplevel->db;
3443 int mask;
3444
drhc275b4e2004-07-19 17:25:24 +00003445 assert( iDb<db->nDb );
3446 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003447 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003448 mask = 1<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003449 if( (pToplevel->cookieMask & mask)==0 ){
3450 pToplevel->cookieMask |= mask;
3451 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003452 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003453 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003454 }
drhc275b4e2004-07-19 17:25:24 +00003455 }
drh001bbcb2003-03-19 03:14:00 +00003456 }
drh001bbcb2003-03-19 03:14:00 +00003457}
3458
3459/*
drh1c928532002-01-31 15:54:21 +00003460** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003461** might change the database.
3462**
3463** This routine starts a new transaction if we are not already within
3464** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003465** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003466** be set for operations that might fail (due to a constraint) part of
3467** the way through and which will need to undo some writes without having to
3468** rollback the whole transaction. For operations where all constraints
3469** can be checked before any changes are made to the database, it is never
3470** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003471*/
drh7f0f12e2004-05-21 13:39:50 +00003472void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003473 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003474 sqlite3CodeVerifySchema(pParse, iDb);
dan65a7cd12009-09-01 12:16:01 +00003475 pToplevel->writeMask |= 1<<iDb;
dane0af83a2009-09-08 19:15:01 +00003476 pToplevel->isMultiWrite |= setStatement;
3477}
3478
3479/*
3480** Set the "may throw abort exception" flag for the statement currently
3481** being coded.
3482*/
3483void sqlite3MayAbort(Parse *pParse){
3484 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3485 pToplevel->mayAbort = 1;
3486}
3487
3488/*
3489** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3490** error. The onError parameter determines which (if any) of the statement
3491** and/or current transaction is rolled back.
3492*/
3493void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3494 Vdbe *v = sqlite3GetVdbe(pParse);
3495 if( onError==OE_Abort ){
3496 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003497 }
dane0af83a2009-09-08 19:15:01 +00003498 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003499}
3500
drh4343fea2004-11-05 23:46:15 +00003501/*
3502** Check to see if pIndex uses the collating sequence pColl. Return
3503** true if it does and false if it does not.
3504*/
3505#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003506static int collationMatch(const char *zColl, Index *pIndex){
3507 int i;
drh04491712009-05-13 17:21:13 +00003508 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003509 for(i=0; i<pIndex->nColumn; i++){
3510 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003511 assert( z!=0 );
3512 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003513 return 1;
3514 }
drh4343fea2004-11-05 23:46:15 +00003515 }
3516 return 0;
3517}
3518#endif
3519
3520/*
3521** Recompute all indices of pTab that use the collating sequence pColl.
3522** If pColl==0 then recompute all indices of pTab.
3523*/
3524#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003525static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003526 Index *pIndex; /* An index associated with pTab */
3527
3528 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003529 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003530 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3531 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003532 sqlite3RefillIndex(pParse, pIndex, -1);
3533 }
3534 }
3535}
3536#endif
3537
3538/*
3539** Recompute all indices of all tables in all databases where the
3540** indices use the collating sequence pColl. If pColl==0 then recompute
3541** all indices everywhere.
3542*/
3543#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003544static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003545 Db *pDb; /* A single database */
3546 int iDb; /* The database index number */
3547 sqlite3 *db = pParse->db; /* The database connection */
3548 HashElem *k; /* For looping over tables in pDb */
3549 Table *pTab; /* A table in the database */
3550
3551 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003552 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003553 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003554 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003555 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003556 }
3557 }
3558}
3559#endif
3560
3561/*
drheee46cf2004-11-06 00:02:48 +00003562** Generate code for the REINDEX command.
3563**
3564** REINDEX -- 1
3565** REINDEX <collation> -- 2
3566** REINDEX ?<database>.?<tablename> -- 3
3567** REINDEX ?<database>.?<indexname> -- 4
3568**
3569** Form 1 causes all indices in all attached databases to be rebuilt.
3570** Form 2 rebuilds all indices in all databases that use the named
3571** collating function. Forms 3 and 4 rebuild the named index or all
3572** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003573*/
3574#ifndef SQLITE_OMIT_REINDEX
3575void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3576 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3577 char *z; /* Name of a table or index */
3578 const char *zDb; /* Name of the database */
3579 Table *pTab; /* A table in the database */
3580 Index *pIndex; /* An index associated with pTab */
3581 int iDb; /* The database index number */
3582 sqlite3 *db = pParse->db; /* The database connection */
3583 Token *pObjName; /* Name of the table or index to be reindexed */
3584
danielk197733a5edc2005-01-27 00:22:02 +00003585 /* Read the database schema. If an error occurs, leave an error message
3586 ** and code in pParse and return NULL. */
3587 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003588 return;
danielk197733a5edc2005-01-27 00:22:02 +00003589 }
3590
drh8af73d42009-05-13 22:58:28 +00003591 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003592 reindexDatabases(pParse, 0);
3593 return;
drhd3001712009-05-12 17:46:53 +00003594 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003595 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003596 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003597 zColl = sqlite3NameFromToken(pParse->db, pName1);
3598 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003599 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003600 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003601 reindexDatabases(pParse, zColl);
3602 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003603 return;
3604 }
drh633e6d52008-07-28 19:34:53 +00003605 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003606 }
3607 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3608 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003609 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003610 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003611 zDb = db->aDb[iDb].zName;
3612 pTab = sqlite3FindTable(db, z, zDb);
3613 if( pTab ){
3614 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003615 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003616 return;
3617 }
3618 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003619 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003620 if( pIndex ){
3621 sqlite3BeginWriteOperation(pParse, 0, iDb);
3622 sqlite3RefillIndex(pParse, pIndex, -1);
3623 return;
3624 }
3625 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3626}
3627#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003628
3629/*
3630** Return a dynamicly allocated KeyInfo structure that can be used
3631** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3632**
3633** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003634** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003635** pointer. If an error occurs (out of memory or missing collation
3636** sequence), NULL is returned and the state of pParse updated to reflect
3637** the error.
3638*/
3639KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3640 int i;
3641 int nCol = pIdx->nColumn;
3642 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003643 sqlite3 *db = pParse->db;
3644 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003645
3646 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003647 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003648 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3649 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3650 for(i=0; i<nCol; i++){
3651 char *zColl = pIdx->azColl[i];
3652 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003653 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003654 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3655 }
drh1bd10f82008-12-10 21:19:56 +00003656 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003657 }
3658
3659 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003660 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003661 pKey = 0;
3662 }
3663 return pKey;
3664}