blob: 7e73b6a8ebb36d2b8a06641364d46c277fe6eccd [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhb19a2bc2001-09-16 00:13:26 +000012** This file contains C code routines that are called by the SQLite parser
13** when syntax rules are reduced. The routines in this file handle the
14** following kinds of SQL syntax:
drh75897232000-05-29 14:26:00 +000015**
drhbed86902000-06-02 13:27:59 +000016** CREATE TABLE
17** DROP TABLE
18** CREATE INDEX
19** DROP INDEX
drh832508b2002-03-02 17:04:07 +000020** creating ID lists
drhb19a2bc2001-09-16 00:13:26 +000021** BEGIN TRANSACTION
22** COMMIT
23** ROLLBACK
drh75897232000-05-29 14:26:00 +000024*/
25#include "sqliteInt.h"
26
27/*
drhe0bc4042002-06-25 01:09:11 +000028** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000029** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000030*/
danielk19774adee202004-05-08 08:23:19 +000031void sqlite3BeginParse(Parse *pParse, int explainFlag){
drh1bd10f82008-12-10 21:19:56 +000032 pParse->explain = (u8)explainFlag;
drh7c972de2003-09-06 22:18:07 +000033 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000034}
35
danielk1977c00da102006-01-07 13:21:04 +000036#ifndef SQLITE_OMIT_SHARED_CACHE
37/*
38** The TableLock structure is only used by the sqlite3TableLock() and
39** codeTableLocks() functions.
40*/
41struct TableLock {
drhd698bc12006-03-23 23:33:26 +000042 int iDb; /* The database containing the table to be locked */
43 int iTab; /* The root page of the table to be locked */
44 u8 isWriteLock; /* True for write lock. False for a read lock */
45 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000046};
47
48/*
drhd698bc12006-03-23 23:33:26 +000049** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000050**
drhd698bc12006-03-23 23:33:26 +000051** The table to be locked has root page iTab and is found in database iDb.
52** A read or a write lock can be taken depending on isWritelock.
53**
54** This routine just records the fact that the lock is desired. The
55** code to make the lock occur is generated by a later call to
56** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000057*/
58void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000059 Parse *pParse, /* Parsing context */
60 int iDb, /* Index of the database containing the table to lock */
61 int iTab, /* Root page number of the table to be locked */
62 u8 isWriteLock, /* True for a write lock */
63 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000064){
dan65a7cd12009-09-01 12:16:01 +000065 Parse *pToplevel = sqlite3ParseToplevel(pParse);
danielk1977c00da102006-01-07 13:21:04 +000066 int i;
67 int nBytes;
68 TableLock *p;
drh8af73d42009-05-13 22:58:28 +000069 assert( iDb>=0 );
dan165921a2009-08-28 18:53:45 +000070
dan65a7cd12009-09-01 12:16:01 +000071 for(i=0; i<pToplevel->nTableLock; i++){
72 p = &pToplevel->aTableLock[i];
danielk1977c00da102006-01-07 13:21:04 +000073 if( p->iDb==iDb && p->iTab==iTab ){
74 p->isWriteLock = (p->isWriteLock || isWriteLock);
75 return;
76 }
77 }
78
dan65a7cd12009-09-01 12:16:01 +000079 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80 pToplevel->aTableLock =
81 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82 if( pToplevel->aTableLock ){
83 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
danielk1977c00da102006-01-07 13:21:04 +000084 p->iDb = iDb;
85 p->iTab = iTab;
86 p->isWriteLock = isWriteLock;
87 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000088 }else{
dan65a7cd12009-09-01 12:16:01 +000089 pToplevel->nTableLock = 0;
90 pToplevel->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000091 }
92}
93
94/*
95** Code an OP_TableLock instruction for each table locked by the
96** statement (configured by calls to sqlite3TableLock()).
97*/
98static void codeTableLocks(Parse *pParse){
99 int i;
100 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000101
drh04491712009-05-13 17:21:13 +0000102 pVdbe = sqlite3GetVdbe(pParse);
103 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
danielk1977c00da102006-01-07 13:21:04 +0000104
105 for(i=0; i<pParse->nTableLock; i++){
106 TableLock *p = &pParse->aTableLock[i];
107 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
109 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000110 }
111}
112#else
113 #define codeTableLocks(x)
114#endif
115
drhe0bc4042002-06-25 01:09:11 +0000116/*
drh75897232000-05-29 14:26:00 +0000117** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000118** parsed and a VDBE program to execute that statement has been
119** prepared. This routine puts the finishing touches on the
120** VDBE program and resets the pParse structure for the next
121** parse.
drh75897232000-05-29 14:26:00 +0000122**
123** Note that if an error occurred, it might be the case that
124** no VDBE code was generated.
125*/
drh80242052004-06-09 00:48:12 +0000126void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000127 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000128 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000129
drh17435752007-08-16 04:30:38 +0000130 db = pParse->db;
131 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000132 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000133 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000134
drh80242052004-06-09 00:48:12 +0000135 /* Begin by generating some termination code at the end of the
136 ** vdbe program
137 */
drh80242052004-06-09 00:48:12 +0000138 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000139 assert( !pParse->isMultiWrite
140 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000141 if( v ){
drh66a51672008-01-03 00:01:23 +0000142 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000143
144 /* The cookie mask contains one bit for each database file open.
145 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
146 ** set for each database that is used. Generate code to start a
147 ** transaction on each used database and to verify the schema cookie
148 ** on each used database.
149 */
drhc275b4e2004-07-19 17:25:24 +0000150 if( pParse->cookieGoto>0 ){
drh64123582011-04-02 20:01:02 +0000151 yDbMask mask;
drh26e4a8b2008-05-01 17:16:52 +0000152 int iDb;
drhd654be82005-09-20 17:42:23 +0000153 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000154 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
155 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000156 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000157 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drh8a939192009-04-20 17:43:03 +0000158 if( db->init.busy==0 ){
drh21206082011-04-04 18:22:02 +0000159 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhc2a75552011-03-18 21:55:46 +0000160 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
161 iDb, pParse->cookieValue[iDb],
162 db->aDb[iDb].pSchema->iGeneration);
drh8a939192009-04-20 17:43:03 +0000163 }
drh80242052004-06-09 00:48:12 +0000164 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000165#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000166 {
167 int i;
168 for(i=0; i<pParse->nVtabLock; i++){
danielk1977595a5232009-07-24 17:58:53 +0000169 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
drh26e4a8b2008-05-01 17:16:52 +0000170 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
171 }
172 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000173 }
174#endif
danielk1977c00da102006-01-07 13:21:04 +0000175
176 /* Once all the cookies have been verified and transactions opened,
177 ** obtain the required table-locks. This is a no-op unless the
178 ** shared-cache feature is enabled.
179 */
180 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000181
182 /* Initialize any AUTOINCREMENT data structures required.
183 */
184 sqlite3AutoincrementBegin(pParse);
185
186 /* Finally, jump back to the beginning of the executable code. */
drh66a51672008-01-03 00:01:23 +0000187 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000188 }
drh71c697e2004-08-08 23:39:19 +0000189 }
190
drh3f7d4e42004-07-24 14:35:58 +0000191
drh80242052004-06-09 00:48:12 +0000192 /* Get the VDBE program ready for execution
193 */
drh04491712009-05-13 17:21:13 +0000194 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000195#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000196 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000197 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000198#endif
drhceea3322009-04-23 13:22:42 +0000199 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000200 /* A minimum of one cursor is required if autoincrement is used
201 * See ticket [a696379c1f08866] */
202 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
danielk19776ab3a2e2009-02-19 14:39:25 +0000203 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
dane0af83a2009-09-08 19:15:01 +0000204 pParse->nTab, pParse->nMaxArg, pParse->explain,
205 pParse->isMultiWrite && pParse->mayAbort);
danielk1977441daf62005-02-01 03:46:43 +0000206 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000207 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000208 }else{
drh483750b2003-01-29 18:46:51 +0000209 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000210 }
drha226d052002-09-25 19:04:07 +0000211 pParse->nTab = 0;
212 pParse->nMem = 0;
213 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000214 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000215 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000216 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000217}
218
219/*
drh205f48e2004-11-05 00:43:11 +0000220** Run the parser and code generator recursively in order to generate
221** code for the SQL statement given onto the end of the pParse context
222** currently under construction. When the parser is run recursively
223** this way, the final OP_Halt is not appended and other initialization
224** and finalization steps are omitted because those are handling by the
225** outermost parser.
226**
227** Not everything is nestable. This facility is designed to permit
228** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000229** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000230*/
231void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
232 va_list ap;
233 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000234 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000235 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000236# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
237 char saveBuf[SAVE_SZ];
238
drh205f48e2004-11-05 00:43:11 +0000239 if( pParse->nErr ) return;
240 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
241 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000242 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000243 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000244 if( zSql==0 ){
245 return; /* A malloc must have failed */
246 }
drh205f48e2004-11-05 00:43:11 +0000247 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000248 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
249 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000250 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000251 sqlite3DbFree(db, zErrMsg);
252 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000253 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000254 pParse->nested--;
255}
256
257/*
danielk19778a414492004-06-29 08:59:35 +0000258** Locate the in-memory structure that describes a particular database
259** table given the name of that table and (optionally) the name of the
260** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000261**
danielk19778a414492004-06-29 08:59:35 +0000262** If zDatabase is 0, all databases are searched for the table and the
263** first matching table is returned. (No checking for duplicate table
264** names is done.) The search order is TEMP first, then MAIN, then any
265** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000266**
danielk19774adee202004-05-08 08:23:19 +0000267** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000268*/
drh9bb575f2004-09-06 17:24:11 +0000269Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000270 Table *p = 0;
271 int i;
drh0a687d12008-07-08 14:52:07 +0000272 int nName;
drh645f63e2004-06-22 13:22:40 +0000273 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000274 nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000275 /* All mutexes are required for schema access. Make sure we hold them. */
276 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000277 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000278 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000279 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000280 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh0a687d12008-07-08 14:52:07 +0000281 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000282 if( p ) break;
283 }
drh74e24cd2002-01-09 03:19:59 +0000284 return p;
drh75897232000-05-29 14:26:00 +0000285}
286
287/*
danielk19778a414492004-06-29 08:59:35 +0000288** Locate the in-memory structure that describes a particular database
289** table given the name of that table and (optionally) the name of the
290** database containing the table. Return NULL if not found. Also leave an
291** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000292**
danielk19778a414492004-06-29 08:59:35 +0000293** The difference between this routine and sqlite3FindTable() is that this
294** routine leaves an error message in pParse->zErrMsg where
295** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000296*/
drhca424112008-01-25 15:04:48 +0000297Table *sqlite3LocateTable(
298 Parse *pParse, /* context in which to report errors */
299 int isView, /* True if looking for a VIEW rather than a TABLE */
300 const char *zName, /* Name of the table we are looking for */
301 const char *zDbase /* Name of the database. Might be NULL */
302){
drha69d9162003-04-17 22:57:53 +0000303 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000304
danielk19778a414492004-06-29 08:59:35 +0000305 /* Read the database schema. If an error occurs, leave an error message
306 ** and code in pParse and return NULL. */
307 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
308 return 0;
309 }
310
danielk19774adee202004-05-08 08:23:19 +0000311 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000312 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000313 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000314 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000315 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000316 }else{
drhca424112008-01-25 15:04:48 +0000317 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000318 }
drha6ecd332004-06-10 00:29:09 +0000319 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000320 }
321 return p;
322}
323
324/*
325** Locate the in-memory structure that describes
326** a particular index given the name of that index
327** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000328** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000329**
330** If zDatabase is 0, all databases are searched for the
331** table and the first matching index is returned. (No checking
332** for duplicate index names is done.) The search order is
333** TEMP first, then MAIN, then any auxiliary databases added
334** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000335*/
drh9bb575f2004-09-06 17:24:11 +0000336Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000337 Index *p = 0;
338 int i;
drhdee0e402009-05-03 20:23:53 +0000339 int nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000340 /* All mutexes are required for schema access. Make sure we hold them. */
341 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000342 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000343 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000344 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000345 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000346 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000347 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh04491712009-05-13 17:21:13 +0000348 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000349 if( p ) break;
350 }
drh74e24cd2002-01-09 03:19:59 +0000351 return p;
drh75897232000-05-29 14:26:00 +0000352}
353
354/*
drh956bc922004-07-24 17:38:29 +0000355** Reclaim the memory used by an index
356*/
dan1feeaed2010-07-23 15:41:47 +0000357static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000358#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000359 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000360#endif
drh633e6d52008-07-28 19:34:53 +0000361 sqlite3DbFree(db, p->zColAff);
362 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000363}
364
365/*
drhc96d8532005-05-03 12:30:33 +0000366** For the index called zIdxName which is found in the database iDb,
367** unlike that index from its Table then remove the index from
368** the index hash table and free all memory structures associated
369** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000370*/
drh9bb575f2004-09-06 17:24:11 +0000371void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000372 Index *pIndex;
373 int len;
drh21206082011-04-04 18:22:02 +0000374 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000375
drh21206082011-04-04 18:22:02 +0000376 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
377 pHash = &db->aDb[iDb].pSchema->idxHash;
drhdee0e402009-05-03 20:23:53 +0000378 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000379 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh22645842011-03-24 01:34:03 +0000380 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000381 if( pIndex->pTable->pIndex==pIndex ){
382 pIndex->pTable->pIndex = pIndex->pNext;
383 }else{
384 Index *p;
drh04491712009-05-13 17:21:13 +0000385 /* Justification of ALWAYS(); The index must be on the list of
386 ** indices. */
387 p = pIndex->pTable->pIndex;
388 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
389 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000390 p->pNext = pIndex->pNext;
391 }
drh5e00f6c2001-09-13 13:46:56 +0000392 }
dan1feeaed2010-07-23 15:41:47 +0000393 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000394 }
drh956bc922004-07-24 17:38:29 +0000395 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000396}
397
398/*
drhe0bc4042002-06-25 01:09:11 +0000399** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000400** a single database. This routine is called to reclaim memory
401** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000402** if there were schema changes during the transaction or if a
403** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000404**
drhc7792fa2011-04-02 16:28:52 +0000405** If iDb<0 then reset the internal schema tables for all database
406** files. If iDb>=0 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000407** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000408*/
drh9bb575f2004-09-06 17:24:11 +0000409void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000410 int i, j;
drhc7792fa2011-04-02 16:28:52 +0000411 assert( iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000412
drhc7792fa2011-04-02 16:28:52 +0000413 if( iDb>=0 ){
414 /* Case 1: Reset the single schema identified by iDb */
415 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +0000416 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
417 if( ALWAYS(pDb->pSchema) ){
drhb6ee6602011-04-04 13:40:53 +0000418 sqlite3SchemaClear(pDb->pSchema);
drhc7792fa2011-04-02 16:28:52 +0000419 }
drhff2e14b2011-04-02 16:50:25 +0000420 /* If any database other than TEMP is reset, then also reset TEMP
421 ** since TEMP might be holding triggers that reference tables in the
422 ** other database.
423 */
drh21206082011-04-04 18:22:02 +0000424 if( iDb!=1 && (pDb = &db->aDb[1])!=0 && ALWAYS(pDb->pSchema) ){
drhb6ee6602011-04-04 13:40:53 +0000425 sqlite3SchemaClear(pDb->pSchema);
drhff2e14b2011-04-02 16:50:25 +0000426 }
drhc7792fa2011-04-02 16:28:52 +0000427 return;
danielk19774eab8b72007-12-27 15:12:16 +0000428 }
drhc7792fa2011-04-02 16:28:52 +0000429 /* Case 2 (from here to the end): Reset all schemas for all attached
430 ** databases. */
431 assert( iDb<0 );
432 sqlite3BtreeEnterAll(db);
433 for(i=0; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000434 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000435 if( pDb->pSchema ){
drhb6ee6602011-04-04 13:40:53 +0000436 sqlite3SchemaClear(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000437 }
drh74e24cd2002-01-09 03:19:59 +0000438 }
drh1c2d8412003-03-31 00:30:47 +0000439 db->flags &= ~SQLITE_InternChanges;
danielk1977595a5232009-07-24 17:58:53 +0000440 sqlite3VtabUnlockList(db);
danielk19774eab8b72007-12-27 15:12:16 +0000441 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000442
443 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000444 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000445 ** opportunity to do this here since we have just deleted all of the
446 ** schema hash tables and therefore do not have to make any changes
447 ** to any of those tables.
448 */
449 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000450 struct Db *pDb = &db->aDb[i];
451 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000452 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000453 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000454 continue;
455 }
456 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000457 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000458 }
drh8bf8dc92003-05-17 17:35:10 +0000459 j++;
drh1c2d8412003-03-31 00:30:47 +0000460 }
461 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
462 db->nDb = j;
463 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
464 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000465 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000466 db->aDb = db->aDbStatic;
467 }
drhe0bc4042002-06-25 01:09:11 +0000468}
469
470/*
drhe0bc4042002-06-25 01:09:11 +0000471** This routine is called when a commit occurs.
472*/
drh9bb575f2004-09-06 17:24:11 +0000473void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000474 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000475}
476
477/*
dand46def72010-07-24 11:28:28 +0000478** Delete memory allocated for the column names of a table or view (the
479** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000480*/
dand46def72010-07-24 11:28:28 +0000481static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000482 int i;
483 Column *pCol;
484 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000485 if( (pCol = pTable->aCol)!=0 ){
486 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000487 sqlite3DbFree(db, pCol->zName);
488 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000489 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000490 sqlite3DbFree(db, pCol->zType);
491 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000492 }
drh633e6d52008-07-28 19:34:53 +0000493 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000494 }
drh956bc922004-07-24 17:38:29 +0000495}
496
497/*
drh75897232000-05-29 14:26:00 +0000498** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000499** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000500**
501** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000502** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000503** memory structures of the indices and foreign keys associated with
504** the table.
drh75897232000-05-29 14:26:00 +0000505*/
dan1feeaed2010-07-23 15:41:47 +0000506void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000507 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000508
dand46def72010-07-24 11:28:28 +0000509 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000510
drhed8a3bb2005-06-06 21:19:56 +0000511 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000512 if( !pTable ) return;
513 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000514
dand46def72010-07-24 11:28:28 +0000515 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000516 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
517 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000518 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000519 if( !db || db->pnBytesFreed==0 ){
520 char *zName = pIndex->zName;
521 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
522 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
523 );
drh21206082011-04-04 18:22:02 +0000524 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000525 assert( pOld==pIndex || pOld==0 );
526 }
527 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000528 }
529
dan1da40a32009-09-19 17:00:31 +0000530 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000531 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000532
533 /* Delete the Table structure itself.
534 */
dand46def72010-07-24 11:28:28 +0000535 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000536 sqlite3DbFree(db, pTable->zName);
537 sqlite3DbFree(db, pTable->zColAff);
538 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000539#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000540 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000541#endif
drh078e4082010-07-28 19:17:51 +0000542#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000543 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000544#endif
drh633e6d52008-07-28 19:34:53 +0000545 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000546}
547
548/*
drh5edc3122001-09-13 21:53:09 +0000549** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000550** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000551*/
drh9bb575f2004-09-06 17:24:11 +0000552void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000553 Table *p;
drh956bc922004-07-24 17:38:29 +0000554 Db *pDb;
555
drhd229ca92002-01-09 13:30:41 +0000556 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000557 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000558 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000559 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000560 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000561 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);
dan1feeaed2010-07-23 15:41:47 +0000564 sqlite3DeleteTable(db, 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;
dan72c5ea32010-09-28 15:55:47 +0000756 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
757 /* If creating a temp table, the name may not be qualified. Unless
758 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000759 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000760 return;
761 }
danielk197753c0f742005-03-29 03:10:59 +0000762 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000763
764 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000765 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000766 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000767 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000768 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000769 }
drh1d85d932004-02-14 23:05:52 +0000770 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000771#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000772 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000773 {
774 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000775 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000776 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000777 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000778 }
drhe5f9c642003-01-13 23:27:31 +0000779 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000780 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000781 code = SQLITE_CREATE_TEMP_VIEW;
782 }else{
783 code = SQLITE_CREATE_VIEW;
784 }
785 }else{
danielk197753c0f742005-03-29 03:10:59 +0000786 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000787 code = SQLITE_CREATE_TEMP_TABLE;
788 }else{
789 code = SQLITE_CREATE_TABLE;
790 }
791 }
danielk1977f1a381e2006-06-16 08:01:02 +0000792 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000793 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000794 }
795 }
796#endif
drhf57b3392001-10-08 13:22:32 +0000797
drhf57b3392001-10-08 13:22:32 +0000798 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000799 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000800 ** it does. The exception is if the statement being parsed was passed
801 ** to an sqlite3_declare_vtab() call. In that case only the column names
802 ** and types will be used, so there is no need to test for namespace
803 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000804 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000805 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000806 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000807 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
808 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000809 }
dana16d1062010-09-28 17:37:28 +0000810 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000811 if( pTable ){
812 if( !noErr ){
813 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
814 }
815 goto begin_table_error;
816 }
drh8a8a0d12010-09-28 20:26:44 +0000817 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000818 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
819 goto begin_table_error;
820 }
drh75897232000-05-29 14:26:00 +0000821 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000822
danielk197726783a52007-08-29 14:06:22 +0000823 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000824 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000825 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000826 pParse->rc = SQLITE_NOMEM;
827 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000828 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000829 }
drh75897232000-05-29 14:26:00 +0000830 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000831 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000832 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000833 pTable->nRef = 1;
drh15564052010-09-25 22:32:56 +0000834 pTable->nRowEst = 1000000;
drhc4a64fa2009-05-11 20:53:28 +0000835 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000836 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000837
drh4794f732004-11-05 17:17:50 +0000838 /* If this is the magic sqlite_sequence table used by autoincrement,
839 ** then record a pointer to this table in the main database structure
840 ** so that INSERT can find the table easily.
841 */
842#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000843 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000844 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000845 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000846 }
847#endif
848
drh17f71932002-02-21 12:01:27 +0000849 /* Begin generating the code that will insert the table record into
850 ** the SQLITE_MASTER table. Note in particular that we must go ahead
851 ** and allocate the record number for the table entry now. Before any
852 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
853 ** indices to be created and the table record must come before the
854 ** indices. Hence, the record number for the table must be allocated
855 ** now.
856 */
danielk19774adee202004-05-08 08:23:19 +0000857 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000858 int j1;
drhe321c292006-01-12 01:56:43 +0000859 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000860 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000861 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000862
danielk197720b1eaf2006-07-26 16:22:14 +0000863#ifndef SQLITE_OMIT_VIRTUALTABLE
864 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000865 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000866 }
867#endif
868
danielk197736963fd2005-02-19 08:18:05 +0000869 /* If the file format and encoding in the database have not been set,
870 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000871 */
drhb7654112008-01-12 12:48:07 +0000872 reg1 = pParse->regRowid = ++pParse->nMem;
873 reg2 = pParse->regRoot = ++pParse->nMem;
874 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000875 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000876 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000877 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000878 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000879 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000880 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000881 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000882 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000883 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000884 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000885
drh4794f732004-11-05 17:17:50 +0000886 /* This just creates a place-holder record in the sqlite_master table.
887 ** The record created does not contain anything yet. It will be replaced
888 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000889 **
drh0fa991b2009-03-21 16:19:26 +0000890 ** The rowid for the new entry is left in register pParse->regRowid.
891 ** The root page number of the new table is left in reg pParse->regRoot.
892 ** The rowid and root page number values are needed by the code that
893 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000894 */
danielk1977f1a381e2006-06-16 08:01:02 +0000895#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
896 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000897 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000898 }else
899#endif
900 {
drhb7654112008-01-12 12:48:07 +0000901 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000902 }
danielk1977c00da102006-01-07 13:21:04 +0000903 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000904 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
905 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
906 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
907 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000908 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000909 }
drh23bf66d2004-12-14 03:34:34 +0000910
911 /* Normal (non-error) return. */
912 return;
913
914 /* If an error occurs, we jump here */
915begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000916 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000917 return;
drh75897232000-05-29 14:26:00 +0000918}
919
920/*
danielk1977c60e9b82005-01-31 12:42:29 +0000921** This macro is used to compare two strings in a case-insensitive manner.
922** It is slightly faster than calling sqlite3StrICmp() directly, but
923** produces larger code.
924**
925** WARNING: This macro is not compatible with the strcmp() family. It
926** returns true if the two strings are equal, otherwise false.
927*/
928#define STRICMP(x, y) (\
929sqlite3UpperToLower[*(unsigned char *)(x)]== \
930sqlite3UpperToLower[*(unsigned char *)(y)] \
931&& sqlite3StrICmp((x)+1,(y)+1)==0 )
932
933/*
drh75897232000-05-29 14:26:00 +0000934** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000935**
936** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000937** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000938** first to get things going. Then this routine is called for each
939** column.
drh75897232000-05-29 14:26:00 +0000940*/
danielk19774adee202004-05-08 08:23:19 +0000941void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000942 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000943 int i;
drha99db3b2004-06-19 14:49:12 +0000944 char *z;
drhc9b84a12002-06-20 11:36:48 +0000945 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000946 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000947 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000948#if SQLITE_MAX_COLUMN
949 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000950 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
951 return;
952 }
drhbb4957f2008-03-20 14:03:29 +0000953#endif
danielk1977ae74e032008-12-23 11:11:51 +0000954 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000955 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000956 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000957 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000958 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000959 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000960 return;
961 }
962 }
drh75897232000-05-29 14:26:00 +0000963 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000964 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000965 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000966 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000967 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000968 return;
969 }
drh6d4abfb2001-10-22 02:58:08 +0000970 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000971 }
drhc9b84a12002-06-20 11:36:48 +0000972 pCol = &p->aCol[p->nCol];
973 memset(pCol, 0, sizeof(p->aCol[0]));
974 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000975
976 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000977 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
978 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000979 */
danielk19774f057f92004-06-08 00:02:33 +0000980 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000981 p->nCol++;
drh75897232000-05-29 14:26:00 +0000982}
983
984/*
drh382c0242001-10-06 16:33:02 +0000985** This routine is called by the parser while in the middle of
986** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
987** been seen on a column. This routine sets the notNull flag on
988** the column currently under construction.
989*/
danielk19774adee202004-05-08 08:23:19 +0000990void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000991 Table *p;
drhc4a64fa2009-05-11 20:53:28 +0000992 p = pParse->pNewTable;
993 if( p==0 || NEVER(p->nCol<1) ) return;
994 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000995}
996
997/*
danielk197752a83fb2005-01-31 12:56:44 +0000998** Scan the column type name zType (length nType) and return the
999** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001000**
1001** This routine does a case-independent search of zType for the
1002** substrings in the following table. If one of the substrings is
1003** found, the corresponding affinity is returned. If zType contains
1004** more than one of the substrings, entries toward the top of
1005** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001006** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001007**
1008** Substring | Affinity
1009** --------------------------------
1010** 'INT' | SQLITE_AFF_INTEGER
1011** 'CHAR' | SQLITE_AFF_TEXT
1012** 'CLOB' | SQLITE_AFF_TEXT
1013** 'TEXT' | SQLITE_AFF_TEXT
1014** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001015** 'REAL' | SQLITE_AFF_REAL
1016** 'FLOA' | SQLITE_AFF_REAL
1017** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001018**
1019** If none of the substrings in the above table are found,
1020** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001021*/
drhb7916a72009-05-27 10:31:29 +00001022char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +00001023 u32 h = 0;
1024 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +00001025
drhb7916a72009-05-27 10:31:29 +00001026 if( zIn ) while( zIn[0] ){
1027 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001028 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001029 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1030 aff = SQLITE_AFF_TEXT;
1031 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1032 aff = SQLITE_AFF_TEXT;
1033 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1034 aff = SQLITE_AFF_TEXT;
1035 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001036 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001037 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001038#ifndef SQLITE_OMIT_FLOATING_POINT
1039 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1040 && aff==SQLITE_AFF_NUMERIC ){
1041 aff = SQLITE_AFF_REAL;
1042 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1043 && aff==SQLITE_AFF_NUMERIC ){
1044 aff = SQLITE_AFF_REAL;
1045 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1046 && aff==SQLITE_AFF_NUMERIC ){
1047 aff = SQLITE_AFF_REAL;
1048#endif
danielk1977201f7162005-02-01 02:13:29 +00001049 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001050 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001051 break;
danielk197752a83fb2005-01-31 12:56:44 +00001052 }
1053 }
danielk1977b3dff962005-02-01 01:21:55 +00001054
1055 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001056}
1057
1058/*
drh382c0242001-10-06 16:33:02 +00001059** This routine is called by the parser while in the middle of
1060** parsing a CREATE TABLE statement. The pFirst token is the first
1061** token in the sequence of tokens that describe the type of the
1062** column currently under construction. pLast is the last token
1063** in the sequence. Use this information to construct a string
1064** that contains the typename of the column and store that string
1065** in zType.
1066*/
drh487e2622005-06-25 18:42:14 +00001067void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001068 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001069 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001070
drhc4a64fa2009-05-11 20:53:28 +00001071 p = pParse->pNewTable;
1072 if( p==0 || NEVER(p->nCol<1) ) return;
1073 pCol = &p->aCol[p->nCol-1];
1074 assert( pCol->zType==0 );
1075 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001076 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001077}
1078
1079/*
danielk19777977a172004-11-09 12:44:37 +00001080** The expression is the default value for the most recently added column
1081** of the table currently under construction.
1082**
1083** Default value expressions must be constant. Raise an exception if this
1084** is not the case.
drhd9b02572001-04-15 00:37:09 +00001085**
1086** This routine is called by the parser while in the middle of
1087** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001088*/
drhb7916a72009-05-27 10:31:29 +00001089void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001090 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001091 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001092 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001093 p = pParse->pNewTable;
1094 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001095 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001096 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001097 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1098 pCol->zName);
1099 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001100 /* A copy of pExpr is used instead of the original, as pExpr contains
1101 ** tokens that point to volatile memory. The 'span' of the expression
1102 ** is required by pragma table_info.
1103 */
drh633e6d52008-07-28 19:34:53 +00001104 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001105 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1106 sqlite3DbFree(db, pCol->zDflt);
1107 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001108 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001109 }
danielk19777977a172004-11-09 12:44:37 +00001110 }
drhb7916a72009-05-27 10:31:29 +00001111 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001112}
1113
1114/*
drh4a324312001-12-21 14:30:42 +00001115** Designate the PRIMARY KEY for the table. pList is a list of names
1116** of columns that form the primary key. If pList is NULL, then the
1117** most recently added column of the table is the primary key.
1118**
1119** A table can have at most one primary key. If the table already has
1120** a primary key (and this is the second primary key) then create an
1121** error.
1122**
1123** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001124** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001125** field of the table under construction to be the index of the
1126** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1127** no INTEGER PRIMARY KEY.
1128**
1129** If the key is not an INTEGER PRIMARY KEY, then create a unique
1130** index for the key. No index is created for INTEGER PRIMARY KEYs.
1131*/
drh205f48e2004-11-05 00:43:11 +00001132void sqlite3AddPrimaryKey(
1133 Parse *pParse, /* Parsing context */
1134 ExprList *pList, /* List of field names to be indexed */
1135 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001136 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1137 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001138){
drh4a324312001-12-21 14:30:42 +00001139 Table *pTab = pParse->pNewTable;
1140 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001141 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001142 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001143 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001144 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001145 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001146 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001147 }
drh7d10d5a2008-08-20 16:35:10 +00001148 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001149 if( pList==0 ){
1150 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001151 pTab->aCol[iCol].isPrimKey = 1;
1152 }else{
danielk19770202b292004-06-09 09:55:16 +00001153 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001154 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001155 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1156 break;
1157 }
drh78100cc2003-08-23 22:40:53 +00001158 }
drh6e4fc2c2005-09-15 21:24:51 +00001159 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001160 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001161 }
drh4a324312001-12-21 14:30:42 +00001162 }
danielk19770202b292004-06-09 09:55:16 +00001163 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001164 }
1165 if( iCol>=0 && iCol<pTab->nCol ){
1166 zType = pTab->aCol[iCol].zType;
1167 }
drhfdd6e852005-12-16 01:06:16 +00001168 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1169 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001170 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001171 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001172 assert( autoInc==0 || autoInc==1 );
1173 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001174 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001175#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001176 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1177 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001178#endif
drh4a324312001-12-21 14:30:42 +00001179 }else{
dan1da40a32009-09-19 17:00:31 +00001180 Index *p;
1181 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1182 if( p ){
1183 p->autoIndex = 2;
1184 }
drhe0194f22003-02-26 13:52:51 +00001185 pList = 0;
drh4a324312001-12-21 14:30:42 +00001186 }
drhe0194f22003-02-26 13:52:51 +00001187
1188primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001189 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001190 return;
drh4a324312001-12-21 14:30:42 +00001191}
1192
1193/*
drhffe07b22005-11-03 00:41:17 +00001194** Add a new CHECK constraint to the table currently under construction.
1195*/
1196void sqlite3AddCheckConstraint(
1197 Parse *pParse, /* Parsing context */
1198 Expr *pCheckExpr /* The check expression */
1199){
drh633e6d52008-07-28 19:34:53 +00001200 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001201#ifndef SQLITE_OMIT_CHECK
1202 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001203 if( pTab && !IN_DECLARE_VTAB ){
drh33e619f2009-05-28 01:00:55 +00001204 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1205 }else
drhffe07b22005-11-03 00:41:17 +00001206#endif
drh33e619f2009-05-28 01:00:55 +00001207 {
1208 sqlite3ExprDelete(db, pCheckExpr);
1209 }
drhffe07b22005-11-03 00:41:17 +00001210}
1211
1212/*
drhd3d39e92004-05-20 22:16:29 +00001213** Set the collation function of the most recently parsed table column
1214** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001215*/
danielk197739002502007-11-12 09:50:26 +00001216void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001217 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001218 int i;
danielk197739002502007-11-12 09:50:26 +00001219 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001220 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001221
danielk1977b8cbb872006-06-19 05:33:45 +00001222 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001223 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001224 db = pParse->db;
1225 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001226 if( !zColl ) return;
1227
drhc4a64fa2009-05-11 20:53:28 +00001228 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001229 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001230 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001231
1232 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1233 ** then an index may have been created on this column before the
1234 ** collation type was added. Correct this if it is the case.
1235 */
1236 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1237 assert( pIdx->nColumn==1 );
1238 if( pIdx->aiColumn[0]==i ){
1239 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001240 }
1241 }
danielk197739002502007-11-12 09:50:26 +00001242 }else{
drh633e6d52008-07-28 19:34:53 +00001243 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001244 }
danielk19777cedc8d2004-06-10 10:50:08 +00001245}
1246
danielk1977466be562004-06-10 02:16:01 +00001247/*
1248** This function returns the collation sequence for database native text
1249** encoding identified by the string zName, length nName.
1250**
1251** If the requested collation sequence is not available, or not available
1252** in the database native encoding, the collation factory is invoked to
1253** request it. If the collation factory does not supply such a sequence,
1254** and the sequence is available in another text encoding, then that is
1255** returned instead.
1256**
1257** If no versions of the requested collations sequence are available, or
1258** another error occurs, NULL is returned and an error message written into
1259** pParse.
drha34001c2007-02-02 12:44:37 +00001260**
1261** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1262** invokes the collation factory if the named collation cannot be found
1263** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001264**
1265** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001266*/
drhc4a64fa2009-05-11 20:53:28 +00001267CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001268 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001269 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001270 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001271 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001272
drhc4a64fa2009-05-11 20:53:28 +00001273 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001274 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh9aeda792009-08-20 02:34:15 +00001275 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
danielk19774dade032005-05-25 10:45:10 +00001276 if( !pColl ){
drhc4a64fa2009-05-11 20:53:28 +00001277 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
danielk1977466be562004-06-10 02:16:01 +00001278 }
1279 }
1280
danielk19770202b292004-06-09 09:55:16 +00001281 return pColl;
1282}
1283
1284
drh8e2ca022002-06-17 17:07:19 +00001285/*
drh3f7d4e42004-07-24 14:35:58 +00001286** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001287**
1288** The schema cookie is used to determine when the schema for the
1289** database changes. After each schema change, the cookie value
1290** changes. When a process first reads the schema it records the
1291** cookie. Thereafter, whenever it goes to access the database,
1292** it checks the cookie to make sure the schema has not changed
1293** since it was last read.
1294**
1295** This plan is not completely bullet-proof. It is possible for
1296** the schema to change multiple times and for the cookie to be
1297** set back to prior value. But schema changes are infrequent
1298** and the probability of hitting the same cookie value is only
1299** 1 chance in 2^32. So we're safe enough.
1300*/
drh9cbf3422008-01-17 16:22:13 +00001301void sqlite3ChangeCookie(Parse *pParse, int iDb){
1302 int r1 = sqlite3GetTempReg(pParse);
1303 sqlite3 *db = pParse->db;
1304 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001305 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001306 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001307 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001308 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001309}
1310
1311/*
drh969fa7c2002-02-18 18:30:32 +00001312** Measure the number of characters needed to output the given
1313** identifier. The number returned includes any quotes used
1314** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001315**
1316** The estimate is conservative. It might be larger that what is
1317** really needed.
drh969fa7c2002-02-18 18:30:32 +00001318*/
1319static int identLength(const char *z){
1320 int n;
drh17f71932002-02-21 12:01:27 +00001321 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001322 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001323 }
drh234c39d2004-07-24 03:30:47 +00001324 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001325}
1326
1327/*
danielk19771b870de2009-03-14 08:37:23 +00001328** The first parameter is a pointer to an output buffer. The second
1329** parameter is a pointer to an integer that contains the offset at
1330** which to write into the output buffer. This function copies the
1331** nul-terminated string pointed to by the third parameter, zSignedIdent,
1332** to the specified offset in the buffer and updates *pIdx to refer
1333** to the first byte after the last byte written before returning.
1334**
1335** If the string zSignedIdent consists entirely of alpha-numeric
1336** characters, does not begin with a digit and is not an SQL keyword,
1337** then it is copied to the output buffer exactly as it is. Otherwise,
1338** it is quoted using double-quotes.
1339*/
drhc4a64fa2009-05-11 20:53:28 +00001340static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001341 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001342 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001343 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001344
drh17f71932002-02-21 12:01:27 +00001345 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001346 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001347 }
danielk19771b870de2009-03-14 08:37:23 +00001348 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1349 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001350 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001351 }
1352
drh234c39d2004-07-24 03:30:47 +00001353 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001354 for(j=0; zIdent[j]; j++){
1355 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001356 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001357 }
drh234c39d2004-07-24 03:30:47 +00001358 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001359 z[i] = 0;
1360 *pIdx = i;
1361}
1362
1363/*
1364** Generate a CREATE TABLE statement appropriate for the given
1365** table. Memory to hold the text of the statement is obtained
1366** from sqliteMalloc() and must be freed by the calling function.
1367*/
drh1d34fde2009-02-03 15:50:33 +00001368static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001369 int i, k, n;
1370 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001371 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001372 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001373 n = 0;
drh234c39d2004-07-24 03:30:47 +00001374 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001375 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001376 }
1377 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001378 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001379 zSep = "";
1380 zSep2 = ",";
1381 zEnd = ")";
1382 }else{
1383 zSep = "\n ";
1384 zSep2 = ",\n ";
1385 zEnd = "\n)";
1386 }
drhe0bc4042002-06-25 01:09:11 +00001387 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001388 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001389 if( zStmt==0 ){
1390 db->mallocFailed = 1;
1391 return 0;
1392 }
drhbdb339f2009-02-02 18:03:21 +00001393 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001394 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001395 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001396 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001397 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001398 static const char * const azType[] = {
1399 /* SQLITE_AFF_TEXT */ " TEXT",
1400 /* SQLITE_AFF_NONE */ "",
1401 /* SQLITE_AFF_NUMERIC */ " NUM",
1402 /* SQLITE_AFF_INTEGER */ " INT",
1403 /* SQLITE_AFF_REAL */ " REAL"
1404 };
1405 int len;
1406 const char *zType;
1407
drh5bb3eb92007-05-04 13:15:55 +00001408 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001409 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001410 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001411 identPut(zStmt, &k, pCol->zName);
1412 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1413 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
1414 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1415 testcase( pCol->affinity==SQLITE_AFF_NONE );
1416 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1417 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1418 testcase( pCol->affinity==SQLITE_AFF_REAL );
1419
1420 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1421 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001422 assert( pCol->affinity==SQLITE_AFF_NONE
1423 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001424 memcpy(&zStmt[k], zType, len);
1425 k += len;
1426 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001427 }
drh5bb3eb92007-05-04 13:15:55 +00001428 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001429 return zStmt;
1430}
1431
1432/*
drh75897232000-05-29 14:26:00 +00001433** This routine is called to report the final ")" that terminates
1434** a CREATE TABLE statement.
1435**
drhf57b3392001-10-08 13:22:32 +00001436** The table structure that other action routines have been building
1437** is added to the internal hash tables, assuming no errors have
1438** occurred.
drh75897232000-05-29 14:26:00 +00001439**
drh1d85d932004-02-14 23:05:52 +00001440** An entry for the table is made in the master table on disk, unless
1441** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001442** it means we are reading the sqlite_master table because we just
1443** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001444** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001445** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001446**
1447** If the pSelect argument is not NULL, it means that this routine
1448** was called to create a table generated from a
1449** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1450** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001451*/
danielk197719a8e7e2005-03-17 05:03:38 +00001452void sqlite3EndTable(
1453 Parse *pParse, /* Parse context */
1454 Token *pCons, /* The ',' token after the last column defn. */
1455 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1456 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1457){
drh75897232000-05-29 14:26:00 +00001458 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001459 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001460 int iDb;
drh75897232000-05-29 14:26:00 +00001461
drh8af73d42009-05-13 22:58:28 +00001462 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001463 return;
1464 }
drh28037572000-08-02 13:47:41 +00001465 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001466 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001467
danielk1977517eb642004-06-07 10:00:31 +00001468 assert( !db->init.busy || !pSelect );
1469
drhb9bb7c12006-06-11 23:41:55 +00001470 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001471
drhffe07b22005-11-03 00:41:17 +00001472#ifndef SQLITE_OMIT_CHECK
1473 /* Resolve names in all CHECK constraint expressions.
1474 */
1475 if( p->pCheck ){
1476 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1477 NameContext sNC; /* Name context for pParse->pNewTable */
1478
1479 memset(&sNC, 0, sizeof(sNC));
1480 memset(&sSrc, 0, sizeof(sSrc));
1481 sSrc.nSrc = 1;
1482 sSrc.a[0].zName = p->zName;
1483 sSrc.a[0].pTab = p;
1484 sSrc.a[0].iCursor = -1;
1485 sNC.pParse = pParse;
1486 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001487 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001488 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001489 return;
1490 }
1491 }
1492#endif /* !defined(SQLITE_OMIT_CHECK) */
1493
drh1d85d932004-02-14 23:05:52 +00001494 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001495 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1496 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001497 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001498 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001499 */
drh1d85d932004-02-14 23:05:52 +00001500 if( db->init.busy ){
1501 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001502 }
1503
drhe3c41372001-09-17 20:25:58 +00001504 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001505 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001506 **
drhe0bc4042002-06-25 01:09:11 +00001507 ** If this is a TEMPORARY table, write the entry into the auxiliary
1508 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001509 */
drh1d85d932004-02-14 23:05:52 +00001510 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001511 int n;
drhd8bc7082000-06-07 23:51:50 +00001512 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001513 char *zType; /* "view" or "table" */
1514 char *zType2; /* "VIEW" or "TABLE" */
1515 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001516
danielk19774adee202004-05-08 08:23:19 +00001517 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001518 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001519
drh66a51672008-01-03 00:01:23 +00001520 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001521
drh0fa991b2009-03-21 16:19:26 +00001522 /*
1523 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001524 */
drh4ff6dfa2002-03-03 23:06:00 +00001525 if( p->pSelect==0 ){
1526 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001527 zType = "table";
1528 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001529#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001530 }else{
1531 /* A view */
drh4794f732004-11-05 17:17:50 +00001532 zType = "view";
1533 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001534#endif
drh4ff6dfa2002-03-03 23:06:00 +00001535 }
danielk1977517eb642004-06-07 10:00:31 +00001536
danielk1977517eb642004-06-07 10:00:31 +00001537 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1538 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001539 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001540 **
1541 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1542 ** suitable state to query for the column names and types to be used
1543 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001544 **
1545 ** A shared-cache write-lock is not required to write to the new table,
1546 ** as a schema-lock must have already been obtained to create it. Since
1547 ** a schema-lock excludes all other database users, the write-lock would
1548 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001549 */
1550 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001551 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001552 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001553
danielk19776ab3a2e2009-02-19 14:39:25 +00001554 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001555 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001556 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001557 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001558 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001559 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001560 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001561 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001562 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001563 if( pSelTab==0 ) return;
1564 assert( p->aCol==0 );
1565 p->nCol = pSelTab->nCol;
1566 p->aCol = pSelTab->aCol;
1567 pSelTab->nCol = 0;
1568 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001569 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001570 }
1571 }
drh4794f732004-11-05 17:17:50 +00001572
drh4794f732004-11-05 17:17:50 +00001573 /* Compute the complete text of the CREATE statement */
1574 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001575 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001576 }else{
drh1bd10f82008-12-10 21:19:56 +00001577 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001578 zStmt = sqlite3MPrintf(db,
1579 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1580 );
drh4794f732004-11-05 17:17:50 +00001581 }
1582
1583 /* A slot for the record has already been allocated in the
1584 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001585 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001586 */
1587 sqlite3NestedParse(pParse,
1588 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001589 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1590 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001591 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001592 zType,
1593 p->zName,
1594 p->zName,
drhb7654112008-01-12 12:48:07 +00001595 pParse->regRoot,
1596 zStmt,
1597 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001598 );
drh633e6d52008-07-28 19:34:53 +00001599 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001600 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001601
1602#ifndef SQLITE_OMIT_AUTOINCREMENT
1603 /* Check to see if we need to create an sqlite_sequence table for
1604 ** keeping track of autoincrement keys.
1605 */
drh7d10d5a2008-08-20 16:35:10 +00001606 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001607 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001608 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001609 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001610 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001611 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1612 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001613 );
1614 }
1615 }
1616#endif
drh4794f732004-11-05 17:17:50 +00001617
1618 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001619 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1620 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001621 }
drh17e9e292003-02-01 13:53:28 +00001622
drh2958a4e2004-11-12 03:56:15 +00001623
drh17e9e292003-02-01 13:53:28 +00001624 /* Add the table to the in-memory representation of the database.
1625 */
drh8af73d42009-05-13 22:58:28 +00001626 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001627 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001628 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001629 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001630 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001631 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001632 if( pOld ){
1633 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001634 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001635 return;
1636 }
drh17e9e292003-02-01 13:53:28 +00001637 pParse->pNewTable = 0;
1638 db->nTable++;
1639 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001640
1641#ifndef SQLITE_OMIT_ALTERTABLE
1642 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001643 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001644 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001645 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001646 if( pCons->z==0 ){
1647 pCons = pEnd;
1648 }
drh1bd10f82008-12-10 21:19:56 +00001649 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001650 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001651 }
1652#endif
drh17e9e292003-02-01 13:53:28 +00001653 }
drh75897232000-05-29 14:26:00 +00001654}
1655
drhb7f91642004-10-31 02:22:47 +00001656#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001657/*
drha76b5df2002-02-23 02:32:10 +00001658** The parser calls this routine in order to create a new VIEW
1659*/
danielk19774adee202004-05-08 08:23:19 +00001660void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001661 Parse *pParse, /* The parsing context */
1662 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001663 Token *pName1, /* The token that holds the name of the view */
1664 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001665 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001666 int isTemp, /* TRUE for a TEMPORARY view */
1667 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001668){
drha76b5df2002-02-23 02:32:10 +00001669 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001670 int n;
drhb7916a72009-05-27 10:31:29 +00001671 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001672 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001673 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001674 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001675 int iDb;
drh17435752007-08-16 04:30:38 +00001676 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001677
drh7c3d64f2005-06-06 15:32:08 +00001678 if( pParse->nVar>0 ){
1679 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001680 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001681 return;
1682 }
drhfdd48a72006-09-11 23:45:48 +00001683 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001684 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001685 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001686 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001687 return;
1688 }
danielk1977ef2cb632004-05-29 02:37:19 +00001689 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001690 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001691 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001692 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001693 ){
drh633e6d52008-07-28 19:34:53 +00001694 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001695 return;
1696 }
drh174b6192002-12-03 02:22:52 +00001697
drh4b59ab52002-08-24 18:24:51 +00001698 /* Make a copy of the entire SELECT statement that defines the view.
1699 ** This will force all the Expr.token.z values to be dynamically
1700 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001701 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001702 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001703 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001704 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001705 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001706 return;
1707 }
drh17435752007-08-16 04:30:38 +00001708 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001709 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001710 }
drh4b59ab52002-08-24 18:24:51 +00001711
1712 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1713 ** the end.
1714 */
drha76b5df2002-02-23 02:32:10 +00001715 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001716 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001717 sEnd.z += sEnd.n;
1718 }
1719 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001720 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001721 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001722 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001723 sEnd.z = &z[n-1];
1724 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001725
danielk19774adee202004-05-08 08:23:19 +00001726 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001727 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001728 return;
drh417be792002-03-03 18:59:40 +00001729}
drhb7f91642004-10-31 02:22:47 +00001730#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001731
danielk1977fe3fcbe22006-06-12 12:08:45 +00001732#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001733/*
1734** The Table structure pTable is really a VIEW. Fill in the names of
1735** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001736** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001737*/
danielk19774adee202004-05-08 08:23:19 +00001738int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001739 Table *pSelTab; /* A fake table from which we get the result set */
1740 Select *pSel; /* Copy of the SELECT that implements the view */
1741 int nErr = 0; /* Number of errors encountered */
1742 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001743 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001744 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001745
1746 assert( pTable );
1747
danielk1977fe3fcbe22006-06-12 12:08:45 +00001748#ifndef SQLITE_OMIT_VIRTUALTABLE
1749 if( sqlite3VtabCallConnect(pParse, pTable) ){
1750 return SQLITE_ERROR;
1751 }
drh4cbdda92006-06-14 19:00:20 +00001752 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001753#endif
1754
1755#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001756 /* A positive nCol means the columns names for this view are
1757 ** already known.
1758 */
1759 if( pTable->nCol>0 ) return 0;
1760
1761 /* A negative nCol is a special marker meaning that we are currently
1762 ** trying to compute the column names. If we enter this routine with
1763 ** a negative nCol, it means two or more views form a loop, like this:
1764 **
1765 ** CREATE VIEW one AS SELECT * FROM two;
1766 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001767 **
drh768578e2009-05-12 00:40:12 +00001768 ** Actually, the error above is now caught prior to reaching this point.
1769 ** But the following test is still important as it does come up
1770 ** in the following:
1771 **
1772 ** CREATE TABLE main.ex1(a);
1773 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1774 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001775 */
1776 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001777 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001778 return 1;
1779 }
drh85c23c62005-08-20 03:03:04 +00001780 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001781
1782 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001783 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1784 ** "*" elements in the results set of the view and will assign cursors
1785 ** to the elements of the FROM clause. But we do not want these changes
1786 ** to be permanent. So the computation is done on a copy of the SELECT
1787 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001788 */
drh9b3187e2005-01-18 14:45:47 +00001789 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001790 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001791 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001792 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001793 n = pParse->nTab;
1794 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1795 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001796 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001797#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001798 xAuth = db->xAuth;
1799 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001800 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001801 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001802#else
drh7d10d5a2008-08-20 16:35:10 +00001803 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001804#endif
drhd9da78a2009-03-24 15:08:09 +00001805 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001806 pParse->nTab = n;
1807 if( pSelTab ){
1808 assert( pTable->aCol==0 );
1809 pTable->nCol = pSelTab->nCol;
1810 pTable->aCol = pSelTab->aCol;
1811 pSelTab->nCol = 0;
1812 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001813 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00001814 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00001815 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001816 }else{
1817 pTable->nCol = 0;
1818 nErr++;
1819 }
drh633e6d52008-07-28 19:34:53 +00001820 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001821 } else {
drh417be792002-03-03 18:59:40 +00001822 nErr++;
1823 }
drhb7f91642004-10-31 02:22:47 +00001824#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001825 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001826}
1827#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001828
drhb7f91642004-10-31 02:22:47 +00001829#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001830/*
drh8bf8dc92003-05-17 17:35:10 +00001831** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001832*/
drh9bb575f2004-09-06 17:24:11 +00001833static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001834 HashElem *i;
drh21206082011-04-04 18:22:02 +00001835 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00001836 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001837 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001838 Table *pTab = sqliteHashData(i);
1839 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00001840 sqliteDeleteColumnNames(db, pTab);
1841 pTab->aCol = 0;
1842 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00001843 }
1844 }
drh8bf8dc92003-05-17 17:35:10 +00001845 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001846}
drhb7f91642004-10-31 02:22:47 +00001847#else
1848# define sqliteViewResetAll(A,B)
1849#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001850
drh75897232000-05-29 14:26:00 +00001851/*
danielk1977a0bf2652004-11-04 14:30:04 +00001852** This function is called by the VDBE to adjust the internal schema
1853** used by SQLite when the btree layer moves a table root page. The
1854** root-page of a table or index in database iDb has changed from iFrom
1855** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001856**
1857** Ticket #1728: The symbol table might still contain information
1858** on tables and/or indices that are the process of being deleted.
1859** If you are unlucky, one of those deleted indices or tables might
1860** have the same rootpage number as the real table or index that is
1861** being moved. So we cannot stop searching after the first match
1862** because the first match might be for one of the deleted indices
1863** or tables and not the table/index that is actually being moved.
1864** We must continue looping until all tables and indices with
1865** rootpage==iFrom have been converted to have a rootpage of iTo
1866** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001867*/
1868#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00001869void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00001870 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001871 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00001872 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00001873
drhcdf011d2011-04-04 21:25:28 +00001874 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1875 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00001876 pHash = &pDb->pSchema->tblHash;
1877 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001878 Table *pTab = sqliteHashData(pElem);
1879 if( pTab->tnum==iFrom ){
1880 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001881 }
1882 }
danielk1977da184232006-01-05 11:34:32 +00001883 pHash = &pDb->pSchema->idxHash;
1884 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001885 Index *pIdx = sqliteHashData(pElem);
1886 if( pIdx->tnum==iFrom ){
1887 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001888 }
1889 }
danielk1977a0bf2652004-11-04 14:30:04 +00001890}
1891#endif
1892
1893/*
1894** Write code to erase the table with root-page iTable from database iDb.
1895** Also write code to modify the sqlite_master table and internal schema
1896** if a root-page of another table is moved by the btree-layer whilst
1897** erasing iTable (this can happen with an auto-vacuum database).
1898*/
drh4e0cff62004-11-05 05:10:28 +00001899static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1900 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001901 int r1 = sqlite3GetTempReg(pParse);
1902 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001903 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001904#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001905 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001906 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001907 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001908 ** reflect this.
1909 **
drh0fa991b2009-03-21 16:19:26 +00001910 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001911 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1912 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001913 */
danielk197763e3e9f2004-11-05 09:19:27 +00001914 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001915 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1916 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001917#endif
drhb7654112008-01-12 12:48:07 +00001918 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001919}
1920
1921/*
1922** Write VDBE code to erase table pTab and all associated indices on disk.
1923** Code to update the sqlite_master tables and internal schema definitions
1924** in case a root-page belonging to another table is moved by the btree layer
1925** is also added (this can happen with an auto-vacuum database).
1926*/
drh4e0cff62004-11-05 05:10:28 +00001927static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001928#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001929 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001930 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1931 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001932 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001933 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001934 }
1935#else
1936 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1937 ** is not defined), then it is important to call OP_Destroy on the
1938 ** table and index root-pages in order, starting with the numerically
1939 ** largest root-page number. This guarantees that none of the root-pages
1940 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1941 ** following were coded:
1942 **
1943 ** OP_Destroy 4 0
1944 ** ...
1945 ** OP_Destroy 5 0
1946 **
1947 ** and root page 5 happened to be the largest root-page number in the
1948 ** database, then root page 5 would be moved to page 4 by the
1949 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1950 ** a free-list page.
1951 */
1952 int iTab = pTab->tnum;
1953 int iDestroyed = 0;
1954
1955 while( 1 ){
1956 Index *pIdx;
1957 int iLargest = 0;
1958
1959 if( iDestroyed==0 || iTab<iDestroyed ){
1960 iLargest = iTab;
1961 }
1962 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1963 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001964 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001965 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1966 iLargest = iIdx;
1967 }
1968 }
danielk1977da184232006-01-05 11:34:32 +00001969 if( iLargest==0 ){
1970 return;
1971 }else{
1972 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1973 destroyRootPage(pParse, iLargest, iDb);
1974 iDestroyed = iLargest;
1975 }
danielk1977a0bf2652004-11-04 14:30:04 +00001976 }
1977#endif
1978}
1979
1980/*
drh75897232000-05-29 14:26:00 +00001981** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001982** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001983*/
drha0733842005-12-29 01:11:36 +00001984void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001985 Table *pTab;
drh75897232000-05-29 14:26:00 +00001986 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001987 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001988 int iDb;
drh75897232000-05-29 14:26:00 +00001989
drh8af73d42009-05-13 22:58:28 +00001990 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001991 goto exit_drop_table;
1992 }
drh8af73d42009-05-13 22:58:28 +00001993 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00001994 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00001995 if( noErr ) db->suppressErr++;
drhca424112008-01-25 15:04:48 +00001996 pTab = sqlite3LocateTable(pParse, isView,
1997 pName->a[0].zName, pName->a[0].zDatabase);
drha7564662010-02-22 19:32:31 +00001998 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00001999
drha0733842005-12-29 01:11:36 +00002000 if( pTab==0 ){
drha0733842005-12-29 01:11:36 +00002001 goto exit_drop_table;
2002 }
danielk1977da184232006-01-05 11:34:32 +00002003 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002004 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002005
2006 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2007 ** it is initialized.
2008 */
2009 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2010 goto exit_drop_table;
2011 }
drhe5f9c642003-01-13 23:27:31 +00002012#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002013 {
2014 int code;
danielk1977da184232006-01-05 11:34:32 +00002015 const char *zTab = SCHEMA_TABLE(iDb);
2016 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002017 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002018 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002019 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002020 }
drhe5f9c642003-01-13 23:27:31 +00002021 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002022 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002023 code = SQLITE_DROP_TEMP_VIEW;
2024 }else{
2025 code = SQLITE_DROP_VIEW;
2026 }
danielk19774b2688a2006-06-20 11:01:07 +00002027#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002028 }else if( IsVirtual(pTab) ){
2029 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002030 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002031#endif
drhe5f9c642003-01-13 23:27:31 +00002032 }else{
danielk197753c0f742005-03-29 03:10:59 +00002033 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002034 code = SQLITE_DROP_TEMP_TABLE;
2035 }else{
2036 code = SQLITE_DROP_TABLE;
2037 }
2038 }
danielk1977f1a381e2006-06-16 08:01:02 +00002039 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002040 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002041 }
danielk1977a8858102004-05-28 12:11:21 +00002042 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2043 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002044 }
drhe5f9c642003-01-13 23:27:31 +00002045 }
2046#endif
drhc456e572008-08-11 18:44:58 +00002047 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002048 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002049 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002050 }
danielk1977576ec6b2005-01-21 11:55:25 +00002051
2052#ifndef SQLITE_OMIT_VIEW
2053 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2054 ** on a table.
2055 */
danielk1977a8858102004-05-28 12:11:21 +00002056 if( isView && pTab->pSelect==0 ){
2057 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2058 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002059 }
danielk1977a8858102004-05-28 12:11:21 +00002060 if( !isView && pTab->pSelect ){
2061 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2062 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002063 }
danielk1977576ec6b2005-01-21 11:55:25 +00002064#endif
drh75897232000-05-29 14:26:00 +00002065
drh1ccde152000-06-17 13:12:39 +00002066 /* Generate code to remove the table from the master table
2067 ** on disk.
2068 */
danielk19774adee202004-05-08 08:23:19 +00002069 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002070 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002071 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002072 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002073 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002074
danielk197720b1eaf2006-07-26 16:22:14 +00002075#ifndef SQLITE_OMIT_VIRTUALTABLE
2076 if( IsVirtual(pTab) ){
drh768578e2009-05-12 00:40:12 +00002077 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002078 }
2079#endif
dand66c8302009-09-28 14:49:01 +00002080 sqlite3FkDropTable(pParse, pName, pTab);
danielk197720b1eaf2006-07-26 16:22:14 +00002081
danielk19778e227872004-06-07 07:52:17 +00002082 /* Drop all triggers associated with the table being dropped. Code
2083 ** is generated to remove entries from sqlite_master and/or
2084 ** sqlite_temp_master if required.
2085 */
danielk19772f886d12009-02-28 10:47:41 +00002086 pTrigger = sqlite3TriggerList(pParse, pTab);
drhe0bc4042002-06-25 01:09:11 +00002087 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002088 assert( pTrigger->pSchema==pTab->pSchema ||
2089 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002090 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002091 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002092 }
drh8bf8dc92003-05-17 17:35:10 +00002093
danielk19774d36b812004-11-19 07:07:30 +00002094#ifndef SQLITE_OMIT_AUTOINCREMENT
2095 /* Remove any entries of the sqlite_sequence table associated with
2096 ** the table being dropped. This is done before the table is dropped
2097 ** at the btree level, in case the sqlite_sequence table needs to
2098 ** move as a result of the drop (can happen in auto-vacuum mode).
2099 */
drh7d10d5a2008-08-20 16:35:10 +00002100 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002101 sqlite3NestedParse(pParse,
2102 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2103 pDb->zName, pTab->zName
2104 );
2105 }
2106#endif
2107
danielk19778e227872004-06-07 07:52:17 +00002108 /* Drop all SQLITE_MASTER table and index entries that refer to the
2109 ** table. The program name loops through the master table and deletes
2110 ** every row that refers to a table of the same name as the one being
2111 ** dropped. Triggers are handled seperately because a trigger can be
2112 ** created in the temp database that refers to a table in another
2113 ** database.
2114 */
drhf1974842004-11-05 03:56:00 +00002115 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002116 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002117 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002118
2119 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2120 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2121 sqlite3NestedParse(pParse,
2122 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2123 );
2124 }
2125
danielk19774b2688a2006-06-20 11:01:07 +00002126 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002127 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002128 }
drh2958a4e2004-11-12 03:56:15 +00002129
danielk1977a21c6b62005-01-24 10:25:59 +00002130 /* Remove the table entry from SQLite's internal schema and modify
2131 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002132 */
drh4cbdda92006-06-14 19:00:20 +00002133 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002134 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002135 }
drh66a51672008-01-03 00:01:23 +00002136 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002137 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002138 }
drhd24cc422003-03-27 12:51:24 +00002139 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002140
2141exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002142 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002143}
2144
2145/*
drhc2eef3b2002-08-31 18:53:06 +00002146** This routine is called to create a new foreign key on the table
2147** currently under construction. pFromCol determines which columns
2148** in the current table point to the foreign key. If pFromCol==0 then
2149** connect the key to the last column inserted. pTo is the name of
2150** the table referred to. pToCol is a list of tables in the other
2151** pTo table that the foreign key points to. flags contains all
2152** information about the conflict resolution algorithms specified
2153** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2154**
2155** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002156** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002157**
2158** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002159** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002160*/
danielk19774adee202004-05-08 08:23:19 +00002161void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002162 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002163 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002164 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002165 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002166 int flags /* Conflict resolution algorithms. */
2167){
danielk197718576932008-08-06 13:47:40 +00002168 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002169#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002170 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002171 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002172 Table *p = pParse->pNewTable;
2173 int nByte;
2174 int i;
2175 int nCol;
2176 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002177
2178 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002179 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002180 if( pFromCol==0 ){
2181 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002182 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002183 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002184 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002185 " should reference only one column of table %T",
2186 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002187 goto fk_end;
2188 }
2189 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002190 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002191 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002192 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002193 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002194 goto fk_end;
2195 }else{
danielk19770202b292004-06-09 09:55:16 +00002196 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002197 }
drhe61922a2009-05-02 13:29:37 +00002198 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002199 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002200 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002201 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002202 }
2203 }
drh633e6d52008-07-28 19:34:53 +00002204 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002205 if( pFKey==0 ){
2206 goto fk_end;
2207 }
drhc2eef3b2002-08-31 18:53:06 +00002208 pFKey->pFrom = p;
2209 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002210 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002211 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002212 memcpy(z, pTo->z, pTo->n);
2213 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002214 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002215 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002216 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002217 if( pFromCol==0 ){
2218 pFKey->aCol[0].iFrom = p->nCol-1;
2219 }else{
2220 for(i=0; i<nCol; i++){
2221 int j;
2222 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002223 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002224 pFKey->aCol[i].iFrom = j;
2225 break;
2226 }
2227 }
2228 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002229 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002230 "unknown column \"%s\" in foreign key definition",
2231 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002232 goto fk_end;
2233 }
2234 }
2235 }
2236 if( pToCol ){
2237 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002238 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002239 pFKey->aCol[i].zCol = z;
2240 memcpy(z, pToCol->a[i].zName, n);
2241 z[n] = 0;
2242 z += n+1;
2243 }
2244 }
2245 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002246 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2247 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002248
drh21206082011-04-04 18:22:02 +00002249 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002250 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2251 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2252 );
danf59c5ca2009-09-22 16:55:38 +00002253 if( pNextTo==pFKey ){
2254 db->mallocFailed = 1;
2255 goto fk_end;
2256 }
dan1da40a32009-09-19 17:00:31 +00002257 if( pNextTo ){
2258 assert( pNextTo->pPrevTo==0 );
2259 pFKey->pNextTo = pNextTo;
2260 pNextTo->pPrevTo = pFKey;
2261 }
2262
drhc2eef3b2002-08-31 18:53:06 +00002263 /* Link the foreign key to the table as the last step.
2264 */
2265 p->pFKey = pFKey;
2266 pFKey = 0;
2267
2268fk_end:
drh633e6d52008-07-28 19:34:53 +00002269 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002270#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002271 sqlite3ExprListDelete(db, pFromCol);
2272 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002273}
2274
2275/*
2276** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2277** clause is seen as part of a foreign key definition. The isDeferred
2278** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2279** The behavior of the most recently created foreign key is adjusted
2280** accordingly.
2281*/
danielk19774adee202004-05-08 08:23:19 +00002282void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002283#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002284 Table *pTab;
2285 FKey *pFKey;
2286 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002287 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002288 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002289#endif
drhc2eef3b2002-08-31 18:53:06 +00002290}
2291
2292/*
drh063336a2004-11-05 20:58:39 +00002293** Generate code that will erase and refill index *pIdx. This is
2294** used to initialize a newly created index or to recompute the
2295** content of an index in response to a REINDEX command.
2296**
2297** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002298** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002299** root page number of the index. If memRootPage is negative, then
2300** the index already exists and must be cleared before being refilled and
2301** the root page number of the index is taken from pIndex->tnum.
2302*/
2303static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2304 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002305 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2306 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drh063336a2004-11-05 20:58:39 +00002307 int addr1; /* Address of top of loop */
2308 int tnum; /* Root page of index */
2309 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002310 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002311 int regIdxKey; /* Registers containing the index key */
2312 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002313 sqlite3 *db = pParse->db; /* The database connection */
2314 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002315
danielk19771d54df82004-11-23 15:41:16 +00002316#ifndef SQLITE_OMIT_AUTHORIZATION
2317 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002318 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002319 return;
2320 }
2321#endif
2322
danielk1977c00da102006-01-07 13:21:04 +00002323 /* Require a write-lock on the table to perform this operation */
2324 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2325
drh063336a2004-11-05 20:58:39 +00002326 v = sqlite3GetVdbe(pParse);
2327 if( v==0 ) return;
2328 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002329 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002330 }else{
2331 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002332 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002333 }
danielk1977b3bf5562006-01-10 17:58:23 +00002334 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002335 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002336 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002337 if( memRootPage>=0 ){
2338 sqlite3VdbeChangeP5(v, 1);
2339 }
danielk1977c00da102006-01-07 13:21:04 +00002340 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002341 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002342 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002343 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002344 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002345 const int regRowid = regIdxKey + pIndex->nColumn;
2346 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2347 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002348
danielk1977de630352009-05-04 11:42:29 +00002349 /* The registers accessed by the OP_IsUnique opcode were allocated
2350 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2351 ** call above. Just before that function was freed they were released
2352 ** (made available to the compiler for reuse) using
2353 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2354 ** opcode use the values stored within seems dangerous. However, since
2355 ** we can be sure that no other temp registers have been allocated
2356 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2357 */
2358 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
dane0af83a2009-09-08 19:15:01 +00002359 sqlite3HaltConstraint(
2360 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002361 }
drh2d401ab2008-01-10 23:50:11 +00002362 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
danielk1977de630352009-05-04 11:42:29 +00002363 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002364 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002365 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002366 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002367 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2368 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002369}
2370
2371/*
drh23bf66d2004-12-14 03:34:34 +00002372** Create a new index for an SQL table. pName1.pName2 is the name of the index
2373** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002374** be NULL for a primary key or an index that is created to satisfy a
2375** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002376** as the table to be indexed. pParse->pNewTable is a table that is
2377** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002378**
drh382c0242001-10-06 16:33:02 +00002379** pList is a list of columns to be indexed. pList will be NULL if this
2380** is a primary key or unique-constraint on the most recent column added
2381** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002382**
2383** If the index is created successfully, return a pointer to the new Index
2384** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2385** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002386*/
dan1da40a32009-09-19 17:00:31 +00002387Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002388 Parse *pParse, /* All information about this parse */
2389 Token *pName1, /* First part of index name. May be NULL */
2390 Token *pName2, /* Second part of index name. May be NULL */
2391 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002392 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002393 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002394 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002395 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002396 int sortOrder, /* Sort order of primary key when pList==NULL */
2397 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002398){
dan1da40a32009-09-19 17:00:31 +00002399 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002400 Table *pTab = 0; /* Table to be indexed */
2401 Index *pIndex = 0; /* The index to be created */
2402 char *zName = 0; /* Name of the index */
2403 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002404 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002405 Token nullId; /* Fake token for an empty ID list */
2406 DbFixer sFix; /* For assigning database names to pTable */
2407 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002408 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002409 Db *pDb; /* The specific table containing the indexed database */
2410 int iDb; /* Index of the database that is being written */
2411 Token *pName = 0; /* Unqualified name of the index to create */
2412 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002413 int nCol;
2414 int nExtra = 0;
2415 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002416
drhd3001712009-05-12 17:46:53 +00002417 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
drh8af73d42009-05-13 22:58:28 +00002418 assert( pParse->nErr==0 ); /* Never called with prior errors */
2419 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002420 goto exit_create_index;
2421 }
2422 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002423 goto exit_create_index;
2424 }
drhdaffd0e2001-04-11 14:28:42 +00002425
drh75897232000-05-29 14:26:00 +00002426 /*
2427 ** Find the table that is to be indexed. Return early if not found.
2428 */
danielk1977cbb18d22004-05-28 11:37:27 +00002429 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002430
2431 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002432 ** to search for the table. 'Fix' the table name to this db
2433 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002434 */
2435 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002436 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002437 if( iDb<0 ) goto exit_create_index;
2438
danielk197753c0f742005-03-29 03:10:59 +00002439#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002440 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002441 ** is a temp table. If so, set the database to 1. Do not do this
2442 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002443 */
danielk1977fe910332007-12-02 11:46:34 +00002444 if( !db->init.busy ){
2445 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002446 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002447 iDb = 1;
2448 }
danielk1977ef2cb632004-05-29 02:37:19 +00002449 }
danielk197753c0f742005-03-29 03:10:59 +00002450#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002451
2452 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2453 sqlite3FixSrcList(&sFix, pTblName)
2454 ){
drh85c23c62005-08-20 03:03:04 +00002455 /* Because the parser constructs pTblName from a single identifier,
2456 ** sqlite3FixSrcList can never fail. */
2457 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002458 }
drhca424112008-01-25 15:04:48 +00002459 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002460 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002461 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002462 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002463 }else{
drhe3c41372001-09-17 20:25:58 +00002464 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002465 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002466 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002467 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002468 }
drhfdd6e852005-12-16 01:06:16 +00002469 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002470
drhd3001712009-05-12 17:46:53 +00002471 assert( pTab!=0 );
2472 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002473 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2474 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002475 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002476 goto exit_create_index;
2477 }
danielk1977576ec6b2005-01-21 11:55:25 +00002478#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002479 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002480 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002481 goto exit_create_index;
2482 }
danielk1977576ec6b2005-01-21 11:55:25 +00002483#endif
danielk19775ee9d692006-06-21 12:36:25 +00002484#ifndef SQLITE_OMIT_VIRTUALTABLE
2485 if( IsVirtual(pTab) ){
2486 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2487 goto exit_create_index;
2488 }
2489#endif
drh75897232000-05-29 14:26:00 +00002490
2491 /*
2492 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002493 ** index or table with the same name.
2494 **
2495 ** Exception: If we are reading the names of permanent indices from the
2496 ** sqlite_master table (because some other process changed the schema) and
2497 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002498 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002499 **
2500 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002501 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2502 ** own name.
drh75897232000-05-29 14:26:00 +00002503 */
danielk1977d8123362004-06-12 09:25:12 +00002504 if( pName ){
drh17435752007-08-16 04:30:38 +00002505 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002506 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002507 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002508 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002509 }
danielk1977d8123362004-06-12 09:25:12 +00002510 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002511 if( sqlite3FindTable(db, zName, 0)!=0 ){
2512 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2513 goto exit_create_index;
2514 }
2515 }
danielk197759a33f92007-03-17 10:26:59 +00002516 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2517 if( !ifNotExist ){
2518 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002519 }
danielk197759a33f92007-03-17 10:26:59 +00002520 goto exit_create_index;
2521 }
danielk1977a21c6b62005-01-24 10:25:59 +00002522 }else{
drhadbca9c2001-09-27 15:11:53 +00002523 int n;
2524 Index *pLoop;
2525 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002526 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002527 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002528 goto exit_create_index;
2529 }
drh75897232000-05-29 14:26:00 +00002530 }
2531
drhe5f9c642003-01-13 23:27:31 +00002532 /* Check for authorization to create an index.
2533 */
2534#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002535 {
drhfdd6e852005-12-16 01:06:16 +00002536 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002537 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002538 goto exit_create_index;
2539 }
2540 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002541 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002542 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002543 goto exit_create_index;
2544 }
drhe5f9c642003-01-13 23:27:31 +00002545 }
2546#endif
2547
drh75897232000-05-29 14:26:00 +00002548 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002549 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002550 ** So create a fake list to simulate this.
2551 */
2552 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002553 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002554 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002555 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002556 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002557 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002558 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002559 }
2560
danielk1977b3bf5562006-01-10 17:58:23 +00002561 /* Figure out how many bytes of space are required to store explicitly
2562 ** specified collation sequence names.
2563 */
2564 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002565 Expr *pExpr = pList->a[i].pExpr;
2566 if( pExpr ){
2567 CollSeq *pColl = pExpr->pColl;
2568 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2569 ** failure we have quit before reaching this point. */
2570 if( ALWAYS(pColl) ){
2571 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2572 }
danielk1977b3bf5562006-01-10 17:58:23 +00002573 }
2574 }
2575
drh75897232000-05-29 14:26:00 +00002576 /*
2577 ** Allocate the index structure.
2578 */
drhea678832008-12-10 19:26:22 +00002579 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002580 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002581 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002582 sizeof(Index) + /* Index structure */
2583 sizeof(int)*nCol + /* Index.aiColumn */
2584 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2585 sizeof(char *)*nCol + /* Index.azColl */
2586 sizeof(u8)*nCol + /* Index.aSortOrder */
2587 nName + 1 + /* Index.zName */
2588 nExtra /* Collation sequence names */
2589 );
drh17435752007-08-16 04:30:38 +00002590 if( db->mallocFailed ){
2591 goto exit_create_index;
2592 }
drh78aecb72006-02-10 18:08:09 +00002593 pIndex->azColl = (char**)(&pIndex[1]);
2594 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002595 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002596 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002597 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2598 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002599 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002600 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002601 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002602 pIndex->onError = (u8)onError;
2603 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002604 pIndex->pSchema = db->aDb[iDb].pSchema;
drh21206082011-04-04 18:22:02 +00002605 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002606
drhfdd6e852005-12-16 01:06:16 +00002607 /* Check to see if we should honor DESC requests on index columns
2608 */
danielk1977da184232006-01-05 11:34:32 +00002609 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002610 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002611 }else{
2612 sortOrderMask = 0; /* Ignore DESC */
2613 }
2614
drh1ccde152000-06-17 13:12:39 +00002615 /* Scan the names of the columns of the table to be indexed and
2616 ** load the column indices into the Index structure. Report an error
2617 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002618 **
2619 ** TODO: Add a test to make sure that the same column is not named
2620 ** more than once within the same index. Only the first instance of
2621 ** the column will ever be used by the optimizer. Note that using the
2622 ** same column more than once cannot be an error because that would
2623 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002624 */
drhfdd6e852005-12-16 01:06:16 +00002625 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2626 const char *zColName = pListItem->zName;
2627 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002628 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002629 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002630
drhfdd6e852005-12-16 01:06:16 +00002631 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2632 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002633 }
2634 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002635 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002636 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00002637 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00002638 goto exit_create_index;
2639 }
drh967e8b72000-06-21 13:59:10 +00002640 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002641 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2642 ** the way the "idxlist" non-terminal is constructed by the parser,
2643 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2644 ** must exist or else there must have been an OOM error. But if there
2645 ** was an OOM error, we would never reach this point. */
2646 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2647 int nColl;
2648 zColl = pListItem->pExpr->pColl->zName;
2649 nColl = sqlite3Strlen30(zColl) + 1;
2650 assert( nExtra>=nColl );
2651 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002652 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002653 zExtra += nColl;
2654 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002655 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002656 zColl = pTab->aCol[j].zColl;
2657 if( !zColl ){
2658 zColl = db->pDfltColl->zName;
2659 }
danielk19770202b292004-06-09 09:55:16 +00002660 }
drhb7f24de2009-05-13 17:35:23 +00002661 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002662 goto exit_create_index;
2663 }
danielk1977b3bf5562006-01-10 17:58:23 +00002664 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002665 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002666 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002667 }
drh51147ba2005-07-23 22:59:55 +00002668 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002669
danielk1977d8123362004-06-12 09:25:12 +00002670 if( pTab==pParse->pNewTable ){
2671 /* This routine has been called to create an automatic index as a
2672 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2673 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2674 ** i.e. one of:
2675 **
2676 ** CREATE TABLE t(x PRIMARY KEY, y);
2677 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2678 **
2679 ** Either way, check to see if the table already has such an index. If
2680 ** so, don't bother creating this one. This only applies to
2681 ** automatically created indices. Users can do as they wish with
2682 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002683 **
2684 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2685 ** (and thus suppressing the second one) even if they have different
2686 ** sort orders.
2687 **
2688 ** If there are different collating sequences or if the columns of
2689 ** the constraint occur in different orders, then the constraints are
2690 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002691 */
2692 Index *pIdx;
2693 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2694 int k;
2695 assert( pIdx->onError!=OE_None );
2696 assert( pIdx->autoIndex );
2697 assert( pIndex->onError!=OE_None );
2698
2699 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2700 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002701 const char *z1;
2702 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002703 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002704 z1 = pIdx->azColl[k];
2705 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002706 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002707 }
2708 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002709 if( pIdx->onError!=pIndex->onError ){
2710 /* This constraint creates the same index as a previous
2711 ** constraint specified somewhere in the CREATE TABLE statement.
2712 ** However the ON CONFLICT clauses are different. If both this
2713 ** constraint and the previous equivalent constraint have explicit
2714 ** ON CONFLICT clauses this is an error. Otherwise, use the
2715 ** explicitly specified behaviour for the index.
2716 */
2717 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2718 sqlite3ErrorMsg(pParse,
2719 "conflicting ON CONFLICT clauses specified", 0);
2720 }
2721 if( pIdx->onError==OE_Default ){
2722 pIdx->onError = pIndex->onError;
2723 }
2724 }
danielk1977d8123362004-06-12 09:25:12 +00002725 goto exit_create_index;
2726 }
2727 }
2728 }
2729
drh75897232000-05-29 14:26:00 +00002730 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002731 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002732 */
drh234c39d2004-07-24 03:30:47 +00002733 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002734 Index *p;
drh21206082011-04-04 18:22:02 +00002735 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002736 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002737 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002738 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002739 if( p ){
2740 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002741 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002742 goto exit_create_index;
2743 }
drh5e00f6c2001-09-13 13:46:56 +00002744 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002745 if( pTblName!=0 ){
2746 pIndex->tnum = db->init.newTnum;
2747 }
drhd78eeee2001-09-13 16:18:53 +00002748 }
2749
drh1d85d932004-02-14 23:05:52 +00002750 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002751 ** involves writing the index into the master table and filling in the
2752 ** index with the current table contents.
2753 **
drh1d85d932004-02-14 23:05:52 +00002754 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2755 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002756 ** CREATE INDEX statements are read out of the master table. In
2757 ** the latter case the index already exists on disk, which is why
2758 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002759 **
danielk1977cbb18d22004-05-28 11:37:27 +00002760 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002761 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2762 ** has just been created, it contains no data and the index initialization
2763 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002764 */
drhd3001712009-05-12 17:46:53 +00002765 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002766 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002767 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002768 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002769
danielk19774adee202004-05-08 08:23:19 +00002770 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002771 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002772
drhfdd6e852005-12-16 01:06:16 +00002773
drh063336a2004-11-05 20:58:39 +00002774 /* Create the rootpage for the index
2775 */
drhaee128d2005-02-14 20:48:18 +00002776 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002777 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002778
2779 /* Gather the complete text of the CREATE INDEX statement into
2780 ** the zStmt variable
2781 */
drhd3001712009-05-12 17:46:53 +00002782 if( pStart ){
2783 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002784 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002785 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002786 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002787 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002788 pName->z);
2789 }else{
2790 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002791 /* zStmt = sqlite3MPrintf(""); */
2792 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002793 }
drh063336a2004-11-05 20:58:39 +00002794
2795 /* Add an entry in sqlite_master for this index
2796 */
2797 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002798 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002799 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2800 pIndex->zName,
2801 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002802 iMem,
drh063336a2004-11-05 20:58:39 +00002803 zStmt
2804 );
drh633e6d52008-07-28 19:34:53 +00002805 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002806
danielk1977a21c6b62005-01-24 10:25:59 +00002807 /* Fill the index with data and reparse the schema. Code an OP_Expire
2808 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002809 */
danielk1977cbb18d22004-05-28 11:37:27 +00002810 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002811 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002812 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002813 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
dan39f1bcb2010-09-29 07:16:46 +00002814 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
2815 P4_DYNAMIC);
drh66a51672008-01-03 00:01:23 +00002816 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002817 }
drh75897232000-05-29 14:26:00 +00002818 }
2819
danielk1977d8123362004-06-12 09:25:12 +00002820 /* When adding an index to the list of indices for a table, make
2821 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002822 ** OE_Ignore. This is necessary for the correct constraint check
2823 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2824 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002825 */
drh234c39d2004-07-24 03:30:47 +00002826 if( db->init.busy || pTblName==0 ){
2827 if( onError!=OE_Replace || pTab->pIndex==0
2828 || pTab->pIndex->onError==OE_Replace){
2829 pIndex->pNext = pTab->pIndex;
2830 pTab->pIndex = pIndex;
2831 }else{
2832 Index *pOther = pTab->pIndex;
2833 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2834 pOther = pOther->pNext;
2835 }
2836 pIndex->pNext = pOther->pNext;
2837 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002838 }
dan1da40a32009-09-19 17:00:31 +00002839 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00002840 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002841 }
danielk1977d8123362004-06-12 09:25:12 +00002842
drh75897232000-05-29 14:26:00 +00002843 /* Clean up before exiting */
2844exit_create_index:
drh956bc922004-07-24 17:38:29 +00002845 if( pIndex ){
drhb9755982010-07-24 16:34:37 +00002846 sqlite3DbFree(db, pIndex->zColAff);
danielk1977cb9d8d82009-03-18 18:43:36 +00002847 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002848 }
drh633e6d52008-07-28 19:34:53 +00002849 sqlite3ExprListDelete(db, pList);
2850 sqlite3SrcListDelete(db, pTblName);
2851 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00002852 return pRet;
drh75897232000-05-29 14:26:00 +00002853}
2854
2855/*
drh51147ba2005-07-23 22:59:55 +00002856** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002857** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002858**
2859** aiRowEst[0] is suppose to contain the number of elements in the index.
2860** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2861** number of rows in the table that match any particular value of the
2862** first column of the index. aiRowEst[2] is an estimate of the number
2863** of rows that match any particular combiniation of the first 2 columns
2864** of the index. And so forth. It must always be the case that
2865*
2866** aiRowEst[N]<=aiRowEst[N-1]
2867** aiRowEst[N]>=1
2868**
2869** Apart from that, we have little to go on besides intuition as to
2870** how aiRowEst[] should be initialized. The numbers generated here
2871** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002872*/
2873void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002874 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002875 int i;
drh15564052010-09-25 22:32:56 +00002876 unsigned n;
drh28c4cf42005-07-27 20:41:43 +00002877 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00002878 a[0] = pIdx->pTable->nRowEst;
2879 if( a[0]<10 ) a[0] = 10;
2880 n = 10;
2881 for(i=1; i<=pIdx->nColumn; i++){
2882 a[i] = n;
2883 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00002884 }
2885 if( pIdx->onError!=OE_None ){
2886 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002887 }
2888}
2889
2890/*
drh74e24cd2002-01-09 03:19:59 +00002891** This routine will drop an existing named index. This routine
2892** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002893*/
drh4d91a702006-01-04 15:54:36 +00002894void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002895 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002896 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002897 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002898 int iDb;
drh75897232000-05-29 14:26:00 +00002899
drh8af73d42009-05-13 22:58:28 +00002900 assert( pParse->nErr==0 ); /* Never called with prior errors */
2901 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002902 goto exit_drop_index;
2903 }
drhd24cc422003-03-27 12:51:24 +00002904 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002905 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2906 goto exit_drop_index;
2907 }
danielk19774adee202004-05-08 08:23:19 +00002908 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002909 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002910 if( !ifExists ){
2911 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2912 }
drha6ecd332004-06-10 00:29:09 +00002913 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002914 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002915 }
drh485b39b2002-07-13 03:11:52 +00002916 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002917 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002918 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002919 goto exit_drop_index;
2920 }
danielk1977da184232006-01-05 11:34:32 +00002921 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002922#ifndef SQLITE_OMIT_AUTHORIZATION
2923 {
2924 int code = SQLITE_DROP_INDEX;
2925 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002926 const char *zDb = db->aDb[iDb].zName;
2927 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002928 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002929 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002930 }
danielk1977da184232006-01-05 11:34:32 +00002931 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002932 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002933 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002934 }
drhed6c8672003-01-12 18:02:16 +00002935 }
drhe5f9c642003-01-13 23:27:31 +00002936#endif
drh75897232000-05-29 14:26:00 +00002937
2938 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002939 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002940 if( v ){
drh77658e22007-12-04 16:54:52 +00002941 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002942 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00002943 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drhb17131a2004-11-05 22:18:49 +00002944 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2945 pIndex->zName
2946 );
danielk1977006015d2008-04-11 17:11:26 +00002947 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2948 sqlite3NestedParse(pParse,
2949 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2950 db->aDb[iDb].zName, pIndex->zName
2951 );
2952 }
drh9cbf3422008-01-17 16:22:13 +00002953 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002954 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002955 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002956 }
2957
drhd24cc422003-03-27 12:51:24 +00002958exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002959 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002960}
2961
2962/*
drhcf643722007-03-27 13:36:37 +00002963** pArray is a pointer to an array of objects. Each object in the
2964** array is szEntry bytes in size. This routine allocates a new
2965** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002966**
drhcf643722007-03-27 13:36:37 +00002967** *pnEntry is the number of entries already in use. *pnAlloc is
2968** the previously allocated size of the array. initSize is the
2969** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002970**
drhcf643722007-03-27 13:36:37 +00002971** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002972**
drhcf643722007-03-27 13:36:37 +00002973** This routine returns a pointer to the array of objects. This
2974** might be the same as the pArray parameter or it might be a different
2975** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002976*/
drhcf643722007-03-27 13:36:37 +00002977void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002978 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002979 void *pArray, /* Array of objects. Might be reallocated */
2980 int szEntry, /* Size of each object in the array */
2981 int initSize, /* Suggested initial allocation, in elements */
2982 int *pnEntry, /* Number of objects currently in use */
2983 int *pnAlloc, /* Current size of the allocation, in elements */
2984 int *pIdx /* Write the index of a new slot here */
2985){
2986 char *z;
2987 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002988 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002989 int newSize;
drhcf643722007-03-27 13:36:37 +00002990 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002991 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002992 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002993 *pIdx = -1;
2994 return pArray;
drh13449892005-09-07 21:22:45 +00002995 }
drh6a1e0712008-12-05 15:24:15 +00002996 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002997 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002998 }
drhcf643722007-03-27 13:36:37 +00002999 z = (char*)pArray;
3000 memset(&z[*pnEntry * szEntry], 0, szEntry);
3001 *pIdx = *pnEntry;
3002 ++*pnEntry;
3003 return pArray;
drh13449892005-09-07 21:22:45 +00003004}
3005
3006/*
drh75897232000-05-29 14:26:00 +00003007** Append a new element to the given IdList. Create a new IdList if
3008** need be.
drhdaffd0e2001-04-11 14:28:42 +00003009**
3010** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003011*/
drh17435752007-08-16 04:30:38 +00003012IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003013 int i;
drh75897232000-05-29 14:26:00 +00003014 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003015 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003016 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003017 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00003018 }
drhcf643722007-03-27 13:36:37 +00003019 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003020 db,
drhcf643722007-03-27 13:36:37 +00003021 pList->a,
3022 sizeof(pList->a[0]),
3023 5,
3024 &pList->nId,
3025 &pList->nAlloc,
3026 &i
3027 );
drh13449892005-09-07 21:22:45 +00003028 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003029 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003030 return 0;
drh75897232000-05-29 14:26:00 +00003031 }
drh17435752007-08-16 04:30:38 +00003032 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003033 return pList;
3034}
3035
3036/*
drhfe05af82005-07-21 03:14:59 +00003037** Delete an IdList.
3038*/
drh633e6d52008-07-28 19:34:53 +00003039void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003040 int i;
3041 if( pList==0 ) return;
3042 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003043 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003044 }
drh633e6d52008-07-28 19:34:53 +00003045 sqlite3DbFree(db, pList->a);
3046 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003047}
3048
3049/*
3050** Return the index in pList of the identifier named zId. Return -1
3051** if not found.
3052*/
3053int sqlite3IdListIndex(IdList *pList, const char *zName){
3054 int i;
3055 if( pList==0 ) return -1;
3056 for(i=0; i<pList->nId; i++){
3057 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3058 }
3059 return -1;
3060}
3061
3062/*
drha78c22c2008-11-11 18:28:58 +00003063** Expand the space allocated for the given SrcList object by
3064** creating nExtra new slots beginning at iStart. iStart is zero based.
3065** New slots are zeroed.
3066**
3067** For example, suppose a SrcList initially contains two entries: A,B.
3068** To append 3 new entries onto the end, do this:
3069**
3070** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3071**
3072** After the call above it would contain: A, B, nil, nil, nil.
3073** If the iStart argument had been 1 instead of 2, then the result
3074** would have been: A, nil, nil, nil, B. To prepend the new slots,
3075** the iStart value would be 0. The result then would
3076** be: nil, nil, nil, A, B.
3077**
3078** If a memory allocation fails the SrcList is unchanged. The
3079** db->mallocFailed flag will be set to true.
3080*/
3081SrcList *sqlite3SrcListEnlarge(
3082 sqlite3 *db, /* Database connection to notify of OOM errors */
3083 SrcList *pSrc, /* The SrcList to be enlarged */
3084 int nExtra, /* Number of new slots to add to pSrc->a[] */
3085 int iStart /* Index in pSrc->a[] of first new slot */
3086){
3087 int i;
3088
3089 /* Sanity checking on calling parameters */
3090 assert( iStart>=0 );
3091 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003092 assert( pSrc!=0 );
3093 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003094
3095 /* Allocate additional space if needed */
3096 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3097 SrcList *pNew;
3098 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003099 int nGot;
drha78c22c2008-11-11 18:28:58 +00003100 pNew = sqlite3DbRealloc(db, pSrc,
3101 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3102 if( pNew==0 ){
3103 assert( db->mallocFailed );
3104 return pSrc;
3105 }
3106 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003107 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003108 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003109 }
3110
3111 /* Move existing slots that come after the newly inserted slots
3112 ** out of the way */
3113 for(i=pSrc->nSrc-1; i>=iStart; i--){
3114 pSrc->a[i+nExtra] = pSrc->a[i];
3115 }
shane18e526c2008-12-10 22:30:24 +00003116 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003117
3118 /* Zero the newly allocated slots */
3119 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3120 for(i=iStart; i<iStart+nExtra; i++){
3121 pSrc->a[i].iCursor = -1;
3122 }
3123
3124 /* Return a pointer to the enlarged SrcList */
3125 return pSrc;
3126}
3127
3128
3129/*
drhad3cab52002-05-24 02:04:32 +00003130** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003131** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003132**
drha78c22c2008-11-11 18:28:58 +00003133** A SrcList is returned, or NULL if there is an OOM error. The returned
3134** SrcList might be the same as the SrcList that was input or it might be
3135** a new one. If an OOM error does occurs, then the prior value of pList
3136** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003137**
3138** If pDatabase is not null, it means that the table has an optional
3139** database name prefix. Like this: "database.table". The pDatabase
3140** points to the table name and the pTable points to the database name.
3141** The SrcList.a[].zName field is filled with the table name which might
3142** come from pTable (if pDatabase is NULL) or from pDatabase.
3143** SrcList.a[].zDatabase is filled with the database name from pTable,
3144** or with NULL if no database is specified.
3145**
3146** In other words, if call like this:
3147**
drh17435752007-08-16 04:30:38 +00003148** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003149**
3150** Then B is a table name and the database name is unspecified. If called
3151** like this:
3152**
drh17435752007-08-16 04:30:38 +00003153** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003154**
drhd3001712009-05-12 17:46:53 +00003155** Then C is the table name and B is the database name. If C is defined
3156** then so is B. In other words, we never have a case where:
3157**
3158** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003159**
3160** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3161** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003162*/
drh17435752007-08-16 04:30:38 +00003163SrcList *sqlite3SrcListAppend(
3164 sqlite3 *db, /* Connection to notify of malloc failures */
3165 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3166 Token *pTable, /* Table to append */
3167 Token *pDatabase /* Database of the table */
3168){
drha99db3b2004-06-19 14:49:12 +00003169 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003170 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003171 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003172 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003173 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003174 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003175 }
drha78c22c2008-11-11 18:28:58 +00003176 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3177 if( db->mallocFailed ){
3178 sqlite3SrcListDelete(db, pList);
3179 return 0;
drhad3cab52002-05-24 02:04:32 +00003180 }
drha78c22c2008-11-11 18:28:58 +00003181 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003182 if( pDatabase && pDatabase->z==0 ){
3183 pDatabase = 0;
3184 }
drhd3001712009-05-12 17:46:53 +00003185 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003186 Token *pTemp = pDatabase;
3187 pDatabase = pTable;
3188 pTable = pTemp;
3189 }
drh17435752007-08-16 04:30:38 +00003190 pItem->zName = sqlite3NameFromToken(db, pTable);
3191 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003192 return pList;
3193}
3194
3195/*
drhdfe88ec2008-11-03 20:55:06 +00003196** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003197*/
danielk19774adee202004-05-08 08:23:19 +00003198void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003199 int i;
drh9b3187e2005-01-18 14:45:47 +00003200 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003201 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003202 if( pList ){
3203 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3204 if( pItem->iCursor>=0 ) break;
3205 pItem->iCursor = pParse->nTab++;
3206 if( pItem->pSelect ){
3207 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3208 }
drh63eb5f22003-04-29 16:20:44 +00003209 }
3210 }
3211}
3212
3213/*
drhad3cab52002-05-24 02:04:32 +00003214** Delete an entire SrcList including all its substructure.
3215*/
drh633e6d52008-07-28 19:34:53 +00003216void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003217 int i;
drhbe5c89a2004-07-26 00:31:09 +00003218 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003219 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003220 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003221 sqlite3DbFree(db, pItem->zDatabase);
3222 sqlite3DbFree(db, pItem->zName);
3223 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003224 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003225 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003226 sqlite3SelectDelete(db, pItem->pSelect);
3227 sqlite3ExprDelete(db, pItem->pOn);
3228 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003229 }
drh633e6d52008-07-28 19:34:53 +00003230 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003231}
3232
drh982cef72000-05-30 16:27:03 +00003233/*
drh61dfc312006-12-16 16:25:15 +00003234** This routine is called by the parser to add a new term to the
3235** end of a growing FROM clause. The "p" parameter is the part of
3236** the FROM clause that has already been constructed. "p" is NULL
3237** if this is the first term of the FROM clause. pTable and pDatabase
3238** are the name of the table and database named in the FROM clause term.
3239** pDatabase is NULL if the database name qualifier is missing - the
3240** usual case. If the term has a alias, then pAlias points to the
3241** alias token. If the term is a subquery, then pSubquery is the
3242** SELECT statement that the subquery encodes. The pTable and
3243** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3244** parameters are the content of the ON and USING clauses.
3245**
3246** Return a new SrcList which encodes is the FROM with the new
3247** term added.
3248*/
3249SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003250 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003251 SrcList *p, /* The left part of the FROM clause already seen */
3252 Token *pTable, /* Name of the table to add to the FROM clause */
3253 Token *pDatabase, /* Name of the database containing pTable */
3254 Token *pAlias, /* The right-hand side of the AS subexpression */
3255 Select *pSubquery, /* A subquery used in place of a table name */
3256 Expr *pOn, /* The ON clause of a join */
3257 IdList *pUsing /* The USING clause of a join */
3258){
3259 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003260 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003261 if( !p && (pOn || pUsing) ){
3262 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3263 (pOn ? "ON" : "USING")
3264 );
3265 goto append_from_error;
3266 }
drh17435752007-08-16 04:30:38 +00003267 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003268 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003269 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003270 }
3271 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003272 assert( pAlias!=0 );
3273 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003274 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003275 }
3276 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003277 pItem->pOn = pOn;
3278 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003279 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003280
3281 append_from_error:
3282 assert( p==0 );
3283 sqlite3ExprDelete(db, pOn);
3284 sqlite3IdListDelete(db, pUsing);
3285 sqlite3SelectDelete(db, pSubquery);
3286 return 0;
drh61dfc312006-12-16 16:25:15 +00003287}
3288
3289/*
danielk1977b1c685b2008-10-06 16:18:39 +00003290** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3291** element of the source-list passed as the second argument.
3292*/
3293void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003294 assert( pIndexedBy!=0 );
3295 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003296 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3297 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3298 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3299 /* A "NOT INDEXED" clause was supplied. See parse.y
3300 ** construct "indexed_opt" for details. */
3301 pItem->notIndexed = 1;
3302 }else{
3303 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3304 }
3305 }
3306}
3307
3308/*
drh61dfc312006-12-16 16:25:15 +00003309** When building up a FROM clause in the parser, the join operator
3310** is initially attached to the left operand. But the code generator
3311** expects the join operator to be on the right operand. This routine
3312** Shifts all join operators from left to right for an entire FROM
3313** clause.
3314**
3315** Example: Suppose the join is like this:
3316**
3317** A natural cross join B
3318**
3319** The operator is "natural cross join". The A and B operands are stored
3320** in p->a[0] and p->a[1], respectively. The parser initially stores the
3321** operator with A. This routine shifts that operator over to B.
3322*/
3323void sqlite3SrcListShiftJoinType(SrcList *p){
3324 if( p && p->a ){
3325 int i;
3326 for(i=p->nSrc-1; i>0; i--){
3327 p->a[i].jointype = p->a[i-1].jointype;
3328 }
3329 p->a[0].jointype = 0;
3330 }
3331}
3332
3333/*
drhc4a3c772001-04-04 11:48:57 +00003334** Begin a transaction
3335*/
drh684917c2004-10-05 02:41:42 +00003336void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003337 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003338 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003339 int i;
drh5e00f6c2001-09-13 13:46:56 +00003340
drhd3001712009-05-12 17:46:53 +00003341 assert( pParse!=0 );
3342 db = pParse->db;
3343 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003344/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003345 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3346 return;
3347 }
danielk19771d850a72004-05-31 08:26:49 +00003348 v = sqlite3GetVdbe(pParse);
3349 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003350 if( type!=TK_DEFERRED ){
3351 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003352 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003353 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003354 }
3355 }
drh66a51672008-01-03 00:01:23 +00003356 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003357}
3358
3359/*
3360** Commit a transaction
3361*/
danielk19774adee202004-05-08 08:23:19 +00003362void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003363 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003364 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003365
drhd3001712009-05-12 17:46:53 +00003366 assert( pParse!=0 );
3367 db = pParse->db;
3368 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003369/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003370 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3371 return;
3372 }
danielk19771d850a72004-05-31 08:26:49 +00003373 v = sqlite3GetVdbe(pParse);
3374 if( v ){
drh66a51672008-01-03 00:01:23 +00003375 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003376 }
drhc4a3c772001-04-04 11:48:57 +00003377}
3378
3379/*
3380** Rollback a transaction
3381*/
danielk19774adee202004-05-08 08:23:19 +00003382void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003383 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003384 Vdbe *v;
3385
drhd3001712009-05-12 17:46:53 +00003386 assert( pParse!=0 );
3387 db = pParse->db;
3388 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003389/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003390 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3391 return;
3392 }
danielk19774adee202004-05-08 08:23:19 +00003393 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003394 if( v ){
drh66a51672008-01-03 00:01:23 +00003395 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003396 }
drhc4a3c772001-04-04 11:48:57 +00003397}
drhf57b14a2001-09-14 18:54:08 +00003398
3399/*
danielk1977fd7f0452008-12-17 17:30:26 +00003400** This function is called by the parser when it parses a command to create,
3401** release or rollback an SQL savepoint.
3402*/
3403void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003404 char *zName = sqlite3NameFromToken(pParse->db, pName);
3405 if( zName ){
3406 Vdbe *v = sqlite3GetVdbe(pParse);
3407#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003408 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003409 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3410#endif
3411 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3412 sqlite3DbFree(pParse->db, zName);
3413 return;
3414 }
3415 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003416 }
3417}
3418
3419/*
drhdc3ff9c2004-08-18 02:10:15 +00003420** Make sure the TEMP database is open and available for use. Return
3421** the number of errors. Leave any error messages in the pParse structure.
3422*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003423int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003424 sqlite3 *db = pParse->db;
3425 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003426 int rc;
drh10a76c92010-01-26 01:25:26 +00003427 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003428 static const int flags =
3429 SQLITE_OPEN_READWRITE |
3430 SQLITE_OPEN_CREATE |
3431 SQLITE_OPEN_EXCLUSIVE |
3432 SQLITE_OPEN_DELETEONCLOSE |
3433 SQLITE_OPEN_TEMP_DB;
3434
drh75c014c2010-08-30 15:02:28 +00003435 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003436 if( rc!=SQLITE_OK ){
3437 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3438 "file for storing temporary tables");
3439 pParse->rc = rc;
3440 return 1;
3441 }
drh10a76c92010-01-26 01:25:26 +00003442 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003443 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003444 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3445 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003446 return 1;
drh10a76c92010-01-26 01:25:26 +00003447 }
drhdc3ff9c2004-08-18 02:10:15 +00003448 }
3449 return 0;
3450}
3451
3452/*
drh80242052004-06-09 00:48:12 +00003453** Generate VDBE code that will verify the schema cookie and start
3454** a read-transaction for all named database files.
3455**
3456** It is important that all schema cookies be verified and all
3457** read transactions be started before anything else happens in
3458** the VDBE program. But this routine can be called after much other
3459** code has been generated. So here is what we do:
3460**
drhc275b4e2004-07-19 17:25:24 +00003461** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003462** will jump to a subroutine at the end of the program. Then we
3463** record every database that needs its schema verified in the
3464** pParse->cookieMask field. Later, after all other code has been
3465** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003466** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003467** will be made to point to that subroutine. The generation of the
3468** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003469**
3470** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3471** schema on any databases. This can be used to position the OP_Goto
3472** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003473*/
danielk19774adee202004-05-08 08:23:19 +00003474void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003475 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003476
dan65a7cd12009-09-01 12:16:01 +00003477 if( pToplevel->cookieGoto==0 ){
3478 Vdbe *v = sqlite3GetVdbe(pToplevel);
3479 if( v==0 ) return; /* This only happens if there was a prior error */
3480 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003481 }
drhc275b4e2004-07-19 17:25:24 +00003482 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003483 sqlite3 *db = pToplevel->db;
drh64123582011-04-02 20:01:02 +00003484 yDbMask mask;
dan65a7cd12009-09-01 12:16:01 +00003485
drhc275b4e2004-07-19 17:25:24 +00003486 assert( iDb<db->nDb );
3487 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003488 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drh21206082011-04-04 18:22:02 +00003489 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh64123582011-04-02 20:01:02 +00003490 mask = ((yDbMask)1)<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003491 if( (pToplevel->cookieMask & mask)==0 ){
3492 pToplevel->cookieMask |= mask;
3493 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003494 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003495 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003496 }
drhc275b4e2004-07-19 17:25:24 +00003497 }
drh001bbcb2003-03-19 03:14:00 +00003498 }
drh001bbcb2003-03-19 03:14:00 +00003499}
3500
3501/*
drh1c928532002-01-31 15:54:21 +00003502** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003503** might change the database.
3504**
3505** This routine starts a new transaction if we are not already within
3506** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003507** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003508** be set for operations that might fail (due to a constraint) part of
3509** the way through and which will need to undo some writes without having to
3510** rollback the whole transaction. For operations where all constraints
3511** can be checked before any changes are made to the database, it is never
3512** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003513*/
drh7f0f12e2004-05-21 13:39:50 +00003514void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003515 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003516 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003517 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003518 pToplevel->isMultiWrite |= setStatement;
3519}
3520
drhff738bc2009-09-24 00:09:58 +00003521/*
3522** Indicate that the statement currently under construction might write
3523** more than one entry (example: deleting one row then inserting another,
3524** inserting multiple rows in a table, or inserting a row and index entries.)
3525** If an abort occurs after some of these writes have completed, then it will
3526** be necessary to undo the completed writes.
3527*/
3528void sqlite3MultiWrite(Parse *pParse){
3529 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3530 pToplevel->isMultiWrite = 1;
3531}
3532
dane0af83a2009-09-08 19:15:01 +00003533/*
drhff738bc2009-09-24 00:09:58 +00003534** The code generator calls this routine if is discovers that it is
3535** possible to abort a statement prior to completion. In order to
3536** perform this abort without corrupting the database, we need to make
3537** sure that the statement is protected by a statement transaction.
3538**
3539** Technically, we only need to set the mayAbort flag if the
3540** isMultiWrite flag was previously set. There is a time dependency
3541** such that the abort must occur after the multiwrite. This makes
3542** some statements involving the REPLACE conflict resolution algorithm
3543** go a little faster. But taking advantage of this time dependency
3544** makes it more difficult to prove that the code is correct (in
3545** particular, it prevents us from writing an effective
3546** implementation of sqlite3AssertMayAbort()) and so we have chosen
3547** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003548*/
3549void sqlite3MayAbort(Parse *pParse){
3550 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3551 pToplevel->mayAbort = 1;
3552}
3553
3554/*
3555** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3556** error. The onError parameter determines which (if any) of the statement
3557** and/or current transaction is rolled back.
3558*/
3559void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3560 Vdbe *v = sqlite3GetVdbe(pParse);
3561 if( onError==OE_Abort ){
3562 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003563 }
dane0af83a2009-09-08 19:15:01 +00003564 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003565}
3566
drh4343fea2004-11-05 23:46:15 +00003567/*
3568** Check to see if pIndex uses the collating sequence pColl. Return
3569** true if it does and false if it does not.
3570*/
3571#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003572static int collationMatch(const char *zColl, Index *pIndex){
3573 int i;
drh04491712009-05-13 17:21:13 +00003574 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003575 for(i=0; i<pIndex->nColumn; i++){
3576 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003577 assert( z!=0 );
3578 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003579 return 1;
3580 }
drh4343fea2004-11-05 23:46:15 +00003581 }
3582 return 0;
3583}
3584#endif
3585
3586/*
3587** Recompute all indices of pTab that use the collating sequence pColl.
3588** If pColl==0 then recompute all indices of pTab.
3589*/
3590#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003591static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003592 Index *pIndex; /* An index associated with pTab */
3593
3594 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003595 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003596 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3597 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003598 sqlite3RefillIndex(pParse, pIndex, -1);
3599 }
3600 }
3601}
3602#endif
3603
3604/*
3605** Recompute all indices of all tables in all databases where the
3606** indices use the collating sequence pColl. If pColl==0 then recompute
3607** all indices everywhere.
3608*/
3609#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003610static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003611 Db *pDb; /* A single database */
3612 int iDb; /* The database index number */
3613 sqlite3 *db = pParse->db; /* The database connection */
3614 HashElem *k; /* For looping over tables in pDb */
3615 Table *pTab; /* A table in the database */
3616
drh21206082011-04-04 18:22:02 +00003617 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00003618 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003619 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003620 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003621 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003622 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003623 }
3624 }
3625}
3626#endif
3627
3628/*
drheee46cf2004-11-06 00:02:48 +00003629** Generate code for the REINDEX command.
3630**
3631** REINDEX -- 1
3632** REINDEX <collation> -- 2
3633** REINDEX ?<database>.?<tablename> -- 3
3634** REINDEX ?<database>.?<indexname> -- 4
3635**
3636** Form 1 causes all indices in all attached databases to be rebuilt.
3637** Form 2 rebuilds all indices in all databases that use the named
3638** collating function. Forms 3 and 4 rebuild the named index or all
3639** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003640*/
3641#ifndef SQLITE_OMIT_REINDEX
3642void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3643 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3644 char *z; /* Name of a table or index */
3645 const char *zDb; /* Name of the database */
3646 Table *pTab; /* A table in the database */
3647 Index *pIndex; /* An index associated with pTab */
3648 int iDb; /* The database index number */
3649 sqlite3 *db = pParse->db; /* The database connection */
3650 Token *pObjName; /* Name of the table or index to be reindexed */
3651
danielk197733a5edc2005-01-27 00:22:02 +00003652 /* Read the database schema. If an error occurs, leave an error message
3653 ** and code in pParse and return NULL. */
3654 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003655 return;
danielk197733a5edc2005-01-27 00:22:02 +00003656 }
3657
drh8af73d42009-05-13 22:58:28 +00003658 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003659 reindexDatabases(pParse, 0);
3660 return;
drhd3001712009-05-12 17:46:53 +00003661 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003662 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003663 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003664 zColl = sqlite3NameFromToken(pParse->db, pName1);
3665 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003666 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003667 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003668 reindexDatabases(pParse, zColl);
3669 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003670 return;
3671 }
drh633e6d52008-07-28 19:34:53 +00003672 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003673 }
3674 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3675 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003676 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003677 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003678 zDb = db->aDb[iDb].zName;
3679 pTab = sqlite3FindTable(db, z, zDb);
3680 if( pTab ){
3681 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003682 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003683 return;
3684 }
3685 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003686 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003687 if( pIndex ){
3688 sqlite3BeginWriteOperation(pParse, 0, iDb);
3689 sqlite3RefillIndex(pParse, pIndex, -1);
3690 return;
3691 }
3692 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3693}
3694#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003695
3696/*
3697** Return a dynamicly allocated KeyInfo structure that can be used
3698** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3699**
3700** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003701** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003702** pointer. If an error occurs (out of memory or missing collation
3703** sequence), NULL is returned and the state of pParse updated to reflect
3704** the error.
3705*/
3706KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3707 int i;
3708 int nCol = pIdx->nColumn;
3709 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003710 sqlite3 *db = pParse->db;
3711 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003712
3713 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003714 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003715 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3716 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3717 for(i=0; i<nCol; i++){
3718 char *zColl = pIdx->azColl[i];
3719 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003720 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003721 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3722 }
drh1bd10f82008-12-10 21:19:56 +00003723 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003724 }
3725
3726 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003727 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003728 pKey = 0;
3729 }
3730 return pKey;
3731}