blob: edc70dc916728f9f74bf673b76c8e6e832f9d65d [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 ){
drh80242052004-06-09 00:48:12 +0000151 u32 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 ){
159 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
160 }
drh80242052004-06-09 00:48:12 +0000161 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000162#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000163 {
164 int i;
165 for(i=0; i<pParse->nVtabLock; i++){
danielk1977595a5232009-07-24 17:58:53 +0000166 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
drh26e4a8b2008-05-01 17:16:52 +0000167 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
168 }
169 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000170 }
171#endif
danielk1977c00da102006-01-07 13:21:04 +0000172
173 /* Once all the cookies have been verified and transactions opened,
174 ** obtain the required table-locks. This is a no-op unless the
175 ** shared-cache feature is enabled.
176 */
177 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000178
179 /* Initialize any AUTOINCREMENT data structures required.
180 */
181 sqlite3AutoincrementBegin(pParse);
182
183 /* Finally, jump back to the beginning of the executable code. */
drh66a51672008-01-03 00:01:23 +0000184 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000185 }
drh71c697e2004-08-08 23:39:19 +0000186 }
187
drh3f7d4e42004-07-24 14:35:58 +0000188
drh80242052004-06-09 00:48:12 +0000189 /* Get the VDBE program ready for execution
190 */
drh04491712009-05-13 17:21:13 +0000191 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000192#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000193 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000194 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000195#endif
drhceea3322009-04-23 13:22:42 +0000196 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000197 /* A minimum of one cursor is required if autoincrement is used
198 * See ticket [a696379c1f08866] */
199 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
danielk19776ab3a2e2009-02-19 14:39:25 +0000200 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
dane0af83a2009-09-08 19:15:01 +0000201 pParse->nTab, pParse->nMaxArg, pParse->explain,
202 pParse->isMultiWrite && pParse->mayAbort);
danielk1977441daf62005-02-01 03:46:43 +0000203 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000204 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000205 }else{
drh483750b2003-01-29 18:46:51 +0000206 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000207 }
drha226d052002-09-25 19:04:07 +0000208 pParse->nTab = 0;
209 pParse->nMem = 0;
210 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000211 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000212 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000213 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000214}
215
216/*
drh205f48e2004-11-05 00:43:11 +0000217** Run the parser and code generator recursively in order to generate
218** code for the SQL statement given onto the end of the pParse context
219** currently under construction. When the parser is run recursively
220** this way, the final OP_Halt is not appended and other initialization
221** and finalization steps are omitted because those are handling by the
222** outermost parser.
223**
224** Not everything is nestable. This facility is designed to permit
225** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000226** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000227*/
228void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
229 va_list ap;
230 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000231 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000232 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000233# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
234 char saveBuf[SAVE_SZ];
235
drh205f48e2004-11-05 00:43:11 +0000236 if( pParse->nErr ) return;
237 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
238 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000239 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000240 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000241 if( zSql==0 ){
242 return; /* A malloc must have failed */
243 }
drh205f48e2004-11-05 00:43:11 +0000244 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000245 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
246 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000247 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000248 sqlite3DbFree(db, zErrMsg);
249 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000250 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000251 pParse->nested--;
252}
253
254/*
danielk19778a414492004-06-29 08:59:35 +0000255** Locate the in-memory structure that describes a particular database
256** table given the name of that table and (optionally) the name of the
257** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000258**
danielk19778a414492004-06-29 08:59:35 +0000259** If zDatabase is 0, all databases are searched for the table and the
260** first matching table is returned. (No checking for duplicate table
261** names is done.) The search order is TEMP first, then MAIN, then any
262** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000263**
danielk19774adee202004-05-08 08:23:19 +0000264** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000265*/
drh9bb575f2004-09-06 17:24:11 +0000266Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000267 Table *p = 0;
268 int i;
drh0a687d12008-07-08 14:52:07 +0000269 int nName;
drh645f63e2004-06-22 13:22:40 +0000270 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000271 nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000272 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000273 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000274 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh0a687d12008-07-08 14:52:07 +0000275 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000276 if( p ) break;
277 }
drh74e24cd2002-01-09 03:19:59 +0000278 return p;
drh75897232000-05-29 14:26:00 +0000279}
280
281/*
danielk19778a414492004-06-29 08:59:35 +0000282** Locate the in-memory structure that describes a particular database
283** table given the name of that table and (optionally) the name of the
284** database containing the table. Return NULL if not found. Also leave an
285** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000286**
danielk19778a414492004-06-29 08:59:35 +0000287** The difference between this routine and sqlite3FindTable() is that this
288** routine leaves an error message in pParse->zErrMsg where
289** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000290*/
drhca424112008-01-25 15:04:48 +0000291Table *sqlite3LocateTable(
292 Parse *pParse, /* context in which to report errors */
293 int isView, /* True if looking for a VIEW rather than a TABLE */
294 const char *zName, /* Name of the table we are looking for */
295 const char *zDbase /* Name of the database. Might be NULL */
296){
drha69d9162003-04-17 22:57:53 +0000297 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000298
danielk19778a414492004-06-29 08:59:35 +0000299 /* Read the database schema. If an error occurs, leave an error message
300 ** and code in pParse and return NULL. */
301 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
302 return 0;
303 }
304
danielk19774adee202004-05-08 08:23:19 +0000305 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000306 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000307 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000308 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000309 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000310 }else{
drhca424112008-01-25 15:04:48 +0000311 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000312 }
drha6ecd332004-06-10 00:29:09 +0000313 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000314 }
315 return p;
316}
317
318/*
319** Locate the in-memory structure that describes
320** a particular index given the name of that index
321** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000322** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000323**
324** If zDatabase is 0, all databases are searched for the
325** table and the first matching index is returned. (No checking
326** for duplicate index names is done.) The search order is
327** TEMP first, then MAIN, then any auxiliary databases added
328** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000329*/
drh9bb575f2004-09-06 17:24:11 +0000330Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000331 Index *p = 0;
332 int i;
drhdee0e402009-05-03 20:23:53 +0000333 int nName = sqlite3Strlen30(zName);
danielk197753c0f742005-03-29 03:10:59 +0000334 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000335 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000336 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000337 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000338 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh04491712009-05-13 17:21:13 +0000339 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000340 if( p ) break;
341 }
drh74e24cd2002-01-09 03:19:59 +0000342 return p;
drh75897232000-05-29 14:26:00 +0000343}
344
345/*
drh956bc922004-07-24 17:38:29 +0000346** Reclaim the memory used by an index
347*/
dan1feeaed2010-07-23 15:41:47 +0000348static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000349#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000350 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000351#endif
drh633e6d52008-07-28 19:34:53 +0000352 sqlite3DbFree(db, p->zColAff);
353 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000354}
355
356/*
drhc96d8532005-05-03 12:30:33 +0000357** For the index called zIdxName which is found in the database iDb,
358** unlike that index from its Table then remove the index from
359** the index hash table and free all memory structures associated
360** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000361*/
drh9bb575f2004-09-06 17:24:11 +0000362void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000363 Index *pIndex;
364 int len;
danielk1977da184232006-01-05 11:34:32 +0000365 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000366
drhdee0e402009-05-03 20:23:53 +0000367 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000368 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh9635cc72009-06-25 11:50:21 +0000369 if( pIndex ){
drh956bc922004-07-24 17:38:29 +0000370 if( pIndex->pTable->pIndex==pIndex ){
371 pIndex->pTable->pIndex = pIndex->pNext;
372 }else{
373 Index *p;
drh04491712009-05-13 17:21:13 +0000374 /* Justification of ALWAYS(); The index must be on the list of
375 ** indices. */
376 p = pIndex->pTable->pIndex;
377 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
378 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000379 p->pNext = pIndex->pNext;
380 }
drh5e00f6c2001-09-13 13:46:56 +0000381 }
dan1feeaed2010-07-23 15:41:47 +0000382 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000383 }
drh956bc922004-07-24 17:38:29 +0000384 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000385}
386
387/*
drhe0bc4042002-06-25 01:09:11 +0000388** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000389** a single database. This routine is called to reclaim memory
390** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000391** if there were schema changes during the transaction or if a
392** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000393**
drh62312862009-02-03 22:17:42 +0000394** If iDb==0 then reset the internal schema tables for all database
395** files. If iDb>=1 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000396** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000397*/
drh9bb575f2004-09-06 17:24:11 +0000398void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000399 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000400 assert( iDb>=0 && iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000401
402 if( iDb==0 ){
403 sqlite3BtreeEnterAll(db);
404 }
drh1c2d8412003-03-31 00:30:47 +0000405 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000406 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000407 if( pDb->pSchema ){
danielk19774eab8b72007-12-27 15:12:16 +0000408 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
danielk1977de0fe3e2006-01-06 06:33:12 +0000409 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000410 }
drh1c2d8412003-03-31 00:30:47 +0000411 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000412 }
drh1c2d8412003-03-31 00:30:47 +0000413 assert( iDb==0 );
414 db->flags &= ~SQLITE_InternChanges;
danielk1977595a5232009-07-24 17:58:53 +0000415 sqlite3VtabUnlockList(db);
danielk19774eab8b72007-12-27 15:12:16 +0000416 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000417
418 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000419 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000420 ** opportunity to do this here since we have just deleted all of the
421 ** schema hash tables and therefore do not have to make any changes
422 ** to any of those tables.
423 */
424 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000425 struct Db *pDb = &db->aDb[i];
426 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000427 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000428 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000429 continue;
430 }
431 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000432 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000433 }
drh8bf8dc92003-05-17 17:35:10 +0000434 j++;
drh1c2d8412003-03-31 00:30:47 +0000435 }
436 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
437 db->nDb = j;
438 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
439 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000440 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000441 db->aDb = db->aDbStatic;
442 }
drhe0bc4042002-06-25 01:09:11 +0000443}
444
445/*
drhe0bc4042002-06-25 01:09:11 +0000446** This routine is called when a commit occurs.
447*/
drh9bb575f2004-09-06 17:24:11 +0000448void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000449 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000450}
451
452/*
dand46def72010-07-24 11:28:28 +0000453** Delete memory allocated for the column names of a table or view (the
454** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000455*/
dand46def72010-07-24 11:28:28 +0000456static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000457 int i;
458 Column *pCol;
459 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000460 if( (pCol = pTable->aCol)!=0 ){
461 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000462 sqlite3DbFree(db, pCol->zName);
463 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000464 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000465 sqlite3DbFree(db, pCol->zType);
466 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000467 }
drh633e6d52008-07-28 19:34:53 +0000468 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000469 }
drh956bc922004-07-24 17:38:29 +0000470}
471
472/*
drh75897232000-05-29 14:26:00 +0000473** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000474** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000475**
476** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000477** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000478** memory structures of the indices and foreign keys associated with
479** the table.
drh75897232000-05-29 14:26:00 +0000480*/
dan1feeaed2010-07-23 15:41:47 +0000481void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000482 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000483
dand46def72010-07-24 11:28:28 +0000484 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000485
drhed8a3bb2005-06-06 21:19:56 +0000486 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000487 if( !pTable ) return;
488 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000489
dand46def72010-07-24 11:28:28 +0000490 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000491 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
492 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000493 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000494 if( !db || db->pnBytesFreed==0 ){
495 char *zName = pIndex->zName;
496 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
497 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
498 );
499 assert( pOld==pIndex || pOld==0 );
500 }
501 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000502 }
503
dan1da40a32009-09-19 17:00:31 +0000504 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000505 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000506
507 /* Delete the Table structure itself.
508 */
dand46def72010-07-24 11:28:28 +0000509 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000510 sqlite3DbFree(db, pTable->zName);
511 sqlite3DbFree(db, pTable->zColAff);
512 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000513#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000514 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000515#endif
drh078e4082010-07-28 19:17:51 +0000516#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000517 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000518#endif
drh633e6d52008-07-28 19:34:53 +0000519 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000520}
521
522/*
drh5edc3122001-09-13 21:53:09 +0000523** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000524** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000525*/
drh9bb575f2004-09-06 17:24:11 +0000526void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000527 Table *p;
drh956bc922004-07-24 17:38:29 +0000528 Db *pDb;
529
drhd229ca92002-01-09 13:30:41 +0000530 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000531 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000532 assert( zTabName );
533 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000534 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000535 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000536 sqlite3Strlen30(zTabName),0);
dan1feeaed2010-07-23 15:41:47 +0000537 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000538 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000539}
540
541/*
drha99db3b2004-06-19 14:49:12 +0000542** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000543** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000544** is obtained from sqliteMalloc() and must be freed by the calling
545** function.
drh75897232000-05-29 14:26:00 +0000546**
drh24fb6272009-05-01 21:13:36 +0000547** Any quotation marks (ex: "name", 'name', [name], or `name`) that
548** surround the body of the token are removed.
549**
drhc96d8532005-05-03 12:30:33 +0000550** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000551** are not \000 terminated and are not persistent. The returned string
552** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000553*/
drh17435752007-08-16 04:30:38 +0000554char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000555 char *zName;
556 if( pName ){
drh17435752007-08-16 04:30:38 +0000557 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000558 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000559 }else{
560 zName = 0;
561 }
drh75897232000-05-29 14:26:00 +0000562 return zName;
563}
564
565/*
danielk1977cbb18d22004-05-28 11:37:27 +0000566** Open the sqlite_master table stored in database number iDb for
567** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000568*/
danielk1977c00da102006-01-07 13:21:04 +0000569void sqlite3OpenMasterTable(Parse *p, int iDb){
570 Vdbe *v = sqlite3GetVdbe(p);
571 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000572 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000573 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000574 if( p->nTab==0 ){
575 p->nTab = 1;
576 }
drhe0bc4042002-06-25 01:09:11 +0000577}
578
579/*
danielk197704103022009-02-03 16:51:24 +0000580** Parameter zName points to a nul-terminated buffer containing the name
581** of a database ("main", "temp" or the name of an attached db). This
582** function returns the index of the named database in db->aDb[], or
583** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000584*/
danielk197704103022009-02-03 16:51:24 +0000585int sqlite3FindDbName(sqlite3 *db, const char *zName){
586 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000587 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000588 Db *pDb;
589 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000590 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000591 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000592 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000593 break;
drh73c42a12004-11-20 18:13:10 +0000594 }
danielk1977cbb18d22004-05-28 11:37:27 +0000595 }
596 }
danielk1977576ec6b2005-01-21 11:55:25 +0000597 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000598}
599
danielk197704103022009-02-03 16:51:24 +0000600/*
601** The token *pName contains the name of a database (either "main" or
602** "temp" or the name of an attached db). This routine returns the
603** index of the named database in db->aDb[], or -1 if the named db
604** does not exist.
605*/
606int sqlite3FindDb(sqlite3 *db, Token *pName){
607 int i; /* Database number */
608 char *zName; /* Name we are searching for */
609 zName = sqlite3NameFromToken(db, pName);
610 i = sqlite3FindDbName(db, zName);
611 sqlite3DbFree(db, zName);
612 return i;
613}
614
drh0e3d7472004-06-19 17:33:07 +0000615/* The table or view or trigger name is passed to this routine via tokens
616** pName1 and pName2. If the table name was fully qualified, for example:
617**
618** CREATE TABLE xxx.yyy (...);
619**
620** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
621** the table name is not fully qualified, i.e.:
622**
623** CREATE TABLE yyy(...);
624**
625** Then pName1 is set to "yyy" and pName2 is "".
626**
627** This routine sets the *ppUnqual pointer to point at the token (pName1 or
628** pName2) that stores the unqualified table name. The index of the
629** database "xxx" is returned.
630*/
danielk1977ef2cb632004-05-29 02:37:19 +0000631int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000632 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000633 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000634 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
635 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000636){
drh0e3d7472004-06-19 17:33:07 +0000637 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000638 sqlite3 *db = pParse->db;
639
drhc4a64fa2009-05-11 20:53:28 +0000640 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000641 if( db->init.busy ) {
642 sqlite3ErrorMsg(pParse, "corrupt database");
643 pParse->nErr++;
644 return -1;
645 }
danielk1977cbb18d22004-05-28 11:37:27 +0000646 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000647 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000648 if( iDb<0 ){
649 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
650 pParse->nErr++;
651 return -1;
652 }
653 }else{
654 assert( db->init.iDb==0 || db->init.busy );
655 iDb = db->init.iDb;
656 *pUnqual = pName1;
657 }
658 return iDb;
659}
660
661/*
danielk1977d8123362004-06-12 09:25:12 +0000662** This routine is used to check if the UTF-8 string zName is a legal
663** unqualified name for a new schema object (table, index, view or
664** trigger). All names are legal except those that begin with the string
665** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
666** is reserved for internal use.
667*/
668int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000669 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000670 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000671 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000672 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
673 return SQLITE_ERROR;
674 }
675 return SQLITE_OK;
676}
677
678/*
drh75897232000-05-29 14:26:00 +0000679** Begin constructing a new table representation in memory. This is
680** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000681** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000682** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000683** flag is true if the table should be stored in the auxiliary database
684** file instead of in the main database file. This is normally the case
685** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000686** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000687**
drhf57b3392001-10-08 13:22:32 +0000688** The new table record is initialized and put in pParse->pNewTable.
689** As more of the CREATE TABLE statement is parsed, additional action
690** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000691** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000692** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000693*/
danielk19774adee202004-05-08 08:23:19 +0000694void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000695 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000696 Token *pName1, /* First part of the name of the table or view */
697 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000698 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000699 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000700 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000701 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000702){
drh75897232000-05-29 14:26:00 +0000703 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000704 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000705 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000706 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000707 int iDb; /* Database number to create the table in */
708 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000709
danielk1977cbb18d22004-05-28 11:37:27 +0000710 /* The table or view name to create is passed to this routine via tokens
711 ** pName1 and pName2. If the table name was fully qualified, for example:
712 **
713 ** CREATE TABLE xxx.yyy (...);
714 **
715 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
716 ** the table name is not fully qualified, i.e.:
717 **
718 ** CREATE TABLE yyy(...);
719 **
720 ** Then pName1 is set to "yyy" and pName2 is "".
721 **
722 ** The call below sets the pName pointer to point at the token (pName1 or
723 ** pName2) that stores the unqualified table name. The variable iDb is
724 ** set to the index of the database that the table or view is to be
725 ** created in.
726 */
danielk1977ef2cb632004-05-29 02:37:19 +0000727 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000728 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000729 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
730 /* If creating a temp table, the name may not be qualified. Unless
731 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000732 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000733 return;
734 }
danielk197753c0f742005-03-29 03:10:59 +0000735 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000736
737 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000738 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000739 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000740 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000741 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000742 }
drh1d85d932004-02-14 23:05:52 +0000743 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000744#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000745 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000746 {
747 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000748 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000749 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000750 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000751 }
drhe5f9c642003-01-13 23:27:31 +0000752 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000753 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000754 code = SQLITE_CREATE_TEMP_VIEW;
755 }else{
756 code = SQLITE_CREATE_VIEW;
757 }
758 }else{
danielk197753c0f742005-03-29 03:10:59 +0000759 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000760 code = SQLITE_CREATE_TEMP_TABLE;
761 }else{
762 code = SQLITE_CREATE_TABLE;
763 }
764 }
danielk1977f1a381e2006-06-16 08:01:02 +0000765 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000766 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000767 }
768 }
769#endif
drhf57b3392001-10-08 13:22:32 +0000770
drhf57b3392001-10-08 13:22:32 +0000771 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000772 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000773 ** it does. The exception is if the statement being parsed was passed
774 ** to an sqlite3_declare_vtab() call. In that case only the column names
775 ** and types will be used, so there is no need to test for namespace
776 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000777 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000778 if( !IN_DECLARE_VTAB ){
779 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
780 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000781 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000782 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
783 if( pTable ){
784 if( !noErr ){
785 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
786 }
787 goto begin_table_error;
788 }
789 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
790 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
791 goto begin_table_error;
792 }
drh75897232000-05-29 14:26:00 +0000793 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000794
danielk197726783a52007-08-29 14:06:22 +0000795 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000796 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000797 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000798 pParse->rc = SQLITE_NOMEM;
799 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000800 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000801 }
drh75897232000-05-29 14:26:00 +0000802 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000803 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000804 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000805 pTable->nRef = 1;
drh15564052010-09-25 22:32:56 +0000806 pTable->nRowEst = 1000000;
drhc4a64fa2009-05-11 20:53:28 +0000807 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000808 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000809
drh4794f732004-11-05 17:17:50 +0000810 /* If this is the magic sqlite_sequence table used by autoincrement,
811 ** then record a pointer to this table in the main database structure
812 ** so that INSERT can find the table easily.
813 */
814#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000815 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000816 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000817 }
818#endif
819
drh17f71932002-02-21 12:01:27 +0000820 /* Begin generating the code that will insert the table record into
821 ** the SQLITE_MASTER table. Note in particular that we must go ahead
822 ** and allocate the record number for the table entry now. Before any
823 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
824 ** indices to be created and the table record must come before the
825 ** indices. Hence, the record number for the table must be allocated
826 ** now.
827 */
danielk19774adee202004-05-08 08:23:19 +0000828 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000829 int j1;
drhe321c292006-01-12 01:56:43 +0000830 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000831 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000832 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000833
danielk197720b1eaf2006-07-26 16:22:14 +0000834#ifndef SQLITE_OMIT_VIRTUALTABLE
835 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000836 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000837 }
838#endif
839
danielk197736963fd2005-02-19 08:18:05 +0000840 /* If the file format and encoding in the database have not been set,
841 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000842 */
drhb7654112008-01-12 12:48:07 +0000843 reg1 = pParse->regRowid = ++pParse->nMem;
844 reg2 = pParse->regRoot = ++pParse->nMem;
845 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000846 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000847 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000848 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000849 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000850 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000851 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000852 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000853 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000854 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000855 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000856
drh4794f732004-11-05 17:17:50 +0000857 /* This just creates a place-holder record in the sqlite_master table.
858 ** The record created does not contain anything yet. It will be replaced
859 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000860 **
drh0fa991b2009-03-21 16:19:26 +0000861 ** The rowid for the new entry is left in register pParse->regRowid.
862 ** The root page number of the new table is left in reg pParse->regRoot.
863 ** The rowid and root page number values are needed by the code that
864 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000865 */
danielk1977f1a381e2006-06-16 08:01:02 +0000866#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
867 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000868 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000869 }else
870#endif
871 {
drhb7654112008-01-12 12:48:07 +0000872 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000873 }
danielk1977c00da102006-01-07 13:21:04 +0000874 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000875 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
876 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
877 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
878 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000879 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000880 }
drh23bf66d2004-12-14 03:34:34 +0000881
882 /* Normal (non-error) return. */
883 return;
884
885 /* If an error occurs, we jump here */
886begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000887 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000888 return;
drh75897232000-05-29 14:26:00 +0000889}
890
891/*
danielk1977c60e9b82005-01-31 12:42:29 +0000892** This macro is used to compare two strings in a case-insensitive manner.
893** It is slightly faster than calling sqlite3StrICmp() directly, but
894** produces larger code.
895**
896** WARNING: This macro is not compatible with the strcmp() family. It
897** returns true if the two strings are equal, otherwise false.
898*/
899#define STRICMP(x, y) (\
900sqlite3UpperToLower[*(unsigned char *)(x)]== \
901sqlite3UpperToLower[*(unsigned char *)(y)] \
902&& sqlite3StrICmp((x)+1,(y)+1)==0 )
903
904/*
drh75897232000-05-29 14:26:00 +0000905** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000906**
907** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000908** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000909** first to get things going. Then this routine is called for each
910** column.
drh75897232000-05-29 14:26:00 +0000911*/
danielk19774adee202004-05-08 08:23:19 +0000912void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000913 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000914 int i;
drha99db3b2004-06-19 14:49:12 +0000915 char *z;
drhc9b84a12002-06-20 11:36:48 +0000916 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000917 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000918 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000919#if SQLITE_MAX_COLUMN
920 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000921 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
922 return;
923 }
drhbb4957f2008-03-20 14:03:29 +0000924#endif
danielk1977ae74e032008-12-23 11:11:51 +0000925 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000926 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000927 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000928 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000929 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000930 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000931 return;
932 }
933 }
drh75897232000-05-29 14:26:00 +0000934 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000935 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000936 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000937 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000938 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000939 return;
940 }
drh6d4abfb2001-10-22 02:58:08 +0000941 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000942 }
drhc9b84a12002-06-20 11:36:48 +0000943 pCol = &p->aCol[p->nCol];
944 memset(pCol, 0, sizeof(p->aCol[0]));
945 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000946
947 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000948 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
949 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000950 */
danielk19774f057f92004-06-08 00:02:33 +0000951 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000952 p->nCol++;
drh75897232000-05-29 14:26:00 +0000953}
954
955/*
drh382c0242001-10-06 16:33:02 +0000956** This routine is called by the parser while in the middle of
957** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
958** been seen on a column. This routine sets the notNull flag on
959** the column currently under construction.
960*/
danielk19774adee202004-05-08 08:23:19 +0000961void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000962 Table *p;
drhc4a64fa2009-05-11 20:53:28 +0000963 p = pParse->pNewTable;
964 if( p==0 || NEVER(p->nCol<1) ) return;
965 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000966}
967
968/*
danielk197752a83fb2005-01-31 12:56:44 +0000969** Scan the column type name zType (length nType) and return the
970** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000971**
972** This routine does a case-independent search of zType for the
973** substrings in the following table. If one of the substrings is
974** found, the corresponding affinity is returned. If zType contains
975** more than one of the substrings, entries toward the top of
976** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000977** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000978**
979** Substring | Affinity
980** --------------------------------
981** 'INT' | SQLITE_AFF_INTEGER
982** 'CHAR' | SQLITE_AFF_TEXT
983** 'CLOB' | SQLITE_AFF_TEXT
984** 'TEXT' | SQLITE_AFF_TEXT
985** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000986** 'REAL' | SQLITE_AFF_REAL
987** 'FLOA' | SQLITE_AFF_REAL
988** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +0000989**
990** If none of the substrings in the above table are found,
991** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000992*/
drhb7916a72009-05-27 10:31:29 +0000993char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +0000994 u32 h = 0;
995 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +0000996
drhb7916a72009-05-27 10:31:29 +0000997 if( zIn ) while( zIn[0] ){
998 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +0000999 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001000 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1001 aff = SQLITE_AFF_TEXT;
1002 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1003 aff = SQLITE_AFF_TEXT;
1004 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1005 aff = SQLITE_AFF_TEXT;
1006 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001007 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001008 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001009#ifndef SQLITE_OMIT_FLOATING_POINT
1010 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1011 && aff==SQLITE_AFF_NUMERIC ){
1012 aff = SQLITE_AFF_REAL;
1013 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1014 && aff==SQLITE_AFF_NUMERIC ){
1015 aff = SQLITE_AFF_REAL;
1016 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1017 && aff==SQLITE_AFF_NUMERIC ){
1018 aff = SQLITE_AFF_REAL;
1019#endif
danielk1977201f7162005-02-01 02:13:29 +00001020 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001021 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001022 break;
danielk197752a83fb2005-01-31 12:56:44 +00001023 }
1024 }
danielk1977b3dff962005-02-01 01:21:55 +00001025
1026 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001027}
1028
1029/*
drh382c0242001-10-06 16:33:02 +00001030** This routine is called by the parser while in the middle of
1031** parsing a CREATE TABLE statement. The pFirst token is the first
1032** token in the sequence of tokens that describe the type of the
1033** column currently under construction. pLast is the last token
1034** in the sequence. Use this information to construct a string
1035** that contains the typename of the column and store that string
1036** in zType.
1037*/
drh487e2622005-06-25 18:42:14 +00001038void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001039 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001040 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001041
drhc4a64fa2009-05-11 20:53:28 +00001042 p = pParse->pNewTable;
1043 if( p==0 || NEVER(p->nCol<1) ) return;
1044 pCol = &p->aCol[p->nCol-1];
1045 assert( pCol->zType==0 );
1046 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001047 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001048}
1049
1050/*
danielk19777977a172004-11-09 12:44:37 +00001051** The expression is the default value for the most recently added column
1052** of the table currently under construction.
1053**
1054** Default value expressions must be constant. Raise an exception if this
1055** is not the case.
drhd9b02572001-04-15 00:37:09 +00001056**
1057** This routine is called by the parser while in the middle of
1058** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001059*/
drhb7916a72009-05-27 10:31:29 +00001060void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001061 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001062 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001063 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001064 p = pParse->pNewTable;
1065 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001066 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001067 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001068 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1069 pCol->zName);
1070 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001071 /* A copy of pExpr is used instead of the original, as pExpr contains
1072 ** tokens that point to volatile memory. The 'span' of the expression
1073 ** is required by pragma table_info.
1074 */
drh633e6d52008-07-28 19:34:53 +00001075 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001076 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1077 sqlite3DbFree(db, pCol->zDflt);
1078 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001079 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001080 }
danielk19777977a172004-11-09 12:44:37 +00001081 }
drhb7916a72009-05-27 10:31:29 +00001082 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001083}
1084
1085/*
drh4a324312001-12-21 14:30:42 +00001086** Designate the PRIMARY KEY for the table. pList is a list of names
1087** of columns that form the primary key. If pList is NULL, then the
1088** most recently added column of the table is the primary key.
1089**
1090** A table can have at most one primary key. If the table already has
1091** a primary key (and this is the second primary key) then create an
1092** error.
1093**
1094** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001095** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001096** field of the table under construction to be the index of the
1097** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1098** no INTEGER PRIMARY KEY.
1099**
1100** If the key is not an INTEGER PRIMARY KEY, then create a unique
1101** index for the key. No index is created for INTEGER PRIMARY KEYs.
1102*/
drh205f48e2004-11-05 00:43:11 +00001103void sqlite3AddPrimaryKey(
1104 Parse *pParse, /* Parsing context */
1105 ExprList *pList, /* List of field names to be indexed */
1106 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001107 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1108 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001109){
drh4a324312001-12-21 14:30:42 +00001110 Table *pTab = pParse->pNewTable;
1111 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001112 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001113 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001114 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001115 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001116 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001117 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001118 }
drh7d10d5a2008-08-20 16:35:10 +00001119 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001120 if( pList==0 ){
1121 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001122 pTab->aCol[iCol].isPrimKey = 1;
1123 }else{
danielk19770202b292004-06-09 09:55:16 +00001124 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001125 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001126 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1127 break;
1128 }
drh78100cc2003-08-23 22:40:53 +00001129 }
drh6e4fc2c2005-09-15 21:24:51 +00001130 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001131 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001132 }
drh4a324312001-12-21 14:30:42 +00001133 }
danielk19770202b292004-06-09 09:55:16 +00001134 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001135 }
1136 if( iCol>=0 && iCol<pTab->nCol ){
1137 zType = pTab->aCol[iCol].zType;
1138 }
drhfdd6e852005-12-16 01:06:16 +00001139 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1140 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001141 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001142 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001143 assert( autoInc==0 || autoInc==1 );
1144 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001145 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001146#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001147 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1148 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001149#endif
drh4a324312001-12-21 14:30:42 +00001150 }else{
dan1da40a32009-09-19 17:00:31 +00001151 Index *p;
1152 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1153 if( p ){
1154 p->autoIndex = 2;
1155 }
drhe0194f22003-02-26 13:52:51 +00001156 pList = 0;
drh4a324312001-12-21 14:30:42 +00001157 }
drhe0194f22003-02-26 13:52:51 +00001158
1159primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001160 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001161 return;
drh4a324312001-12-21 14:30:42 +00001162}
1163
1164/*
drhffe07b22005-11-03 00:41:17 +00001165** Add a new CHECK constraint to the table currently under construction.
1166*/
1167void sqlite3AddCheckConstraint(
1168 Parse *pParse, /* Parsing context */
1169 Expr *pCheckExpr /* The check expression */
1170){
drh633e6d52008-07-28 19:34:53 +00001171 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001172#ifndef SQLITE_OMIT_CHECK
1173 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001174 if( pTab && !IN_DECLARE_VTAB ){
drh33e619f2009-05-28 01:00:55 +00001175 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1176 }else
drhffe07b22005-11-03 00:41:17 +00001177#endif
drh33e619f2009-05-28 01:00:55 +00001178 {
1179 sqlite3ExprDelete(db, pCheckExpr);
1180 }
drhffe07b22005-11-03 00:41:17 +00001181}
1182
1183/*
drhd3d39e92004-05-20 22:16:29 +00001184** Set the collation function of the most recently parsed table column
1185** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001186*/
danielk197739002502007-11-12 09:50:26 +00001187void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001188 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001189 int i;
danielk197739002502007-11-12 09:50:26 +00001190 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001191 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001192
danielk1977b8cbb872006-06-19 05:33:45 +00001193 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001194 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001195 db = pParse->db;
1196 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001197 if( !zColl ) return;
1198
drhc4a64fa2009-05-11 20:53:28 +00001199 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001200 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001201 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001202
1203 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1204 ** then an index may have been created on this column before the
1205 ** collation type was added. Correct this if it is the case.
1206 */
1207 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1208 assert( pIdx->nColumn==1 );
1209 if( pIdx->aiColumn[0]==i ){
1210 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001211 }
1212 }
danielk197739002502007-11-12 09:50:26 +00001213 }else{
drh633e6d52008-07-28 19:34:53 +00001214 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001215 }
danielk19777cedc8d2004-06-10 10:50:08 +00001216}
1217
danielk1977466be562004-06-10 02:16:01 +00001218/*
1219** This function returns the collation sequence for database native text
1220** encoding identified by the string zName, length nName.
1221**
1222** If the requested collation sequence is not available, or not available
1223** in the database native encoding, the collation factory is invoked to
1224** request it. If the collation factory does not supply such a sequence,
1225** and the sequence is available in another text encoding, then that is
1226** returned instead.
1227**
1228** If no versions of the requested collations sequence are available, or
1229** another error occurs, NULL is returned and an error message written into
1230** pParse.
drha34001c2007-02-02 12:44:37 +00001231**
1232** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1233** invokes the collation factory if the named collation cannot be found
1234** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001235**
1236** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001237*/
drhc4a64fa2009-05-11 20:53:28 +00001238CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001239 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001240 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001241 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001242 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001243
drhc4a64fa2009-05-11 20:53:28 +00001244 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001245 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh9aeda792009-08-20 02:34:15 +00001246 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
danielk19774dade032005-05-25 10:45:10 +00001247 if( !pColl ){
drhc4a64fa2009-05-11 20:53:28 +00001248 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
danielk1977466be562004-06-10 02:16:01 +00001249 }
1250 }
1251
danielk19770202b292004-06-09 09:55:16 +00001252 return pColl;
1253}
1254
1255
drh8e2ca022002-06-17 17:07:19 +00001256/*
drh3f7d4e42004-07-24 14:35:58 +00001257** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001258**
1259** The schema cookie is used to determine when the schema for the
1260** database changes. After each schema change, the cookie value
1261** changes. When a process first reads the schema it records the
1262** cookie. Thereafter, whenever it goes to access the database,
1263** it checks the cookie to make sure the schema has not changed
1264** since it was last read.
1265**
1266** This plan is not completely bullet-proof. It is possible for
1267** the schema to change multiple times and for the cookie to be
1268** set back to prior value. But schema changes are infrequent
1269** and the probability of hitting the same cookie value is only
1270** 1 chance in 2^32. So we're safe enough.
1271*/
drh9cbf3422008-01-17 16:22:13 +00001272void sqlite3ChangeCookie(Parse *pParse, int iDb){
1273 int r1 = sqlite3GetTempReg(pParse);
1274 sqlite3 *db = pParse->db;
1275 Vdbe *v = pParse->pVdbe;
1276 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001277 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001278 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001279}
1280
1281/*
drh969fa7c2002-02-18 18:30:32 +00001282** Measure the number of characters needed to output the given
1283** identifier. The number returned includes any quotes used
1284** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001285**
1286** The estimate is conservative. It might be larger that what is
1287** really needed.
drh969fa7c2002-02-18 18:30:32 +00001288*/
1289static int identLength(const char *z){
1290 int n;
drh17f71932002-02-21 12:01:27 +00001291 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001292 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001293 }
drh234c39d2004-07-24 03:30:47 +00001294 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001295}
1296
1297/*
danielk19771b870de2009-03-14 08:37:23 +00001298** The first parameter is a pointer to an output buffer. The second
1299** parameter is a pointer to an integer that contains the offset at
1300** which to write into the output buffer. This function copies the
1301** nul-terminated string pointed to by the third parameter, zSignedIdent,
1302** to the specified offset in the buffer and updates *pIdx to refer
1303** to the first byte after the last byte written before returning.
1304**
1305** If the string zSignedIdent consists entirely of alpha-numeric
1306** characters, does not begin with a digit and is not an SQL keyword,
1307** then it is copied to the output buffer exactly as it is. Otherwise,
1308** it is quoted using double-quotes.
1309*/
drhc4a64fa2009-05-11 20:53:28 +00001310static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001311 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001312 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001313 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001314
drh17f71932002-02-21 12:01:27 +00001315 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001316 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001317 }
danielk19771b870de2009-03-14 08:37:23 +00001318 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1319 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001320 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001321 }
1322
drh234c39d2004-07-24 03:30:47 +00001323 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001324 for(j=0; zIdent[j]; j++){
1325 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001326 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001327 }
drh234c39d2004-07-24 03:30:47 +00001328 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001329 z[i] = 0;
1330 *pIdx = i;
1331}
1332
1333/*
1334** Generate a CREATE TABLE statement appropriate for the given
1335** table. Memory to hold the text of the statement is obtained
1336** from sqliteMalloc() and must be freed by the calling function.
1337*/
drh1d34fde2009-02-03 15:50:33 +00001338static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001339 int i, k, n;
1340 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001341 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001342 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001343 n = 0;
drh234c39d2004-07-24 03:30:47 +00001344 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001345 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001346 }
1347 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001348 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001349 zSep = "";
1350 zSep2 = ",";
1351 zEnd = ")";
1352 }else{
1353 zSep = "\n ";
1354 zSep2 = ",\n ";
1355 zEnd = "\n)";
1356 }
drhe0bc4042002-06-25 01:09:11 +00001357 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001358 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001359 if( zStmt==0 ){
1360 db->mallocFailed = 1;
1361 return 0;
1362 }
drhbdb339f2009-02-02 18:03:21 +00001363 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001364 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001365 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001366 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001367 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001368 static const char * const azType[] = {
1369 /* SQLITE_AFF_TEXT */ " TEXT",
1370 /* SQLITE_AFF_NONE */ "",
1371 /* SQLITE_AFF_NUMERIC */ " NUM",
1372 /* SQLITE_AFF_INTEGER */ " INT",
1373 /* SQLITE_AFF_REAL */ " REAL"
1374 };
1375 int len;
1376 const char *zType;
1377
drh5bb3eb92007-05-04 13:15:55 +00001378 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001379 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001380 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001381 identPut(zStmt, &k, pCol->zName);
1382 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1383 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
1384 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1385 testcase( pCol->affinity==SQLITE_AFF_NONE );
1386 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1387 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1388 testcase( pCol->affinity==SQLITE_AFF_REAL );
1389
1390 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1391 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001392 assert( pCol->affinity==SQLITE_AFF_NONE
1393 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001394 memcpy(&zStmt[k], zType, len);
1395 k += len;
1396 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001397 }
drh5bb3eb92007-05-04 13:15:55 +00001398 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001399 return zStmt;
1400}
1401
1402/*
drh75897232000-05-29 14:26:00 +00001403** This routine is called to report the final ")" that terminates
1404** a CREATE TABLE statement.
1405**
drhf57b3392001-10-08 13:22:32 +00001406** The table structure that other action routines have been building
1407** is added to the internal hash tables, assuming no errors have
1408** occurred.
drh75897232000-05-29 14:26:00 +00001409**
drh1d85d932004-02-14 23:05:52 +00001410** An entry for the table is made in the master table on disk, unless
1411** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001412** it means we are reading the sqlite_master table because we just
1413** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001414** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001415** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001416**
1417** If the pSelect argument is not NULL, it means that this routine
1418** was called to create a table generated from a
1419** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1420** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001421*/
danielk197719a8e7e2005-03-17 05:03:38 +00001422void sqlite3EndTable(
1423 Parse *pParse, /* Parse context */
1424 Token *pCons, /* The ',' token after the last column defn. */
1425 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1426 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1427){
drh75897232000-05-29 14:26:00 +00001428 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001429 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001430 int iDb;
drh75897232000-05-29 14:26:00 +00001431
drh8af73d42009-05-13 22:58:28 +00001432 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001433 return;
1434 }
drh28037572000-08-02 13:47:41 +00001435 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001436 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001437
danielk1977517eb642004-06-07 10:00:31 +00001438 assert( !db->init.busy || !pSelect );
1439
drhb9bb7c12006-06-11 23:41:55 +00001440 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001441
drhffe07b22005-11-03 00:41:17 +00001442#ifndef SQLITE_OMIT_CHECK
1443 /* Resolve names in all CHECK constraint expressions.
1444 */
1445 if( p->pCheck ){
1446 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1447 NameContext sNC; /* Name context for pParse->pNewTable */
1448
1449 memset(&sNC, 0, sizeof(sNC));
1450 memset(&sSrc, 0, sizeof(sSrc));
1451 sSrc.nSrc = 1;
1452 sSrc.a[0].zName = p->zName;
1453 sSrc.a[0].pTab = p;
1454 sSrc.a[0].iCursor = -1;
1455 sNC.pParse = pParse;
1456 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001457 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001458 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001459 return;
1460 }
1461 }
1462#endif /* !defined(SQLITE_OMIT_CHECK) */
1463
drh1d85d932004-02-14 23:05:52 +00001464 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001465 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1466 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001467 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001468 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001469 */
drh1d85d932004-02-14 23:05:52 +00001470 if( db->init.busy ){
1471 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001472 }
1473
drhe3c41372001-09-17 20:25:58 +00001474 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001475 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001476 **
drhe0bc4042002-06-25 01:09:11 +00001477 ** If this is a TEMPORARY table, write the entry into the auxiliary
1478 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001479 */
drh1d85d932004-02-14 23:05:52 +00001480 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001481 int n;
drhd8bc7082000-06-07 23:51:50 +00001482 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001483 char *zType; /* "view" or "table" */
1484 char *zType2; /* "VIEW" or "TABLE" */
1485 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001486
danielk19774adee202004-05-08 08:23:19 +00001487 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001488 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001489
drh66a51672008-01-03 00:01:23 +00001490 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001491
drh0fa991b2009-03-21 16:19:26 +00001492 /*
1493 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001494 */
drh4ff6dfa2002-03-03 23:06:00 +00001495 if( p->pSelect==0 ){
1496 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001497 zType = "table";
1498 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001499#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001500 }else{
1501 /* A view */
drh4794f732004-11-05 17:17:50 +00001502 zType = "view";
1503 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001504#endif
drh4ff6dfa2002-03-03 23:06:00 +00001505 }
danielk1977517eb642004-06-07 10:00:31 +00001506
danielk1977517eb642004-06-07 10:00:31 +00001507 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1508 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001509 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001510 **
1511 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1512 ** suitable state to query for the column names and types to be used
1513 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001514 **
1515 ** A shared-cache write-lock is not required to write to the new table,
1516 ** as a schema-lock must have already been obtained to create it. Since
1517 ** a schema-lock excludes all other database users, the write-lock would
1518 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001519 */
1520 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001521 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001522 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001523
danielk19776ab3a2e2009-02-19 14:39:25 +00001524 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001525 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001526 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001527 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001528 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001529 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001530 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001531 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001532 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001533 if( pSelTab==0 ) return;
1534 assert( p->aCol==0 );
1535 p->nCol = pSelTab->nCol;
1536 p->aCol = pSelTab->aCol;
1537 pSelTab->nCol = 0;
1538 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001539 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001540 }
1541 }
drh4794f732004-11-05 17:17:50 +00001542
drh4794f732004-11-05 17:17:50 +00001543 /* Compute the complete text of the CREATE statement */
1544 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001545 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001546 }else{
drh1bd10f82008-12-10 21:19:56 +00001547 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001548 zStmt = sqlite3MPrintf(db,
1549 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1550 );
drh4794f732004-11-05 17:17:50 +00001551 }
1552
1553 /* A slot for the record has already been allocated in the
1554 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001555 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001556 */
1557 sqlite3NestedParse(pParse,
1558 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001559 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1560 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001561 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001562 zType,
1563 p->zName,
1564 p->zName,
drhb7654112008-01-12 12:48:07 +00001565 pParse->regRoot,
1566 zStmt,
1567 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001568 );
drh633e6d52008-07-28 19:34:53 +00001569 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001570 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001571
1572#ifndef SQLITE_OMIT_AUTOINCREMENT
1573 /* Check to see if we need to create an sqlite_sequence table for
1574 ** keeping track of autoincrement keys.
1575 */
drh7d10d5a2008-08-20 16:35:10 +00001576 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001577 Db *pDb = &db->aDb[iDb];
1578 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001579 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001580 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1581 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001582 );
1583 }
1584 }
1585#endif
drh4794f732004-11-05 17:17:50 +00001586
1587 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001588 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1589 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001590 }
drh17e9e292003-02-01 13:53:28 +00001591
drh2958a4e2004-11-12 03:56:15 +00001592
drh17e9e292003-02-01 13:53:28 +00001593 /* Add the table to the in-memory representation of the database.
1594 */
drh8af73d42009-05-13 22:58:28 +00001595 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001596 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001597 Schema *pSchema = p->pSchema;
drhea678832008-12-10 19:26:22 +00001598 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001599 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001600 if( pOld ){
1601 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001602 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001603 return;
1604 }
drh17e9e292003-02-01 13:53:28 +00001605 pParse->pNewTable = 0;
1606 db->nTable++;
1607 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001608
1609#ifndef SQLITE_OMIT_ALTERTABLE
1610 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001611 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001612 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001613 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001614 if( pCons->z==0 ){
1615 pCons = pEnd;
1616 }
drh1bd10f82008-12-10 21:19:56 +00001617 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001618 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001619 }
1620#endif
drh17e9e292003-02-01 13:53:28 +00001621 }
drh75897232000-05-29 14:26:00 +00001622}
1623
drhb7f91642004-10-31 02:22:47 +00001624#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001625/*
drha76b5df2002-02-23 02:32:10 +00001626** The parser calls this routine in order to create a new VIEW
1627*/
danielk19774adee202004-05-08 08:23:19 +00001628void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001629 Parse *pParse, /* The parsing context */
1630 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001631 Token *pName1, /* The token that holds the name of the view */
1632 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001633 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001634 int isTemp, /* TRUE for a TEMPORARY view */
1635 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001636){
drha76b5df2002-02-23 02:32:10 +00001637 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001638 int n;
drhb7916a72009-05-27 10:31:29 +00001639 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001640 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001641 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001642 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001643 int iDb;
drh17435752007-08-16 04:30:38 +00001644 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001645
drh7c3d64f2005-06-06 15:32:08 +00001646 if( pParse->nVar>0 ){
1647 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001648 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001649 return;
1650 }
drhfdd48a72006-09-11 23:45:48 +00001651 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001652 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001653 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001654 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001655 return;
1656 }
danielk1977ef2cb632004-05-29 02:37:19 +00001657 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001658 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001659 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001660 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001661 ){
drh633e6d52008-07-28 19:34:53 +00001662 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001663 return;
1664 }
drh174b6192002-12-03 02:22:52 +00001665
drh4b59ab52002-08-24 18:24:51 +00001666 /* Make a copy of the entire SELECT statement that defines the view.
1667 ** This will force all the Expr.token.z values to be dynamically
1668 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001669 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001670 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001671 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001672 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001673 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001674 return;
1675 }
drh17435752007-08-16 04:30:38 +00001676 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001677 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001678 }
drh4b59ab52002-08-24 18:24:51 +00001679
1680 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1681 ** the end.
1682 */
drha76b5df2002-02-23 02:32:10 +00001683 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001684 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001685 sEnd.z += sEnd.n;
1686 }
1687 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001688 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001689 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001690 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001691 sEnd.z = &z[n-1];
1692 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001693
danielk19774adee202004-05-08 08:23:19 +00001694 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001695 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001696 return;
drh417be792002-03-03 18:59:40 +00001697}
drhb7f91642004-10-31 02:22:47 +00001698#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001699
danielk1977fe3fcbe22006-06-12 12:08:45 +00001700#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001701/*
1702** The Table structure pTable is really a VIEW. Fill in the names of
1703** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001704** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001705*/
danielk19774adee202004-05-08 08:23:19 +00001706int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001707 Table *pSelTab; /* A fake table from which we get the result set */
1708 Select *pSel; /* Copy of the SELECT that implements the view */
1709 int nErr = 0; /* Number of errors encountered */
1710 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001711 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001712 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001713
1714 assert( pTable );
1715
danielk1977fe3fcbe22006-06-12 12:08:45 +00001716#ifndef SQLITE_OMIT_VIRTUALTABLE
1717 if( sqlite3VtabCallConnect(pParse, pTable) ){
1718 return SQLITE_ERROR;
1719 }
drh4cbdda92006-06-14 19:00:20 +00001720 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001721#endif
1722
1723#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001724 /* A positive nCol means the columns names for this view are
1725 ** already known.
1726 */
1727 if( pTable->nCol>0 ) return 0;
1728
1729 /* A negative nCol is a special marker meaning that we are currently
1730 ** trying to compute the column names. If we enter this routine with
1731 ** a negative nCol, it means two or more views form a loop, like this:
1732 **
1733 ** CREATE VIEW one AS SELECT * FROM two;
1734 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001735 **
drh768578e2009-05-12 00:40:12 +00001736 ** Actually, the error above is now caught prior to reaching this point.
1737 ** But the following test is still important as it does come up
1738 ** in the following:
1739 **
1740 ** CREATE TABLE main.ex1(a);
1741 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1742 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001743 */
1744 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001745 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001746 return 1;
1747 }
drh85c23c62005-08-20 03:03:04 +00001748 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001749
1750 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001751 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1752 ** "*" elements in the results set of the view and will assign cursors
1753 ** to the elements of the FROM clause. But we do not want these changes
1754 ** to be permanent. So the computation is done on a copy of the SELECT
1755 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001756 */
drh9b3187e2005-01-18 14:45:47 +00001757 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001758 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001759 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001760 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001761 n = pParse->nTab;
1762 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1763 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001764 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001765#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001766 xAuth = db->xAuth;
1767 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001768 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001769 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001770#else
drh7d10d5a2008-08-20 16:35:10 +00001771 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001772#endif
drhd9da78a2009-03-24 15:08:09 +00001773 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001774 pParse->nTab = n;
1775 if( pSelTab ){
1776 assert( pTable->aCol==0 );
1777 pTable->nCol = pSelTab->nCol;
1778 pTable->aCol = pSelTab->aCol;
1779 pSelTab->nCol = 0;
1780 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001781 sqlite3DeleteTable(db, pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001782 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001783 }else{
1784 pTable->nCol = 0;
1785 nErr++;
1786 }
drh633e6d52008-07-28 19:34:53 +00001787 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001788 } else {
drh417be792002-03-03 18:59:40 +00001789 nErr++;
1790 }
drhb7f91642004-10-31 02:22:47 +00001791#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001792 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001793}
1794#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001795
drhb7f91642004-10-31 02:22:47 +00001796#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001797/*
drh8bf8dc92003-05-17 17:35:10 +00001798** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001799*/
drh9bb575f2004-09-06 17:24:11 +00001800static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001801 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001802 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001803 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001804 Table *pTab = sqliteHashData(i);
1805 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00001806 sqliteDeleteColumnNames(db, pTab);
1807 pTab->aCol = 0;
1808 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00001809 }
1810 }
drh8bf8dc92003-05-17 17:35:10 +00001811 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001812}
drhb7f91642004-10-31 02:22:47 +00001813#else
1814# define sqliteViewResetAll(A,B)
1815#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001816
drh75897232000-05-29 14:26:00 +00001817/*
danielk1977a0bf2652004-11-04 14:30:04 +00001818** This function is called by the VDBE to adjust the internal schema
1819** used by SQLite when the btree layer moves a table root page. The
1820** root-page of a table or index in database iDb has changed from iFrom
1821** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001822**
1823** Ticket #1728: The symbol table might still contain information
1824** on tables and/or indices that are the process of being deleted.
1825** If you are unlucky, one of those deleted indices or tables might
1826** have the same rootpage number as the real table or index that is
1827** being moved. So we cannot stop searching after the first match
1828** because the first match might be for one of the deleted indices
1829** or tables and not the table/index that is actually being moved.
1830** We must continue looping until all tables and indices with
1831** rootpage==iFrom have been converted to have a rootpage of iTo
1832** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001833*/
1834#ifndef SQLITE_OMIT_AUTOVACUUM
1835void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1836 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001837 Hash *pHash;
1838
1839 pHash = &pDb->pSchema->tblHash;
1840 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001841 Table *pTab = sqliteHashData(pElem);
1842 if( pTab->tnum==iFrom ){
1843 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001844 }
1845 }
danielk1977da184232006-01-05 11:34:32 +00001846 pHash = &pDb->pSchema->idxHash;
1847 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001848 Index *pIdx = sqliteHashData(pElem);
1849 if( pIdx->tnum==iFrom ){
1850 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001851 }
1852 }
danielk1977a0bf2652004-11-04 14:30:04 +00001853}
1854#endif
1855
1856/*
1857** Write code to erase the table with root-page iTable from database iDb.
1858** Also write code to modify the sqlite_master table and internal schema
1859** if a root-page of another table is moved by the btree-layer whilst
1860** erasing iTable (this can happen with an auto-vacuum database).
1861*/
drh4e0cff62004-11-05 05:10:28 +00001862static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1863 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001864 int r1 = sqlite3GetTempReg(pParse);
1865 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001866 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001867#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001868 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001869 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001870 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001871 ** reflect this.
1872 **
drh0fa991b2009-03-21 16:19:26 +00001873 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001874 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1875 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001876 */
danielk197763e3e9f2004-11-05 09:19:27 +00001877 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001878 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1879 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001880#endif
drhb7654112008-01-12 12:48:07 +00001881 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001882}
1883
1884/*
1885** Write VDBE code to erase table pTab and all associated indices on disk.
1886** Code to update the sqlite_master tables and internal schema definitions
1887** in case a root-page belonging to another table is moved by the btree layer
1888** is also added (this can happen with an auto-vacuum database).
1889*/
drh4e0cff62004-11-05 05:10:28 +00001890static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001891#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001892 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001893 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1894 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001895 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001896 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001897 }
1898#else
1899 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1900 ** is not defined), then it is important to call OP_Destroy on the
1901 ** table and index root-pages in order, starting with the numerically
1902 ** largest root-page number. This guarantees that none of the root-pages
1903 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1904 ** following were coded:
1905 **
1906 ** OP_Destroy 4 0
1907 ** ...
1908 ** OP_Destroy 5 0
1909 **
1910 ** and root page 5 happened to be the largest root-page number in the
1911 ** database, then root page 5 would be moved to page 4 by the
1912 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1913 ** a free-list page.
1914 */
1915 int iTab = pTab->tnum;
1916 int iDestroyed = 0;
1917
1918 while( 1 ){
1919 Index *pIdx;
1920 int iLargest = 0;
1921
1922 if( iDestroyed==0 || iTab<iDestroyed ){
1923 iLargest = iTab;
1924 }
1925 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1926 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001927 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001928 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1929 iLargest = iIdx;
1930 }
1931 }
danielk1977da184232006-01-05 11:34:32 +00001932 if( iLargest==0 ){
1933 return;
1934 }else{
1935 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1936 destroyRootPage(pParse, iLargest, iDb);
1937 iDestroyed = iLargest;
1938 }
danielk1977a0bf2652004-11-04 14:30:04 +00001939 }
1940#endif
1941}
1942
1943/*
drh75897232000-05-29 14:26:00 +00001944** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001945** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001946*/
drha0733842005-12-29 01:11:36 +00001947void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001948 Table *pTab;
drh75897232000-05-29 14:26:00 +00001949 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001950 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001951 int iDb;
drh75897232000-05-29 14:26:00 +00001952
drh8af73d42009-05-13 22:58:28 +00001953 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001954 goto exit_drop_table;
1955 }
drh8af73d42009-05-13 22:58:28 +00001956 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00001957 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00001958 if( noErr ) db->suppressErr++;
drhca424112008-01-25 15:04:48 +00001959 pTab = sqlite3LocateTable(pParse, isView,
1960 pName->a[0].zName, pName->a[0].zDatabase);
drha7564662010-02-22 19:32:31 +00001961 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00001962
drha0733842005-12-29 01:11:36 +00001963 if( pTab==0 ){
drha0733842005-12-29 01:11:36 +00001964 goto exit_drop_table;
1965 }
danielk1977da184232006-01-05 11:34:32 +00001966 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001967 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00001968
1969 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1970 ** it is initialized.
1971 */
1972 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1973 goto exit_drop_table;
1974 }
drhe5f9c642003-01-13 23:27:31 +00001975#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001976 {
1977 int code;
danielk1977da184232006-01-05 11:34:32 +00001978 const char *zTab = SCHEMA_TABLE(iDb);
1979 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00001980 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00001981 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001982 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001983 }
drhe5f9c642003-01-13 23:27:31 +00001984 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001985 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001986 code = SQLITE_DROP_TEMP_VIEW;
1987 }else{
1988 code = SQLITE_DROP_VIEW;
1989 }
danielk19774b2688a2006-06-20 11:01:07 +00001990#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00001991 }else if( IsVirtual(pTab) ){
1992 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00001993 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00001994#endif
drhe5f9c642003-01-13 23:27:31 +00001995 }else{
danielk197753c0f742005-03-29 03:10:59 +00001996 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001997 code = SQLITE_DROP_TEMP_TABLE;
1998 }else{
1999 code = SQLITE_DROP_TABLE;
2000 }
2001 }
danielk1977f1a381e2006-06-16 08:01:02 +00002002 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002003 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002004 }
danielk1977a8858102004-05-28 12:11:21 +00002005 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2006 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002007 }
drhe5f9c642003-01-13 23:27:31 +00002008 }
2009#endif
drhc456e572008-08-11 18:44:58 +00002010 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002011 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002012 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002013 }
danielk1977576ec6b2005-01-21 11:55:25 +00002014
2015#ifndef SQLITE_OMIT_VIEW
2016 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2017 ** on a table.
2018 */
danielk1977a8858102004-05-28 12:11:21 +00002019 if( isView && pTab->pSelect==0 ){
2020 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2021 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002022 }
danielk1977a8858102004-05-28 12:11:21 +00002023 if( !isView && pTab->pSelect ){
2024 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2025 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002026 }
danielk1977576ec6b2005-01-21 11:55:25 +00002027#endif
drh75897232000-05-29 14:26:00 +00002028
drh1ccde152000-06-17 13:12:39 +00002029 /* Generate code to remove the table from the master table
2030 ** on disk.
2031 */
danielk19774adee202004-05-08 08:23:19 +00002032 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002033 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002034 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002035 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002036 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002037
danielk197720b1eaf2006-07-26 16:22:14 +00002038#ifndef SQLITE_OMIT_VIRTUALTABLE
2039 if( IsVirtual(pTab) ){
drh768578e2009-05-12 00:40:12 +00002040 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002041 }
2042#endif
dand66c8302009-09-28 14:49:01 +00002043 sqlite3FkDropTable(pParse, pName, pTab);
danielk197720b1eaf2006-07-26 16:22:14 +00002044
danielk19778e227872004-06-07 07:52:17 +00002045 /* Drop all triggers associated with the table being dropped. Code
2046 ** is generated to remove entries from sqlite_master and/or
2047 ** sqlite_temp_master if required.
2048 */
danielk19772f886d12009-02-28 10:47:41 +00002049 pTrigger = sqlite3TriggerList(pParse, pTab);
drhe0bc4042002-06-25 01:09:11 +00002050 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002051 assert( pTrigger->pSchema==pTab->pSchema ||
2052 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002053 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002054 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002055 }
drh8bf8dc92003-05-17 17:35:10 +00002056
danielk19774d36b812004-11-19 07:07:30 +00002057#ifndef SQLITE_OMIT_AUTOINCREMENT
2058 /* Remove any entries of the sqlite_sequence table associated with
2059 ** the table being dropped. This is done before the table is dropped
2060 ** at the btree level, in case the sqlite_sequence table needs to
2061 ** move as a result of the drop (can happen in auto-vacuum mode).
2062 */
drh7d10d5a2008-08-20 16:35:10 +00002063 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002064 sqlite3NestedParse(pParse,
2065 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2066 pDb->zName, pTab->zName
2067 );
2068 }
2069#endif
2070
danielk19778e227872004-06-07 07:52:17 +00002071 /* Drop all SQLITE_MASTER table and index entries that refer to the
2072 ** table. The program name loops through the master table and deletes
2073 ** every row that refers to a table of the same name as the one being
2074 ** dropped. Triggers are handled seperately because a trigger can be
2075 ** created in the temp database that refers to a table in another
2076 ** database.
2077 */
drhf1974842004-11-05 03:56:00 +00002078 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002079 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002080 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002081
2082 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2083 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2084 sqlite3NestedParse(pParse,
2085 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2086 );
2087 }
2088
danielk19774b2688a2006-06-20 11:01:07 +00002089 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002090 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002091 }
drh2958a4e2004-11-12 03:56:15 +00002092
danielk1977a21c6b62005-01-24 10:25:59 +00002093 /* Remove the table entry from SQLite's internal schema and modify
2094 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002095 */
drh4cbdda92006-06-14 19:00:20 +00002096 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002097 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002098 }
drh66a51672008-01-03 00:01:23 +00002099 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002100 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002101 }
drhd24cc422003-03-27 12:51:24 +00002102 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002103
2104exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002105 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002106}
2107
2108/*
drhc2eef3b2002-08-31 18:53:06 +00002109** This routine is called to create a new foreign key on the table
2110** currently under construction. pFromCol determines which columns
2111** in the current table point to the foreign key. If pFromCol==0 then
2112** connect the key to the last column inserted. pTo is the name of
2113** the table referred to. pToCol is a list of tables in the other
2114** pTo table that the foreign key points to. flags contains all
2115** information about the conflict resolution algorithms specified
2116** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2117**
2118** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002119** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002120**
2121** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002122** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002123*/
danielk19774adee202004-05-08 08:23:19 +00002124void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002125 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002126 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002127 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002128 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002129 int flags /* Conflict resolution algorithms. */
2130){
danielk197718576932008-08-06 13:47:40 +00002131 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002132#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002133 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002134 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002135 Table *p = pParse->pNewTable;
2136 int nByte;
2137 int i;
2138 int nCol;
2139 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002140
2141 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002142 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002143 if( pFromCol==0 ){
2144 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002145 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002146 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002147 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002148 " should reference only one column of table %T",
2149 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002150 goto fk_end;
2151 }
2152 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002153 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002154 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002155 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002156 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002157 goto fk_end;
2158 }else{
danielk19770202b292004-06-09 09:55:16 +00002159 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002160 }
drhe61922a2009-05-02 13:29:37 +00002161 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002162 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002163 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002164 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002165 }
2166 }
drh633e6d52008-07-28 19:34:53 +00002167 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002168 if( pFKey==0 ){
2169 goto fk_end;
2170 }
drhc2eef3b2002-08-31 18:53:06 +00002171 pFKey->pFrom = p;
2172 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002173 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002174 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002175 memcpy(z, pTo->z, pTo->n);
2176 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002177 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002178 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002179 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002180 if( pFromCol==0 ){
2181 pFKey->aCol[0].iFrom = p->nCol-1;
2182 }else{
2183 for(i=0; i<nCol; i++){
2184 int j;
2185 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002186 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002187 pFKey->aCol[i].iFrom = j;
2188 break;
2189 }
2190 }
2191 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002192 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002193 "unknown column \"%s\" in foreign key definition",
2194 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002195 goto fk_end;
2196 }
2197 }
2198 }
2199 if( pToCol ){
2200 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002201 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002202 pFKey->aCol[i].zCol = z;
2203 memcpy(z, pToCol->a[i].zName, n);
2204 z[n] = 0;
2205 z += n+1;
2206 }
2207 }
2208 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002209 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2210 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002211
dan1da40a32009-09-19 17:00:31 +00002212 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2213 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2214 );
danf59c5ca2009-09-22 16:55:38 +00002215 if( pNextTo==pFKey ){
2216 db->mallocFailed = 1;
2217 goto fk_end;
2218 }
dan1da40a32009-09-19 17:00:31 +00002219 if( pNextTo ){
2220 assert( pNextTo->pPrevTo==0 );
2221 pFKey->pNextTo = pNextTo;
2222 pNextTo->pPrevTo = pFKey;
2223 }
2224
drhc2eef3b2002-08-31 18:53:06 +00002225 /* Link the foreign key to the table as the last step.
2226 */
2227 p->pFKey = pFKey;
2228 pFKey = 0;
2229
2230fk_end:
drh633e6d52008-07-28 19:34:53 +00002231 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002232#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002233 sqlite3ExprListDelete(db, pFromCol);
2234 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002235}
2236
2237/*
2238** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2239** clause is seen as part of a foreign key definition. The isDeferred
2240** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2241** The behavior of the most recently created foreign key is adjusted
2242** accordingly.
2243*/
danielk19774adee202004-05-08 08:23:19 +00002244void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002245#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002246 Table *pTab;
2247 FKey *pFKey;
2248 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002249 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002250 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002251#endif
drhc2eef3b2002-08-31 18:53:06 +00002252}
2253
2254/*
drh063336a2004-11-05 20:58:39 +00002255** Generate code that will erase and refill index *pIdx. This is
2256** used to initialize a newly created index or to recompute the
2257** content of an index in response to a REINDEX command.
2258**
2259** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002260** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002261** root page number of the index. If memRootPage is negative, then
2262** the index already exists and must be cleared before being refilled and
2263** the root page number of the index is taken from pIndex->tnum.
2264*/
2265static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2266 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002267 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2268 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drh063336a2004-11-05 20:58:39 +00002269 int addr1; /* Address of top of loop */
2270 int tnum; /* Root page of index */
2271 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002272 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002273 int regIdxKey; /* Registers containing the index key */
2274 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002275 sqlite3 *db = pParse->db; /* The database connection */
2276 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002277
danielk19771d54df82004-11-23 15:41:16 +00002278#ifndef SQLITE_OMIT_AUTHORIZATION
2279 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002280 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002281 return;
2282 }
2283#endif
2284
danielk1977c00da102006-01-07 13:21:04 +00002285 /* Require a write-lock on the table to perform this operation */
2286 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2287
drh063336a2004-11-05 20:58:39 +00002288 v = sqlite3GetVdbe(pParse);
2289 if( v==0 ) return;
2290 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002291 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002292 }else{
2293 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002294 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002295 }
danielk1977b3bf5562006-01-10 17:58:23 +00002296 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002297 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002298 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002299 if( memRootPage>=0 ){
2300 sqlite3VdbeChangeP5(v, 1);
2301 }
danielk1977c00da102006-01-07 13:21:04 +00002302 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002303 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002304 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002305 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002306 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002307 const int regRowid = regIdxKey + pIndex->nColumn;
2308 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2309 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002310
danielk1977de630352009-05-04 11:42:29 +00002311 /* The registers accessed by the OP_IsUnique opcode were allocated
2312 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2313 ** call above. Just before that function was freed they were released
2314 ** (made available to the compiler for reuse) using
2315 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2316 ** opcode use the values stored within seems dangerous. However, since
2317 ** we can be sure that no other temp registers have been allocated
2318 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2319 */
2320 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
dane0af83a2009-09-08 19:15:01 +00002321 sqlite3HaltConstraint(
2322 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002323 }
drh2d401ab2008-01-10 23:50:11 +00002324 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
danielk1977de630352009-05-04 11:42:29 +00002325 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002326 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002327 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002328 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002329 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2330 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002331}
2332
2333/*
drh23bf66d2004-12-14 03:34:34 +00002334** Create a new index for an SQL table. pName1.pName2 is the name of the index
2335** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002336** be NULL for a primary key or an index that is created to satisfy a
2337** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002338** as the table to be indexed. pParse->pNewTable is a table that is
2339** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002340**
drh382c0242001-10-06 16:33:02 +00002341** pList is a list of columns to be indexed. pList will be NULL if this
2342** is a primary key or unique-constraint on the most recent column added
2343** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002344**
2345** If the index is created successfully, return a pointer to the new Index
2346** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2347** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002348*/
dan1da40a32009-09-19 17:00:31 +00002349Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002350 Parse *pParse, /* All information about this parse */
2351 Token *pName1, /* First part of index name. May be NULL */
2352 Token *pName2, /* Second part of index name. May be NULL */
2353 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002354 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002355 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002356 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002357 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002358 int sortOrder, /* Sort order of primary key when pList==NULL */
2359 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002360){
dan1da40a32009-09-19 17:00:31 +00002361 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002362 Table *pTab = 0; /* Table to be indexed */
2363 Index *pIndex = 0; /* The index to be created */
2364 char *zName = 0; /* Name of the index */
2365 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002366 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002367 Token nullId; /* Fake token for an empty ID list */
2368 DbFixer sFix; /* For assigning database names to pTable */
2369 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002370 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002371 Db *pDb; /* The specific table containing the indexed database */
2372 int iDb; /* Index of the database that is being written */
2373 Token *pName = 0; /* Unqualified name of the index to create */
2374 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002375 int nCol;
2376 int nExtra = 0;
2377 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002378
drhd3001712009-05-12 17:46:53 +00002379 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
drh8af73d42009-05-13 22:58:28 +00002380 assert( pParse->nErr==0 ); /* Never called with prior errors */
2381 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002382 goto exit_create_index;
2383 }
2384 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002385 goto exit_create_index;
2386 }
drhdaffd0e2001-04-11 14:28:42 +00002387
drh75897232000-05-29 14:26:00 +00002388 /*
2389 ** Find the table that is to be indexed. Return early if not found.
2390 */
danielk1977cbb18d22004-05-28 11:37:27 +00002391 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002392
2393 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002394 ** to search for the table. 'Fix' the table name to this db
2395 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002396 */
2397 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002398 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002399 if( iDb<0 ) goto exit_create_index;
2400
danielk197753c0f742005-03-29 03:10:59 +00002401#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002402 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002403 ** is a temp table. If so, set the database to 1. Do not do this
2404 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002405 */
danielk1977fe910332007-12-02 11:46:34 +00002406 if( !db->init.busy ){
2407 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002408 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002409 iDb = 1;
2410 }
danielk1977ef2cb632004-05-29 02:37:19 +00002411 }
danielk197753c0f742005-03-29 03:10:59 +00002412#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002413
2414 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2415 sqlite3FixSrcList(&sFix, pTblName)
2416 ){
drh85c23c62005-08-20 03:03:04 +00002417 /* Because the parser constructs pTblName from a single identifier,
2418 ** sqlite3FixSrcList can never fail. */
2419 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002420 }
drhca424112008-01-25 15:04:48 +00002421 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002422 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002423 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002424 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002425 }else{
drhe3c41372001-09-17 20:25:58 +00002426 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002427 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002428 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002429 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002430 }
drhfdd6e852005-12-16 01:06:16 +00002431 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002432
drhd3001712009-05-12 17:46:53 +00002433 assert( pTab!=0 );
2434 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002435 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2436 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002437 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002438 goto exit_create_index;
2439 }
danielk1977576ec6b2005-01-21 11:55:25 +00002440#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002441 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002442 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002443 goto exit_create_index;
2444 }
danielk1977576ec6b2005-01-21 11:55:25 +00002445#endif
danielk19775ee9d692006-06-21 12:36:25 +00002446#ifndef SQLITE_OMIT_VIRTUALTABLE
2447 if( IsVirtual(pTab) ){
2448 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2449 goto exit_create_index;
2450 }
2451#endif
drh75897232000-05-29 14:26:00 +00002452
2453 /*
2454 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002455 ** index or table with the same name.
2456 **
2457 ** Exception: If we are reading the names of permanent indices from the
2458 ** sqlite_master table (because some other process changed the schema) and
2459 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002460 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002461 **
2462 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002463 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2464 ** own name.
drh75897232000-05-29 14:26:00 +00002465 */
danielk1977d8123362004-06-12 09:25:12 +00002466 if( pName ){
drh17435752007-08-16 04:30:38 +00002467 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002468 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002469 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002470 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002471 }
danielk1977d8123362004-06-12 09:25:12 +00002472 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002473 if( sqlite3FindTable(db, zName, 0)!=0 ){
2474 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2475 goto exit_create_index;
2476 }
2477 }
danielk197759a33f92007-03-17 10:26:59 +00002478 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2479 if( !ifNotExist ){
2480 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002481 }
danielk197759a33f92007-03-17 10:26:59 +00002482 goto exit_create_index;
2483 }
danielk1977a21c6b62005-01-24 10:25:59 +00002484 }else{
drhadbca9c2001-09-27 15:11:53 +00002485 int n;
2486 Index *pLoop;
2487 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002488 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002489 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002490 goto exit_create_index;
2491 }
drh75897232000-05-29 14:26:00 +00002492 }
2493
drhe5f9c642003-01-13 23:27:31 +00002494 /* Check for authorization to create an index.
2495 */
2496#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002497 {
drhfdd6e852005-12-16 01:06:16 +00002498 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002499 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002500 goto exit_create_index;
2501 }
2502 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002503 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002504 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002505 goto exit_create_index;
2506 }
drhe5f9c642003-01-13 23:27:31 +00002507 }
2508#endif
2509
drh75897232000-05-29 14:26:00 +00002510 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002511 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002512 ** So create a fake list to simulate this.
2513 */
2514 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002515 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002516 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002517 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002518 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002519 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002520 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002521 }
2522
danielk1977b3bf5562006-01-10 17:58:23 +00002523 /* Figure out how many bytes of space are required to store explicitly
2524 ** specified collation sequence names.
2525 */
2526 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002527 Expr *pExpr = pList->a[i].pExpr;
2528 if( pExpr ){
2529 CollSeq *pColl = pExpr->pColl;
2530 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2531 ** failure we have quit before reaching this point. */
2532 if( ALWAYS(pColl) ){
2533 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2534 }
danielk1977b3bf5562006-01-10 17:58:23 +00002535 }
2536 }
2537
drh75897232000-05-29 14:26:00 +00002538 /*
2539 ** Allocate the index structure.
2540 */
drhea678832008-12-10 19:26:22 +00002541 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002542 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002543 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002544 sizeof(Index) + /* Index structure */
2545 sizeof(int)*nCol + /* Index.aiColumn */
2546 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2547 sizeof(char *)*nCol + /* Index.azColl */
2548 sizeof(u8)*nCol + /* Index.aSortOrder */
2549 nName + 1 + /* Index.zName */
2550 nExtra /* Collation sequence names */
2551 );
drh17435752007-08-16 04:30:38 +00002552 if( db->mallocFailed ){
2553 goto exit_create_index;
2554 }
drh78aecb72006-02-10 18:08:09 +00002555 pIndex->azColl = (char**)(&pIndex[1]);
2556 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002557 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002558 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002559 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2560 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002561 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002562 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002563 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002564 pIndex->onError = (u8)onError;
2565 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002566 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002567
drhfdd6e852005-12-16 01:06:16 +00002568 /* Check to see if we should honor DESC requests on index columns
2569 */
danielk1977da184232006-01-05 11:34:32 +00002570 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002571 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002572 }else{
2573 sortOrderMask = 0; /* Ignore DESC */
2574 }
2575
drh1ccde152000-06-17 13:12:39 +00002576 /* Scan the names of the columns of the table to be indexed and
2577 ** load the column indices into the Index structure. Report an error
2578 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002579 **
2580 ** TODO: Add a test to make sure that the same column is not named
2581 ** more than once within the same index. Only the first instance of
2582 ** the column will ever be used by the optimizer. Note that using the
2583 ** same column more than once cannot be an error because that would
2584 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002585 */
drhfdd6e852005-12-16 01:06:16 +00002586 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2587 const char *zColName = pListItem->zName;
2588 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002589 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002590 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002591
drhfdd6e852005-12-16 01:06:16 +00002592 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2593 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002594 }
2595 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002596 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002597 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00002598 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00002599 goto exit_create_index;
2600 }
drh967e8b72000-06-21 13:59:10 +00002601 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002602 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2603 ** the way the "idxlist" non-terminal is constructed by the parser,
2604 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2605 ** must exist or else there must have been an OOM error. But if there
2606 ** was an OOM error, we would never reach this point. */
2607 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2608 int nColl;
2609 zColl = pListItem->pExpr->pColl->zName;
2610 nColl = sqlite3Strlen30(zColl) + 1;
2611 assert( nExtra>=nColl );
2612 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002613 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002614 zExtra += nColl;
2615 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002616 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002617 zColl = pTab->aCol[j].zColl;
2618 if( !zColl ){
2619 zColl = db->pDfltColl->zName;
2620 }
danielk19770202b292004-06-09 09:55:16 +00002621 }
drhb7f24de2009-05-13 17:35:23 +00002622 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002623 goto exit_create_index;
2624 }
danielk1977b3bf5562006-01-10 17:58:23 +00002625 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002626 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002627 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002628 }
drh51147ba2005-07-23 22:59:55 +00002629 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002630
danielk1977d8123362004-06-12 09:25:12 +00002631 if( pTab==pParse->pNewTable ){
2632 /* This routine has been called to create an automatic index as a
2633 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2634 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2635 ** i.e. one of:
2636 **
2637 ** CREATE TABLE t(x PRIMARY KEY, y);
2638 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2639 **
2640 ** Either way, check to see if the table already has such an index. If
2641 ** so, don't bother creating this one. This only applies to
2642 ** automatically created indices. Users can do as they wish with
2643 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002644 **
2645 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2646 ** (and thus suppressing the second one) even if they have different
2647 ** sort orders.
2648 **
2649 ** If there are different collating sequences or if the columns of
2650 ** the constraint occur in different orders, then the constraints are
2651 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002652 */
2653 Index *pIdx;
2654 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2655 int k;
2656 assert( pIdx->onError!=OE_None );
2657 assert( pIdx->autoIndex );
2658 assert( pIndex->onError!=OE_None );
2659
2660 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2661 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002662 const char *z1;
2663 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002664 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002665 z1 = pIdx->azColl[k];
2666 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002667 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002668 }
2669 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002670 if( pIdx->onError!=pIndex->onError ){
2671 /* This constraint creates the same index as a previous
2672 ** constraint specified somewhere in the CREATE TABLE statement.
2673 ** However the ON CONFLICT clauses are different. If both this
2674 ** constraint and the previous equivalent constraint have explicit
2675 ** ON CONFLICT clauses this is an error. Otherwise, use the
2676 ** explicitly specified behaviour for the index.
2677 */
2678 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2679 sqlite3ErrorMsg(pParse,
2680 "conflicting ON CONFLICT clauses specified", 0);
2681 }
2682 if( pIdx->onError==OE_Default ){
2683 pIdx->onError = pIndex->onError;
2684 }
2685 }
danielk1977d8123362004-06-12 09:25:12 +00002686 goto exit_create_index;
2687 }
2688 }
2689 }
2690
drh75897232000-05-29 14:26:00 +00002691 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002692 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002693 */
drh234c39d2004-07-24 03:30:47 +00002694 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002695 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002696 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002697 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002698 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002699 if( p ){
2700 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002701 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002702 goto exit_create_index;
2703 }
drh5e00f6c2001-09-13 13:46:56 +00002704 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002705 if( pTblName!=0 ){
2706 pIndex->tnum = db->init.newTnum;
2707 }
drhd78eeee2001-09-13 16:18:53 +00002708 }
2709
drh1d85d932004-02-14 23:05:52 +00002710 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002711 ** involves writing the index into the master table and filling in the
2712 ** index with the current table contents.
2713 **
drh1d85d932004-02-14 23:05:52 +00002714 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2715 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002716 ** CREATE INDEX statements are read out of the master table. In
2717 ** the latter case the index already exists on disk, which is why
2718 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002719 **
danielk1977cbb18d22004-05-28 11:37:27 +00002720 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002721 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2722 ** has just been created, it contains no data and the index initialization
2723 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002724 */
drhd3001712009-05-12 17:46:53 +00002725 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002726 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002727 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002728 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002729
danielk19774adee202004-05-08 08:23:19 +00002730 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002731 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002732
drhfdd6e852005-12-16 01:06:16 +00002733
drh063336a2004-11-05 20:58:39 +00002734 /* Create the rootpage for the index
2735 */
drhaee128d2005-02-14 20:48:18 +00002736 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002737 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002738
2739 /* Gather the complete text of the CREATE INDEX statement into
2740 ** the zStmt variable
2741 */
drhd3001712009-05-12 17:46:53 +00002742 if( pStart ){
2743 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002744 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002745 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002746 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002747 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002748 pName->z);
2749 }else{
2750 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002751 /* zStmt = sqlite3MPrintf(""); */
2752 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002753 }
drh063336a2004-11-05 20:58:39 +00002754
2755 /* Add an entry in sqlite_master for this index
2756 */
2757 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002758 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002759 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2760 pIndex->zName,
2761 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002762 iMem,
drh063336a2004-11-05 20:58:39 +00002763 zStmt
2764 );
drh633e6d52008-07-28 19:34:53 +00002765 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002766
danielk1977a21c6b62005-01-24 10:25:59 +00002767 /* Fill the index with data and reparse the schema. Code an OP_Expire
2768 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002769 */
danielk1977cbb18d22004-05-28 11:37:27 +00002770 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002771 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002772 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002773 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2774 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2775 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002776 }
drh75897232000-05-29 14:26:00 +00002777 }
2778
danielk1977d8123362004-06-12 09:25:12 +00002779 /* When adding an index to the list of indices for a table, make
2780 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002781 ** OE_Ignore. This is necessary for the correct constraint check
2782 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2783 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002784 */
drh234c39d2004-07-24 03:30:47 +00002785 if( db->init.busy || pTblName==0 ){
2786 if( onError!=OE_Replace || pTab->pIndex==0
2787 || pTab->pIndex->onError==OE_Replace){
2788 pIndex->pNext = pTab->pIndex;
2789 pTab->pIndex = pIndex;
2790 }else{
2791 Index *pOther = pTab->pIndex;
2792 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2793 pOther = pOther->pNext;
2794 }
2795 pIndex->pNext = pOther->pNext;
2796 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002797 }
dan1da40a32009-09-19 17:00:31 +00002798 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00002799 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002800 }
danielk1977d8123362004-06-12 09:25:12 +00002801
drh75897232000-05-29 14:26:00 +00002802 /* Clean up before exiting */
2803exit_create_index:
drh956bc922004-07-24 17:38:29 +00002804 if( pIndex ){
drhb9755982010-07-24 16:34:37 +00002805 sqlite3DbFree(db, pIndex->zColAff);
danielk1977cb9d8d82009-03-18 18:43:36 +00002806 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002807 }
drh633e6d52008-07-28 19:34:53 +00002808 sqlite3ExprListDelete(db, pList);
2809 sqlite3SrcListDelete(db, pTblName);
2810 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00002811 return pRet;
drh75897232000-05-29 14:26:00 +00002812}
2813
2814/*
drh51147ba2005-07-23 22:59:55 +00002815** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002816** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002817**
2818** aiRowEst[0] is suppose to contain the number of elements in the index.
2819** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2820** number of rows in the table that match any particular value of the
2821** first column of the index. aiRowEst[2] is an estimate of the number
2822** of rows that match any particular combiniation of the first 2 columns
2823** of the index. And so forth. It must always be the case that
2824*
2825** aiRowEst[N]<=aiRowEst[N-1]
2826** aiRowEst[N]>=1
2827**
2828** Apart from that, we have little to go on besides intuition as to
2829** how aiRowEst[] should be initialized. The numbers generated here
2830** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002831*/
2832void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002833 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002834 int i;
drh15564052010-09-25 22:32:56 +00002835 unsigned n;
drh28c4cf42005-07-27 20:41:43 +00002836 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00002837 a[0] = pIdx->pTable->nRowEst;
2838 if( a[0]<10 ) a[0] = 10;
2839 n = 10;
2840 for(i=1; i<=pIdx->nColumn; i++){
2841 a[i] = n;
2842 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00002843 }
2844 if( pIdx->onError!=OE_None ){
2845 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002846 }
2847}
2848
2849/*
drh74e24cd2002-01-09 03:19:59 +00002850** This routine will drop an existing named index. This routine
2851** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002852*/
drh4d91a702006-01-04 15:54:36 +00002853void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002854 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002855 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002856 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002857 int iDb;
drh75897232000-05-29 14:26:00 +00002858
drh8af73d42009-05-13 22:58:28 +00002859 assert( pParse->nErr==0 ); /* Never called with prior errors */
2860 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002861 goto exit_drop_index;
2862 }
drhd24cc422003-03-27 12:51:24 +00002863 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002864 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2865 goto exit_drop_index;
2866 }
danielk19774adee202004-05-08 08:23:19 +00002867 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002868 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002869 if( !ifExists ){
2870 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2871 }
drha6ecd332004-06-10 00:29:09 +00002872 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002873 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002874 }
drh485b39b2002-07-13 03:11:52 +00002875 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002876 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002877 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002878 goto exit_drop_index;
2879 }
danielk1977da184232006-01-05 11:34:32 +00002880 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002881#ifndef SQLITE_OMIT_AUTHORIZATION
2882 {
2883 int code = SQLITE_DROP_INDEX;
2884 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002885 const char *zDb = db->aDb[iDb].zName;
2886 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002887 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002888 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002889 }
danielk1977da184232006-01-05 11:34:32 +00002890 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002891 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002892 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002893 }
drhed6c8672003-01-12 18:02:16 +00002894 }
drhe5f9c642003-01-13 23:27:31 +00002895#endif
drh75897232000-05-29 14:26:00 +00002896
2897 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002898 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002899 if( v ){
drh77658e22007-12-04 16:54:52 +00002900 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002901 sqlite3NestedParse(pParse,
2902 "DELETE FROM %Q.%s WHERE name=%Q",
2903 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2904 pIndex->zName
2905 );
danielk1977006015d2008-04-11 17:11:26 +00002906 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2907 sqlite3NestedParse(pParse,
2908 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2909 db->aDb[iDb].zName, pIndex->zName
2910 );
2911 }
drh9cbf3422008-01-17 16:22:13 +00002912 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002913 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002914 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002915 }
2916
drhd24cc422003-03-27 12:51:24 +00002917exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002918 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002919}
2920
2921/*
drhcf643722007-03-27 13:36:37 +00002922** pArray is a pointer to an array of objects. Each object in the
2923** array is szEntry bytes in size. This routine allocates a new
2924** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002925**
drhcf643722007-03-27 13:36:37 +00002926** *pnEntry is the number of entries already in use. *pnAlloc is
2927** the previously allocated size of the array. initSize is the
2928** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002929**
drhcf643722007-03-27 13:36:37 +00002930** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002931**
drhcf643722007-03-27 13:36:37 +00002932** This routine returns a pointer to the array of objects. This
2933** might be the same as the pArray parameter or it might be a different
2934** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002935*/
drhcf643722007-03-27 13:36:37 +00002936void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002937 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002938 void *pArray, /* Array of objects. Might be reallocated */
2939 int szEntry, /* Size of each object in the array */
2940 int initSize, /* Suggested initial allocation, in elements */
2941 int *pnEntry, /* Number of objects currently in use */
2942 int *pnAlloc, /* Current size of the allocation, in elements */
2943 int *pIdx /* Write the index of a new slot here */
2944){
2945 char *z;
2946 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002947 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002948 int newSize;
drhcf643722007-03-27 13:36:37 +00002949 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002950 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002951 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002952 *pIdx = -1;
2953 return pArray;
drh13449892005-09-07 21:22:45 +00002954 }
drh6a1e0712008-12-05 15:24:15 +00002955 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002956 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002957 }
drhcf643722007-03-27 13:36:37 +00002958 z = (char*)pArray;
2959 memset(&z[*pnEntry * szEntry], 0, szEntry);
2960 *pIdx = *pnEntry;
2961 ++*pnEntry;
2962 return pArray;
drh13449892005-09-07 21:22:45 +00002963}
2964
2965/*
drh75897232000-05-29 14:26:00 +00002966** Append a new element to the given IdList. Create a new IdList if
2967** need be.
drhdaffd0e2001-04-11 14:28:42 +00002968**
2969** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002970*/
drh17435752007-08-16 04:30:38 +00002971IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002972 int i;
drh75897232000-05-29 14:26:00 +00002973 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002974 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002975 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002976 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002977 }
drhcf643722007-03-27 13:36:37 +00002978 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002979 db,
drhcf643722007-03-27 13:36:37 +00002980 pList->a,
2981 sizeof(pList->a[0]),
2982 5,
2983 &pList->nId,
2984 &pList->nAlloc,
2985 &i
2986 );
drh13449892005-09-07 21:22:45 +00002987 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002988 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002989 return 0;
drh75897232000-05-29 14:26:00 +00002990 }
drh17435752007-08-16 04:30:38 +00002991 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002992 return pList;
2993}
2994
2995/*
drhfe05af82005-07-21 03:14:59 +00002996** Delete an IdList.
2997*/
drh633e6d52008-07-28 19:34:53 +00002998void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00002999 int i;
3000 if( pList==0 ) return;
3001 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003002 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003003 }
drh633e6d52008-07-28 19:34:53 +00003004 sqlite3DbFree(db, pList->a);
3005 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003006}
3007
3008/*
3009** Return the index in pList of the identifier named zId. Return -1
3010** if not found.
3011*/
3012int sqlite3IdListIndex(IdList *pList, const char *zName){
3013 int i;
3014 if( pList==0 ) return -1;
3015 for(i=0; i<pList->nId; i++){
3016 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3017 }
3018 return -1;
3019}
3020
3021/*
drha78c22c2008-11-11 18:28:58 +00003022** Expand the space allocated for the given SrcList object by
3023** creating nExtra new slots beginning at iStart. iStart is zero based.
3024** New slots are zeroed.
3025**
3026** For example, suppose a SrcList initially contains two entries: A,B.
3027** To append 3 new entries onto the end, do this:
3028**
3029** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3030**
3031** After the call above it would contain: A, B, nil, nil, nil.
3032** If the iStart argument had been 1 instead of 2, then the result
3033** would have been: A, nil, nil, nil, B. To prepend the new slots,
3034** the iStart value would be 0. The result then would
3035** be: nil, nil, nil, A, B.
3036**
3037** If a memory allocation fails the SrcList is unchanged. The
3038** db->mallocFailed flag will be set to true.
3039*/
3040SrcList *sqlite3SrcListEnlarge(
3041 sqlite3 *db, /* Database connection to notify of OOM errors */
3042 SrcList *pSrc, /* The SrcList to be enlarged */
3043 int nExtra, /* Number of new slots to add to pSrc->a[] */
3044 int iStart /* Index in pSrc->a[] of first new slot */
3045){
3046 int i;
3047
3048 /* Sanity checking on calling parameters */
3049 assert( iStart>=0 );
3050 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003051 assert( pSrc!=0 );
3052 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003053
3054 /* Allocate additional space if needed */
3055 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3056 SrcList *pNew;
3057 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003058 int nGot;
drha78c22c2008-11-11 18:28:58 +00003059 pNew = sqlite3DbRealloc(db, pSrc,
3060 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3061 if( pNew==0 ){
3062 assert( db->mallocFailed );
3063 return pSrc;
3064 }
3065 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003066 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003067 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003068 }
3069
3070 /* Move existing slots that come after the newly inserted slots
3071 ** out of the way */
3072 for(i=pSrc->nSrc-1; i>=iStart; i--){
3073 pSrc->a[i+nExtra] = pSrc->a[i];
3074 }
shane18e526c2008-12-10 22:30:24 +00003075 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003076
3077 /* Zero the newly allocated slots */
3078 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3079 for(i=iStart; i<iStart+nExtra; i++){
3080 pSrc->a[i].iCursor = -1;
3081 }
3082
3083 /* Return a pointer to the enlarged SrcList */
3084 return pSrc;
3085}
3086
3087
3088/*
drhad3cab52002-05-24 02:04:32 +00003089** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003090** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003091**
drha78c22c2008-11-11 18:28:58 +00003092** A SrcList is returned, or NULL if there is an OOM error. The returned
3093** SrcList might be the same as the SrcList that was input or it might be
3094** a new one. If an OOM error does occurs, then the prior value of pList
3095** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003096**
3097** If pDatabase is not null, it means that the table has an optional
3098** database name prefix. Like this: "database.table". The pDatabase
3099** points to the table name and the pTable points to the database name.
3100** The SrcList.a[].zName field is filled with the table name which might
3101** come from pTable (if pDatabase is NULL) or from pDatabase.
3102** SrcList.a[].zDatabase is filled with the database name from pTable,
3103** or with NULL if no database is specified.
3104**
3105** In other words, if call like this:
3106**
drh17435752007-08-16 04:30:38 +00003107** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003108**
3109** Then B is a table name and the database name is unspecified. If called
3110** like this:
3111**
drh17435752007-08-16 04:30:38 +00003112** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003113**
drhd3001712009-05-12 17:46:53 +00003114** Then C is the table name and B is the database name. If C is defined
3115** then so is B. In other words, we never have a case where:
3116**
3117** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003118**
3119** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3120** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003121*/
drh17435752007-08-16 04:30:38 +00003122SrcList *sqlite3SrcListAppend(
3123 sqlite3 *db, /* Connection to notify of malloc failures */
3124 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3125 Token *pTable, /* Table to append */
3126 Token *pDatabase /* Database of the table */
3127){
drha99db3b2004-06-19 14:49:12 +00003128 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003129 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003130 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003131 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003132 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003133 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003134 }
drha78c22c2008-11-11 18:28:58 +00003135 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3136 if( db->mallocFailed ){
3137 sqlite3SrcListDelete(db, pList);
3138 return 0;
drhad3cab52002-05-24 02:04:32 +00003139 }
drha78c22c2008-11-11 18:28:58 +00003140 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003141 if( pDatabase && pDatabase->z==0 ){
3142 pDatabase = 0;
3143 }
drhd3001712009-05-12 17:46:53 +00003144 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003145 Token *pTemp = pDatabase;
3146 pDatabase = pTable;
3147 pTable = pTemp;
3148 }
drh17435752007-08-16 04:30:38 +00003149 pItem->zName = sqlite3NameFromToken(db, pTable);
3150 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003151 return pList;
3152}
3153
3154/*
drhdfe88ec2008-11-03 20:55:06 +00003155** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003156*/
danielk19774adee202004-05-08 08:23:19 +00003157void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003158 int i;
drh9b3187e2005-01-18 14:45:47 +00003159 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003160 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003161 if( pList ){
3162 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3163 if( pItem->iCursor>=0 ) break;
3164 pItem->iCursor = pParse->nTab++;
3165 if( pItem->pSelect ){
3166 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3167 }
drh63eb5f22003-04-29 16:20:44 +00003168 }
3169 }
3170}
3171
3172/*
drhad3cab52002-05-24 02:04:32 +00003173** Delete an entire SrcList including all its substructure.
3174*/
drh633e6d52008-07-28 19:34:53 +00003175void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003176 int i;
drhbe5c89a2004-07-26 00:31:09 +00003177 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003178 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003179 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003180 sqlite3DbFree(db, pItem->zDatabase);
3181 sqlite3DbFree(db, pItem->zName);
3182 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003183 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003184 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003185 sqlite3SelectDelete(db, pItem->pSelect);
3186 sqlite3ExprDelete(db, pItem->pOn);
3187 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003188 }
drh633e6d52008-07-28 19:34:53 +00003189 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003190}
3191
drh982cef72000-05-30 16:27:03 +00003192/*
drh61dfc312006-12-16 16:25:15 +00003193** This routine is called by the parser to add a new term to the
3194** end of a growing FROM clause. The "p" parameter is the part of
3195** the FROM clause that has already been constructed. "p" is NULL
3196** if this is the first term of the FROM clause. pTable and pDatabase
3197** are the name of the table and database named in the FROM clause term.
3198** pDatabase is NULL if the database name qualifier is missing - the
3199** usual case. If the term has a alias, then pAlias points to the
3200** alias token. If the term is a subquery, then pSubquery is the
3201** SELECT statement that the subquery encodes. The pTable and
3202** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3203** parameters are the content of the ON and USING clauses.
3204**
3205** Return a new SrcList which encodes is the FROM with the new
3206** term added.
3207*/
3208SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003209 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003210 SrcList *p, /* The left part of the FROM clause already seen */
3211 Token *pTable, /* Name of the table to add to the FROM clause */
3212 Token *pDatabase, /* Name of the database containing pTable */
3213 Token *pAlias, /* The right-hand side of the AS subexpression */
3214 Select *pSubquery, /* A subquery used in place of a table name */
3215 Expr *pOn, /* The ON clause of a join */
3216 IdList *pUsing /* The USING clause of a join */
3217){
3218 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003219 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003220 if( !p && (pOn || pUsing) ){
3221 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3222 (pOn ? "ON" : "USING")
3223 );
3224 goto append_from_error;
3225 }
drh17435752007-08-16 04:30:38 +00003226 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003227 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003228 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003229 }
3230 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003231 assert( pAlias!=0 );
3232 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003233 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003234 }
3235 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003236 pItem->pOn = pOn;
3237 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003238 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003239
3240 append_from_error:
3241 assert( p==0 );
3242 sqlite3ExprDelete(db, pOn);
3243 sqlite3IdListDelete(db, pUsing);
3244 sqlite3SelectDelete(db, pSubquery);
3245 return 0;
drh61dfc312006-12-16 16:25:15 +00003246}
3247
3248/*
danielk1977b1c685b2008-10-06 16:18:39 +00003249** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3250** element of the source-list passed as the second argument.
3251*/
3252void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003253 assert( pIndexedBy!=0 );
3254 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003255 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3256 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3257 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3258 /* A "NOT INDEXED" clause was supplied. See parse.y
3259 ** construct "indexed_opt" for details. */
3260 pItem->notIndexed = 1;
3261 }else{
3262 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3263 }
3264 }
3265}
3266
3267/*
drh61dfc312006-12-16 16:25:15 +00003268** When building up a FROM clause in the parser, the join operator
3269** is initially attached to the left operand. But the code generator
3270** expects the join operator to be on the right operand. This routine
3271** Shifts all join operators from left to right for an entire FROM
3272** clause.
3273**
3274** Example: Suppose the join is like this:
3275**
3276** A natural cross join B
3277**
3278** The operator is "natural cross join". The A and B operands are stored
3279** in p->a[0] and p->a[1], respectively. The parser initially stores the
3280** operator with A. This routine shifts that operator over to B.
3281*/
3282void sqlite3SrcListShiftJoinType(SrcList *p){
3283 if( p && p->a ){
3284 int i;
3285 for(i=p->nSrc-1; i>0; i--){
3286 p->a[i].jointype = p->a[i-1].jointype;
3287 }
3288 p->a[0].jointype = 0;
3289 }
3290}
3291
3292/*
drhc4a3c772001-04-04 11:48:57 +00003293** Begin a transaction
3294*/
drh684917c2004-10-05 02:41:42 +00003295void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003296 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003297 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003298 int i;
drh5e00f6c2001-09-13 13:46:56 +00003299
drhd3001712009-05-12 17:46:53 +00003300 assert( pParse!=0 );
3301 db = pParse->db;
3302 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003303/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003304 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3305 return;
3306 }
danielk19771d850a72004-05-31 08:26:49 +00003307 v = sqlite3GetVdbe(pParse);
3308 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003309 if( type!=TK_DEFERRED ){
3310 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003311 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003312 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003313 }
3314 }
drh66a51672008-01-03 00:01:23 +00003315 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003316}
3317
3318/*
3319** Commit a transaction
3320*/
danielk19774adee202004-05-08 08:23:19 +00003321void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003322 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003323 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003324
drhd3001712009-05-12 17:46:53 +00003325 assert( pParse!=0 );
3326 db = pParse->db;
3327 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003328/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003329 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3330 return;
3331 }
danielk19771d850a72004-05-31 08:26:49 +00003332 v = sqlite3GetVdbe(pParse);
3333 if( v ){
drh66a51672008-01-03 00:01:23 +00003334 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003335 }
drhc4a3c772001-04-04 11:48:57 +00003336}
3337
3338/*
3339** Rollback a transaction
3340*/
danielk19774adee202004-05-08 08:23:19 +00003341void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003342 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003343 Vdbe *v;
3344
drhd3001712009-05-12 17:46:53 +00003345 assert( pParse!=0 );
3346 db = pParse->db;
3347 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003348/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003349 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3350 return;
3351 }
danielk19774adee202004-05-08 08:23:19 +00003352 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003353 if( v ){
drh66a51672008-01-03 00:01:23 +00003354 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003355 }
drhc4a3c772001-04-04 11:48:57 +00003356}
drhf57b14a2001-09-14 18:54:08 +00003357
3358/*
danielk1977fd7f0452008-12-17 17:30:26 +00003359** This function is called by the parser when it parses a command to create,
3360** release or rollback an SQL savepoint.
3361*/
3362void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003363 char *zName = sqlite3NameFromToken(pParse->db, pName);
3364 if( zName ){
3365 Vdbe *v = sqlite3GetVdbe(pParse);
3366#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003367 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003368 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3369#endif
3370 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3371 sqlite3DbFree(pParse->db, zName);
3372 return;
3373 }
3374 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003375 }
3376}
3377
3378/*
drhdc3ff9c2004-08-18 02:10:15 +00003379** Make sure the TEMP database is open and available for use. Return
3380** the number of errors. Leave any error messages in the pParse structure.
3381*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003382int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003383 sqlite3 *db = pParse->db;
3384 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003385 int rc;
drh10a76c92010-01-26 01:25:26 +00003386 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003387 static const int flags =
3388 SQLITE_OPEN_READWRITE |
3389 SQLITE_OPEN_CREATE |
3390 SQLITE_OPEN_EXCLUSIVE |
3391 SQLITE_OPEN_DELETEONCLOSE |
3392 SQLITE_OPEN_TEMP_DB;
3393
drh75c014c2010-08-30 15:02:28 +00003394 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003395 if( rc!=SQLITE_OK ){
3396 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3397 "file for storing temporary tables");
3398 pParse->rc = rc;
3399 return 1;
3400 }
drh10a76c92010-01-26 01:25:26 +00003401 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003402 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003403 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3404 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003405 return 1;
drh10a76c92010-01-26 01:25:26 +00003406 }
drhdc3ff9c2004-08-18 02:10:15 +00003407 }
3408 return 0;
3409}
3410
3411/*
drh80242052004-06-09 00:48:12 +00003412** Generate VDBE code that will verify the schema cookie and start
3413** a read-transaction for all named database files.
3414**
3415** It is important that all schema cookies be verified and all
3416** read transactions be started before anything else happens in
3417** the VDBE program. But this routine can be called after much other
3418** code has been generated. So here is what we do:
3419**
drhc275b4e2004-07-19 17:25:24 +00003420** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003421** will jump to a subroutine at the end of the program. Then we
3422** record every database that needs its schema verified in the
3423** pParse->cookieMask field. Later, after all other code has been
3424** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003425** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003426** will be made to point to that subroutine. The generation of the
3427** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003428**
3429** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3430** schema on any databases. This can be used to position the OP_Goto
3431** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003432*/
danielk19774adee202004-05-08 08:23:19 +00003433void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003434 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003435
dan65a7cd12009-09-01 12:16:01 +00003436 if( pToplevel->cookieGoto==0 ){
3437 Vdbe *v = sqlite3GetVdbe(pToplevel);
3438 if( v==0 ) return; /* This only happens if there was a prior error */
3439 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003440 }
drhc275b4e2004-07-19 17:25:24 +00003441 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003442 sqlite3 *db = pToplevel->db;
3443 int mask;
3444
drhc275b4e2004-07-19 17:25:24 +00003445 assert( iDb<db->nDb );
3446 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003447 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003448 mask = 1<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003449 if( (pToplevel->cookieMask & mask)==0 ){
3450 pToplevel->cookieMask |= mask;
3451 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003452 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003453 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003454 }
drhc275b4e2004-07-19 17:25:24 +00003455 }
drh001bbcb2003-03-19 03:14:00 +00003456 }
drh001bbcb2003-03-19 03:14:00 +00003457}
3458
3459/*
drh1c928532002-01-31 15:54:21 +00003460** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003461** might change the database.
3462**
3463** This routine starts a new transaction if we are not already within
3464** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003465** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003466** be set for operations that might fail (due to a constraint) part of
3467** the way through and which will need to undo some writes without having to
3468** rollback the whole transaction. For operations where all constraints
3469** can be checked before any changes are made to the database, it is never
3470** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003471*/
drh7f0f12e2004-05-21 13:39:50 +00003472void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003473 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003474 sqlite3CodeVerifySchema(pParse, iDb);
dan65a7cd12009-09-01 12:16:01 +00003475 pToplevel->writeMask |= 1<<iDb;
dane0af83a2009-09-08 19:15:01 +00003476 pToplevel->isMultiWrite |= setStatement;
3477}
3478
drhff738bc2009-09-24 00:09:58 +00003479/*
3480** Indicate that the statement currently under construction might write
3481** more than one entry (example: deleting one row then inserting another,
3482** inserting multiple rows in a table, or inserting a row and index entries.)
3483** If an abort occurs after some of these writes have completed, then it will
3484** be necessary to undo the completed writes.
3485*/
3486void sqlite3MultiWrite(Parse *pParse){
3487 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3488 pToplevel->isMultiWrite = 1;
3489}
3490
dane0af83a2009-09-08 19:15:01 +00003491/*
drhff738bc2009-09-24 00:09:58 +00003492** The code generator calls this routine if is discovers that it is
3493** possible to abort a statement prior to completion. In order to
3494** perform this abort without corrupting the database, we need to make
3495** sure that the statement is protected by a statement transaction.
3496**
3497** Technically, we only need to set the mayAbort flag if the
3498** isMultiWrite flag was previously set. There is a time dependency
3499** such that the abort must occur after the multiwrite. This makes
3500** some statements involving the REPLACE conflict resolution algorithm
3501** go a little faster. But taking advantage of this time dependency
3502** makes it more difficult to prove that the code is correct (in
3503** particular, it prevents us from writing an effective
3504** implementation of sqlite3AssertMayAbort()) and so we have chosen
3505** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003506*/
3507void sqlite3MayAbort(Parse *pParse){
3508 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3509 pToplevel->mayAbort = 1;
3510}
3511
3512/*
3513** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3514** error. The onError parameter determines which (if any) of the statement
3515** and/or current transaction is rolled back.
3516*/
3517void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3518 Vdbe *v = sqlite3GetVdbe(pParse);
3519 if( onError==OE_Abort ){
3520 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003521 }
dane0af83a2009-09-08 19:15:01 +00003522 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003523}
3524
drh4343fea2004-11-05 23:46:15 +00003525/*
3526** Check to see if pIndex uses the collating sequence pColl. Return
3527** true if it does and false if it does not.
3528*/
3529#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003530static int collationMatch(const char *zColl, Index *pIndex){
3531 int i;
drh04491712009-05-13 17:21:13 +00003532 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003533 for(i=0; i<pIndex->nColumn; i++){
3534 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003535 assert( z!=0 );
3536 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003537 return 1;
3538 }
drh4343fea2004-11-05 23:46:15 +00003539 }
3540 return 0;
3541}
3542#endif
3543
3544/*
3545** Recompute all indices of pTab that use the collating sequence pColl.
3546** If pColl==0 then recompute all indices of pTab.
3547*/
3548#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003549static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003550 Index *pIndex; /* An index associated with pTab */
3551
3552 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003553 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003554 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3555 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003556 sqlite3RefillIndex(pParse, pIndex, -1);
3557 }
3558 }
3559}
3560#endif
3561
3562/*
3563** Recompute all indices of all tables in all databases where the
3564** indices use the collating sequence pColl. If pColl==0 then recompute
3565** all indices everywhere.
3566*/
3567#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003568static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003569 Db *pDb; /* A single database */
3570 int iDb; /* The database index number */
3571 sqlite3 *db = pParse->db; /* The database connection */
3572 HashElem *k; /* For looping over tables in pDb */
3573 Table *pTab; /* A table in the database */
3574
3575 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003576 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003577 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003578 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003579 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003580 }
3581 }
3582}
3583#endif
3584
3585/*
drheee46cf2004-11-06 00:02:48 +00003586** Generate code for the REINDEX command.
3587**
3588** REINDEX -- 1
3589** REINDEX <collation> -- 2
3590** REINDEX ?<database>.?<tablename> -- 3
3591** REINDEX ?<database>.?<indexname> -- 4
3592**
3593** Form 1 causes all indices in all attached databases to be rebuilt.
3594** Form 2 rebuilds all indices in all databases that use the named
3595** collating function. Forms 3 and 4 rebuild the named index or all
3596** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003597*/
3598#ifndef SQLITE_OMIT_REINDEX
3599void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3600 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3601 char *z; /* Name of a table or index */
3602 const char *zDb; /* Name of the database */
3603 Table *pTab; /* A table in the database */
3604 Index *pIndex; /* An index associated with pTab */
3605 int iDb; /* The database index number */
3606 sqlite3 *db = pParse->db; /* The database connection */
3607 Token *pObjName; /* Name of the table or index to be reindexed */
3608
danielk197733a5edc2005-01-27 00:22:02 +00003609 /* Read the database schema. If an error occurs, leave an error message
3610 ** and code in pParse and return NULL. */
3611 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003612 return;
danielk197733a5edc2005-01-27 00:22:02 +00003613 }
3614
drh8af73d42009-05-13 22:58:28 +00003615 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003616 reindexDatabases(pParse, 0);
3617 return;
drhd3001712009-05-12 17:46:53 +00003618 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003619 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003620 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003621 zColl = sqlite3NameFromToken(pParse->db, pName1);
3622 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003623 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003624 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003625 reindexDatabases(pParse, zColl);
3626 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003627 return;
3628 }
drh633e6d52008-07-28 19:34:53 +00003629 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003630 }
3631 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3632 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003633 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003634 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003635 zDb = db->aDb[iDb].zName;
3636 pTab = sqlite3FindTable(db, z, zDb);
3637 if( pTab ){
3638 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003639 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003640 return;
3641 }
3642 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003643 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003644 if( pIndex ){
3645 sqlite3BeginWriteOperation(pParse, 0, iDb);
3646 sqlite3RefillIndex(pParse, pIndex, -1);
3647 return;
3648 }
3649 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3650}
3651#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003652
3653/*
3654** Return a dynamicly allocated KeyInfo structure that can be used
3655** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3656**
3657** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003658** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003659** pointer. If an error occurs (out of memory or missing collation
3660** sequence), NULL is returned and the state of pParse updated to reflect
3661** the error.
3662*/
3663KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3664 int i;
3665 int nCol = pIdx->nColumn;
3666 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003667 sqlite3 *db = pParse->db;
3668 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003669
3670 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003671 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003672 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3673 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3674 for(i=0; i<nCol; i++){
3675 char *zColl = pIdx->azColl[i];
3676 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003677 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003678 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3679 }
drh1bd10f82008-12-10 21:19:56 +00003680 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003681 }
3682
3683 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003684 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003685 pKey = 0;
3686 }
3687 return pKey;
3688}