blob: 2cfb1f45abb2f3917fcbce4635bd0b2e33d13e24 [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 ){
dana16d1062010-09-28 17:37:28 +0000779 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000780 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
781 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000782 }
dana16d1062010-09-28 17:37:28 +0000783 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000784 if( pTable ){
785 if( !noErr ){
786 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
787 }
788 goto begin_table_error;
789 }
drh8a8a0d12010-09-28 20:26:44 +0000790 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000791 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
792 goto begin_table_error;
793 }
drh75897232000-05-29 14:26:00 +0000794 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000795
danielk197726783a52007-08-29 14:06:22 +0000796 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000797 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000798 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000799 pParse->rc = SQLITE_NOMEM;
800 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000801 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000802 }
drh75897232000-05-29 14:26:00 +0000803 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000804 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000805 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000806 pTable->nRef = 1;
drh15564052010-09-25 22:32:56 +0000807 pTable->nRowEst = 1000000;
drhc4a64fa2009-05-11 20:53:28 +0000808 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000809 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000810
drh4794f732004-11-05 17:17:50 +0000811 /* If this is the magic sqlite_sequence table used by autoincrement,
812 ** then record a pointer to this table in the main database structure
813 ** so that INSERT can find the table easily.
814 */
815#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000816 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000817 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000818 }
819#endif
820
drh17f71932002-02-21 12:01:27 +0000821 /* Begin generating the code that will insert the table record into
822 ** the SQLITE_MASTER table. Note in particular that we must go ahead
823 ** and allocate the record number for the table entry now. Before any
824 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
825 ** indices to be created and the table record must come before the
826 ** indices. Hence, the record number for the table must be allocated
827 ** now.
828 */
danielk19774adee202004-05-08 08:23:19 +0000829 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000830 int j1;
drhe321c292006-01-12 01:56:43 +0000831 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000832 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000833 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000834
danielk197720b1eaf2006-07-26 16:22:14 +0000835#ifndef SQLITE_OMIT_VIRTUALTABLE
836 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000837 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000838 }
839#endif
840
danielk197736963fd2005-02-19 08:18:05 +0000841 /* If the file format and encoding in the database have not been set,
842 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000843 */
drhb7654112008-01-12 12:48:07 +0000844 reg1 = pParse->regRowid = ++pParse->nMem;
845 reg2 = pParse->regRoot = ++pParse->nMem;
846 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000847 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000848 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000849 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000850 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000851 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000852 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000853 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000854 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000855 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000856 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000857
drh4794f732004-11-05 17:17:50 +0000858 /* This just creates a place-holder record in the sqlite_master table.
859 ** The record created does not contain anything yet. It will be replaced
860 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000861 **
drh0fa991b2009-03-21 16:19:26 +0000862 ** The rowid for the new entry is left in register pParse->regRowid.
863 ** The root page number of the new table is left in reg pParse->regRoot.
864 ** The rowid and root page number values are needed by the code that
865 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000866 */
danielk1977f1a381e2006-06-16 08:01:02 +0000867#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
868 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000869 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000870 }else
871#endif
872 {
drhb7654112008-01-12 12:48:07 +0000873 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000874 }
danielk1977c00da102006-01-07 13:21:04 +0000875 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000876 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
877 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
878 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
879 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000880 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000881 }
drh23bf66d2004-12-14 03:34:34 +0000882
883 /* Normal (non-error) return. */
884 return;
885
886 /* If an error occurs, we jump here */
887begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000888 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000889 return;
drh75897232000-05-29 14:26:00 +0000890}
891
892/*
danielk1977c60e9b82005-01-31 12:42:29 +0000893** This macro is used to compare two strings in a case-insensitive manner.
894** It is slightly faster than calling sqlite3StrICmp() directly, but
895** produces larger code.
896**
897** WARNING: This macro is not compatible with the strcmp() family. It
898** returns true if the two strings are equal, otherwise false.
899*/
900#define STRICMP(x, y) (\
901sqlite3UpperToLower[*(unsigned char *)(x)]== \
902sqlite3UpperToLower[*(unsigned char *)(y)] \
903&& sqlite3StrICmp((x)+1,(y)+1)==0 )
904
905/*
drh75897232000-05-29 14:26:00 +0000906** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000907**
908** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000909** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000910** first to get things going. Then this routine is called for each
911** column.
drh75897232000-05-29 14:26:00 +0000912*/
danielk19774adee202004-05-08 08:23:19 +0000913void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000914 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000915 int i;
drha99db3b2004-06-19 14:49:12 +0000916 char *z;
drhc9b84a12002-06-20 11:36:48 +0000917 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000918 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000919 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000920#if SQLITE_MAX_COLUMN
921 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000922 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
923 return;
924 }
drhbb4957f2008-03-20 14:03:29 +0000925#endif
danielk1977ae74e032008-12-23 11:11:51 +0000926 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000927 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000928 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000929 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000930 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000931 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000932 return;
933 }
934 }
drh75897232000-05-29 14:26:00 +0000935 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000936 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000937 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000938 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000939 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000940 return;
941 }
drh6d4abfb2001-10-22 02:58:08 +0000942 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000943 }
drhc9b84a12002-06-20 11:36:48 +0000944 pCol = &p->aCol[p->nCol];
945 memset(pCol, 0, sizeof(p->aCol[0]));
946 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000947
948 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000949 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
950 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000951 */
danielk19774f057f92004-06-08 00:02:33 +0000952 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000953 p->nCol++;
drh75897232000-05-29 14:26:00 +0000954}
955
956/*
drh382c0242001-10-06 16:33:02 +0000957** This routine is called by the parser while in the middle of
958** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
959** been seen on a column. This routine sets the notNull flag on
960** the column currently under construction.
961*/
danielk19774adee202004-05-08 08:23:19 +0000962void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000963 Table *p;
drhc4a64fa2009-05-11 20:53:28 +0000964 p = pParse->pNewTable;
965 if( p==0 || NEVER(p->nCol<1) ) return;
966 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000967}
968
969/*
danielk197752a83fb2005-01-31 12:56:44 +0000970** Scan the column type name zType (length nType) and return the
971** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000972**
973** This routine does a case-independent search of zType for the
974** substrings in the following table. If one of the substrings is
975** found, the corresponding affinity is returned. If zType contains
976** more than one of the substrings, entries toward the top of
977** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000978** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000979**
980** Substring | Affinity
981** --------------------------------
982** 'INT' | SQLITE_AFF_INTEGER
983** 'CHAR' | SQLITE_AFF_TEXT
984** 'CLOB' | SQLITE_AFF_TEXT
985** 'TEXT' | SQLITE_AFF_TEXT
986** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000987** 'REAL' | SQLITE_AFF_REAL
988** 'FLOA' | SQLITE_AFF_REAL
989** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +0000990**
991** If none of the substrings in the above table are found,
992** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000993*/
drhb7916a72009-05-27 10:31:29 +0000994char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +0000995 u32 h = 0;
996 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +0000997
drhb7916a72009-05-27 10:31:29 +0000998 if( zIn ) while( zIn[0] ){
999 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001000 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001001 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1002 aff = SQLITE_AFF_TEXT;
1003 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1004 aff = SQLITE_AFF_TEXT;
1005 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1006 aff = SQLITE_AFF_TEXT;
1007 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001008 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001009 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001010#ifndef SQLITE_OMIT_FLOATING_POINT
1011 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1012 && aff==SQLITE_AFF_NUMERIC ){
1013 aff = SQLITE_AFF_REAL;
1014 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1015 && aff==SQLITE_AFF_NUMERIC ){
1016 aff = SQLITE_AFF_REAL;
1017 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1018 && aff==SQLITE_AFF_NUMERIC ){
1019 aff = SQLITE_AFF_REAL;
1020#endif
danielk1977201f7162005-02-01 02:13:29 +00001021 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001022 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001023 break;
danielk197752a83fb2005-01-31 12:56:44 +00001024 }
1025 }
danielk1977b3dff962005-02-01 01:21:55 +00001026
1027 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001028}
1029
1030/*
drh382c0242001-10-06 16:33:02 +00001031** This routine is called by the parser while in the middle of
1032** parsing a CREATE TABLE statement. The pFirst token is the first
1033** token in the sequence of tokens that describe the type of the
1034** column currently under construction. pLast is the last token
1035** in the sequence. Use this information to construct a string
1036** that contains the typename of the column and store that string
1037** in zType.
1038*/
drh487e2622005-06-25 18:42:14 +00001039void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001040 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001041 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001042
drhc4a64fa2009-05-11 20:53:28 +00001043 p = pParse->pNewTable;
1044 if( p==0 || NEVER(p->nCol<1) ) return;
1045 pCol = &p->aCol[p->nCol-1];
1046 assert( pCol->zType==0 );
1047 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001048 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001049}
1050
1051/*
danielk19777977a172004-11-09 12:44:37 +00001052** The expression is the default value for the most recently added column
1053** of the table currently under construction.
1054**
1055** Default value expressions must be constant. Raise an exception if this
1056** is not the case.
drhd9b02572001-04-15 00:37:09 +00001057**
1058** This routine is called by the parser while in the middle of
1059** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001060*/
drhb7916a72009-05-27 10:31:29 +00001061void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001062 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001063 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001064 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001065 p = pParse->pNewTable;
1066 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001067 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001068 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001069 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1070 pCol->zName);
1071 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001072 /* A copy of pExpr is used instead of the original, as pExpr contains
1073 ** tokens that point to volatile memory. The 'span' of the expression
1074 ** is required by pragma table_info.
1075 */
drh633e6d52008-07-28 19:34:53 +00001076 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001077 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1078 sqlite3DbFree(db, pCol->zDflt);
1079 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001080 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001081 }
danielk19777977a172004-11-09 12:44:37 +00001082 }
drhb7916a72009-05-27 10:31:29 +00001083 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001084}
1085
1086/*
drh4a324312001-12-21 14:30:42 +00001087** Designate the PRIMARY KEY for the table. pList is a list of names
1088** of columns that form the primary key. If pList is NULL, then the
1089** most recently added column of the table is the primary key.
1090**
1091** A table can have at most one primary key. If the table already has
1092** a primary key (and this is the second primary key) then create an
1093** error.
1094**
1095** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001096** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001097** field of the table under construction to be the index of the
1098** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1099** no INTEGER PRIMARY KEY.
1100**
1101** If the key is not an INTEGER PRIMARY KEY, then create a unique
1102** index for the key. No index is created for INTEGER PRIMARY KEYs.
1103*/
drh205f48e2004-11-05 00:43:11 +00001104void sqlite3AddPrimaryKey(
1105 Parse *pParse, /* Parsing context */
1106 ExprList *pList, /* List of field names to be indexed */
1107 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001108 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1109 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001110){
drh4a324312001-12-21 14:30:42 +00001111 Table *pTab = pParse->pNewTable;
1112 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001113 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001114 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001115 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001116 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001117 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001118 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001119 }
drh7d10d5a2008-08-20 16:35:10 +00001120 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001121 if( pList==0 ){
1122 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001123 pTab->aCol[iCol].isPrimKey = 1;
1124 }else{
danielk19770202b292004-06-09 09:55:16 +00001125 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001126 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001127 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1128 break;
1129 }
drh78100cc2003-08-23 22:40:53 +00001130 }
drh6e4fc2c2005-09-15 21:24:51 +00001131 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001132 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001133 }
drh4a324312001-12-21 14:30:42 +00001134 }
danielk19770202b292004-06-09 09:55:16 +00001135 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001136 }
1137 if( iCol>=0 && iCol<pTab->nCol ){
1138 zType = pTab->aCol[iCol].zType;
1139 }
drhfdd6e852005-12-16 01:06:16 +00001140 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1141 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001142 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001143 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001144 assert( autoInc==0 || autoInc==1 );
1145 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001146 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001147#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001148 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1149 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001150#endif
drh4a324312001-12-21 14:30:42 +00001151 }else{
dan1da40a32009-09-19 17:00:31 +00001152 Index *p;
1153 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1154 if( p ){
1155 p->autoIndex = 2;
1156 }
drhe0194f22003-02-26 13:52:51 +00001157 pList = 0;
drh4a324312001-12-21 14:30:42 +00001158 }
drhe0194f22003-02-26 13:52:51 +00001159
1160primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001161 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001162 return;
drh4a324312001-12-21 14:30:42 +00001163}
1164
1165/*
drhffe07b22005-11-03 00:41:17 +00001166** Add a new CHECK constraint to the table currently under construction.
1167*/
1168void sqlite3AddCheckConstraint(
1169 Parse *pParse, /* Parsing context */
1170 Expr *pCheckExpr /* The check expression */
1171){
drh633e6d52008-07-28 19:34:53 +00001172 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001173#ifndef SQLITE_OMIT_CHECK
1174 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001175 if( pTab && !IN_DECLARE_VTAB ){
drh33e619f2009-05-28 01:00:55 +00001176 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1177 }else
drhffe07b22005-11-03 00:41:17 +00001178#endif
drh33e619f2009-05-28 01:00:55 +00001179 {
1180 sqlite3ExprDelete(db, pCheckExpr);
1181 }
drhffe07b22005-11-03 00:41:17 +00001182}
1183
1184/*
drhd3d39e92004-05-20 22:16:29 +00001185** Set the collation function of the most recently parsed table column
1186** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001187*/
danielk197739002502007-11-12 09:50:26 +00001188void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001189 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001190 int i;
danielk197739002502007-11-12 09:50:26 +00001191 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001192 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001193
danielk1977b8cbb872006-06-19 05:33:45 +00001194 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001195 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001196 db = pParse->db;
1197 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001198 if( !zColl ) return;
1199
drhc4a64fa2009-05-11 20:53:28 +00001200 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001201 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001202 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001203
1204 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1205 ** then an index may have been created on this column before the
1206 ** collation type was added. Correct this if it is the case.
1207 */
1208 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1209 assert( pIdx->nColumn==1 );
1210 if( pIdx->aiColumn[0]==i ){
1211 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001212 }
1213 }
danielk197739002502007-11-12 09:50:26 +00001214 }else{
drh633e6d52008-07-28 19:34:53 +00001215 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001216 }
danielk19777cedc8d2004-06-10 10:50:08 +00001217}
1218
danielk1977466be562004-06-10 02:16:01 +00001219/*
1220** This function returns the collation sequence for database native text
1221** encoding identified by the string zName, length nName.
1222**
1223** If the requested collation sequence is not available, or not available
1224** in the database native encoding, the collation factory is invoked to
1225** request it. If the collation factory does not supply such a sequence,
1226** and the sequence is available in another text encoding, then that is
1227** returned instead.
1228**
1229** If no versions of the requested collations sequence are available, or
1230** another error occurs, NULL is returned and an error message written into
1231** pParse.
drha34001c2007-02-02 12:44:37 +00001232**
1233** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1234** invokes the collation factory if the named collation cannot be found
1235** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001236**
1237** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001238*/
drhc4a64fa2009-05-11 20:53:28 +00001239CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001240 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001241 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001242 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001243 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001244
drhc4a64fa2009-05-11 20:53:28 +00001245 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001246 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh9aeda792009-08-20 02:34:15 +00001247 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
danielk19774dade032005-05-25 10:45:10 +00001248 if( !pColl ){
drhc4a64fa2009-05-11 20:53:28 +00001249 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
danielk1977466be562004-06-10 02:16:01 +00001250 }
1251 }
1252
danielk19770202b292004-06-09 09:55:16 +00001253 return pColl;
1254}
1255
1256
drh8e2ca022002-06-17 17:07:19 +00001257/*
drh3f7d4e42004-07-24 14:35:58 +00001258** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001259**
1260** The schema cookie is used to determine when the schema for the
1261** database changes. After each schema change, the cookie value
1262** changes. When a process first reads the schema it records the
1263** cookie. Thereafter, whenever it goes to access the database,
1264** it checks the cookie to make sure the schema has not changed
1265** since it was last read.
1266**
1267** This plan is not completely bullet-proof. It is possible for
1268** the schema to change multiple times and for the cookie to be
1269** set back to prior value. But schema changes are infrequent
1270** and the probability of hitting the same cookie value is only
1271** 1 chance in 2^32. So we're safe enough.
1272*/
drh9cbf3422008-01-17 16:22:13 +00001273void sqlite3ChangeCookie(Parse *pParse, int iDb){
1274 int r1 = sqlite3GetTempReg(pParse);
1275 sqlite3 *db = pParse->db;
1276 Vdbe *v = pParse->pVdbe;
1277 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001278 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001279 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001280}
1281
1282/*
drh969fa7c2002-02-18 18:30:32 +00001283** Measure the number of characters needed to output the given
1284** identifier. The number returned includes any quotes used
1285** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001286**
1287** The estimate is conservative. It might be larger that what is
1288** really needed.
drh969fa7c2002-02-18 18:30:32 +00001289*/
1290static int identLength(const char *z){
1291 int n;
drh17f71932002-02-21 12:01:27 +00001292 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001293 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001294 }
drh234c39d2004-07-24 03:30:47 +00001295 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001296}
1297
1298/*
danielk19771b870de2009-03-14 08:37:23 +00001299** The first parameter is a pointer to an output buffer. The second
1300** parameter is a pointer to an integer that contains the offset at
1301** which to write into the output buffer. This function copies the
1302** nul-terminated string pointed to by the third parameter, zSignedIdent,
1303** to the specified offset in the buffer and updates *pIdx to refer
1304** to the first byte after the last byte written before returning.
1305**
1306** If the string zSignedIdent consists entirely of alpha-numeric
1307** characters, does not begin with a digit and is not an SQL keyword,
1308** then it is copied to the output buffer exactly as it is. Otherwise,
1309** it is quoted using double-quotes.
1310*/
drhc4a64fa2009-05-11 20:53:28 +00001311static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001312 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001313 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001314 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001315
drh17f71932002-02-21 12:01:27 +00001316 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001317 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001318 }
danielk19771b870de2009-03-14 08:37:23 +00001319 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1320 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001321 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001322 }
1323
drh234c39d2004-07-24 03:30:47 +00001324 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001325 for(j=0; zIdent[j]; j++){
1326 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001327 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001328 }
drh234c39d2004-07-24 03:30:47 +00001329 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001330 z[i] = 0;
1331 *pIdx = i;
1332}
1333
1334/*
1335** Generate a CREATE TABLE statement appropriate for the given
1336** table. Memory to hold the text of the statement is obtained
1337** from sqliteMalloc() and must be freed by the calling function.
1338*/
drh1d34fde2009-02-03 15:50:33 +00001339static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001340 int i, k, n;
1341 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001342 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001343 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001344 n = 0;
drh234c39d2004-07-24 03:30:47 +00001345 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001346 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001347 }
1348 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001349 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001350 zSep = "";
1351 zSep2 = ",";
1352 zEnd = ")";
1353 }else{
1354 zSep = "\n ";
1355 zSep2 = ",\n ";
1356 zEnd = "\n)";
1357 }
drhe0bc4042002-06-25 01:09:11 +00001358 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001359 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001360 if( zStmt==0 ){
1361 db->mallocFailed = 1;
1362 return 0;
1363 }
drhbdb339f2009-02-02 18:03:21 +00001364 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001365 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001366 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001367 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001368 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001369 static const char * const azType[] = {
1370 /* SQLITE_AFF_TEXT */ " TEXT",
1371 /* SQLITE_AFF_NONE */ "",
1372 /* SQLITE_AFF_NUMERIC */ " NUM",
1373 /* SQLITE_AFF_INTEGER */ " INT",
1374 /* SQLITE_AFF_REAL */ " REAL"
1375 };
1376 int len;
1377 const char *zType;
1378
drh5bb3eb92007-05-04 13:15:55 +00001379 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001380 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001381 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001382 identPut(zStmt, &k, pCol->zName);
1383 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1384 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
1385 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1386 testcase( pCol->affinity==SQLITE_AFF_NONE );
1387 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1388 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1389 testcase( pCol->affinity==SQLITE_AFF_REAL );
1390
1391 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1392 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001393 assert( pCol->affinity==SQLITE_AFF_NONE
1394 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001395 memcpy(&zStmt[k], zType, len);
1396 k += len;
1397 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001398 }
drh5bb3eb92007-05-04 13:15:55 +00001399 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001400 return zStmt;
1401}
1402
1403/*
drh75897232000-05-29 14:26:00 +00001404** This routine is called to report the final ")" that terminates
1405** a CREATE TABLE statement.
1406**
drhf57b3392001-10-08 13:22:32 +00001407** The table structure that other action routines have been building
1408** is added to the internal hash tables, assuming no errors have
1409** occurred.
drh75897232000-05-29 14:26:00 +00001410**
drh1d85d932004-02-14 23:05:52 +00001411** An entry for the table is made in the master table on disk, unless
1412** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001413** it means we are reading the sqlite_master table because we just
1414** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001415** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001416** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001417**
1418** If the pSelect argument is not NULL, it means that this routine
1419** was called to create a table generated from a
1420** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1421** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001422*/
danielk197719a8e7e2005-03-17 05:03:38 +00001423void sqlite3EndTable(
1424 Parse *pParse, /* Parse context */
1425 Token *pCons, /* The ',' token after the last column defn. */
1426 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1427 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1428){
drh75897232000-05-29 14:26:00 +00001429 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001430 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001431 int iDb;
drh75897232000-05-29 14:26:00 +00001432
drh8af73d42009-05-13 22:58:28 +00001433 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001434 return;
1435 }
drh28037572000-08-02 13:47:41 +00001436 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001437 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001438
danielk1977517eb642004-06-07 10:00:31 +00001439 assert( !db->init.busy || !pSelect );
1440
drhb9bb7c12006-06-11 23:41:55 +00001441 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001442
drhffe07b22005-11-03 00:41:17 +00001443#ifndef SQLITE_OMIT_CHECK
1444 /* Resolve names in all CHECK constraint expressions.
1445 */
1446 if( p->pCheck ){
1447 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1448 NameContext sNC; /* Name context for pParse->pNewTable */
1449
1450 memset(&sNC, 0, sizeof(sNC));
1451 memset(&sSrc, 0, sizeof(sSrc));
1452 sSrc.nSrc = 1;
1453 sSrc.a[0].zName = p->zName;
1454 sSrc.a[0].pTab = p;
1455 sSrc.a[0].iCursor = -1;
1456 sNC.pParse = pParse;
1457 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001458 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001459 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001460 return;
1461 }
1462 }
1463#endif /* !defined(SQLITE_OMIT_CHECK) */
1464
drh1d85d932004-02-14 23:05:52 +00001465 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001466 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1467 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001468 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001469 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001470 */
drh1d85d932004-02-14 23:05:52 +00001471 if( db->init.busy ){
1472 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001473 }
1474
drhe3c41372001-09-17 20:25:58 +00001475 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001476 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001477 **
drhe0bc4042002-06-25 01:09:11 +00001478 ** If this is a TEMPORARY table, write the entry into the auxiliary
1479 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001480 */
drh1d85d932004-02-14 23:05:52 +00001481 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001482 int n;
drhd8bc7082000-06-07 23:51:50 +00001483 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001484 char *zType; /* "view" or "table" */
1485 char *zType2; /* "VIEW" or "TABLE" */
1486 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001487
danielk19774adee202004-05-08 08:23:19 +00001488 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001489 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001490
drh66a51672008-01-03 00:01:23 +00001491 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001492
drh0fa991b2009-03-21 16:19:26 +00001493 /*
1494 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001495 */
drh4ff6dfa2002-03-03 23:06:00 +00001496 if( p->pSelect==0 ){
1497 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001498 zType = "table";
1499 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001500#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001501 }else{
1502 /* A view */
drh4794f732004-11-05 17:17:50 +00001503 zType = "view";
1504 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001505#endif
drh4ff6dfa2002-03-03 23:06:00 +00001506 }
danielk1977517eb642004-06-07 10:00:31 +00001507
danielk1977517eb642004-06-07 10:00:31 +00001508 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1509 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001510 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001511 **
1512 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1513 ** suitable state to query for the column names and types to be used
1514 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001515 **
1516 ** A shared-cache write-lock is not required to write to the new table,
1517 ** as a schema-lock must have already been obtained to create it. Since
1518 ** a schema-lock excludes all other database users, the write-lock would
1519 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001520 */
1521 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001522 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001523 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001524
danielk19776ab3a2e2009-02-19 14:39:25 +00001525 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001526 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001527 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001528 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001529 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001530 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001531 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001532 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001533 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001534 if( pSelTab==0 ) return;
1535 assert( p->aCol==0 );
1536 p->nCol = pSelTab->nCol;
1537 p->aCol = pSelTab->aCol;
1538 pSelTab->nCol = 0;
1539 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001540 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001541 }
1542 }
drh4794f732004-11-05 17:17:50 +00001543
drh4794f732004-11-05 17:17:50 +00001544 /* Compute the complete text of the CREATE statement */
1545 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001546 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001547 }else{
drh1bd10f82008-12-10 21:19:56 +00001548 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001549 zStmt = sqlite3MPrintf(db,
1550 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1551 );
drh4794f732004-11-05 17:17:50 +00001552 }
1553
1554 /* A slot for the record has already been allocated in the
1555 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001556 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001557 */
1558 sqlite3NestedParse(pParse,
1559 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001560 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1561 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001562 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001563 zType,
1564 p->zName,
1565 p->zName,
drhb7654112008-01-12 12:48:07 +00001566 pParse->regRoot,
1567 zStmt,
1568 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001569 );
drh633e6d52008-07-28 19:34:53 +00001570 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001571 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001572
1573#ifndef SQLITE_OMIT_AUTOINCREMENT
1574 /* Check to see if we need to create an sqlite_sequence table for
1575 ** keeping track of autoincrement keys.
1576 */
drh7d10d5a2008-08-20 16:35:10 +00001577 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001578 Db *pDb = &db->aDb[iDb];
1579 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001580 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001581 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1582 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001583 );
1584 }
1585 }
1586#endif
drh4794f732004-11-05 17:17:50 +00001587
1588 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001589 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1590 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001591 }
drh17e9e292003-02-01 13:53:28 +00001592
drh2958a4e2004-11-12 03:56:15 +00001593
drh17e9e292003-02-01 13:53:28 +00001594 /* Add the table to the in-memory representation of the database.
1595 */
drh8af73d42009-05-13 22:58:28 +00001596 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001597 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001598 Schema *pSchema = p->pSchema;
drhea678832008-12-10 19:26:22 +00001599 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001600 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001601 if( pOld ){
1602 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001603 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001604 return;
1605 }
drh17e9e292003-02-01 13:53:28 +00001606 pParse->pNewTable = 0;
1607 db->nTable++;
1608 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001609
1610#ifndef SQLITE_OMIT_ALTERTABLE
1611 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001612 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001613 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001614 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001615 if( pCons->z==0 ){
1616 pCons = pEnd;
1617 }
drh1bd10f82008-12-10 21:19:56 +00001618 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001619 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001620 }
1621#endif
drh17e9e292003-02-01 13:53:28 +00001622 }
drh75897232000-05-29 14:26:00 +00001623}
1624
drhb7f91642004-10-31 02:22:47 +00001625#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001626/*
drha76b5df2002-02-23 02:32:10 +00001627** The parser calls this routine in order to create a new VIEW
1628*/
danielk19774adee202004-05-08 08:23:19 +00001629void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001630 Parse *pParse, /* The parsing context */
1631 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001632 Token *pName1, /* The token that holds the name of the view */
1633 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001634 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001635 int isTemp, /* TRUE for a TEMPORARY view */
1636 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001637){
drha76b5df2002-02-23 02:32:10 +00001638 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001639 int n;
drhb7916a72009-05-27 10:31:29 +00001640 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001641 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001642 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001643 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001644 int iDb;
drh17435752007-08-16 04:30:38 +00001645 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001646
drh7c3d64f2005-06-06 15:32:08 +00001647 if( pParse->nVar>0 ){
1648 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001649 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001650 return;
1651 }
drhfdd48a72006-09-11 23:45:48 +00001652 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001653 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001654 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001655 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001656 return;
1657 }
danielk1977ef2cb632004-05-29 02:37:19 +00001658 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001659 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001660 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001661 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001662 ){
drh633e6d52008-07-28 19:34:53 +00001663 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001664 return;
1665 }
drh174b6192002-12-03 02:22:52 +00001666
drh4b59ab52002-08-24 18:24:51 +00001667 /* Make a copy of the entire SELECT statement that defines the view.
1668 ** This will force all the Expr.token.z values to be dynamically
1669 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001670 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001671 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001672 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001673 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001674 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001675 return;
1676 }
drh17435752007-08-16 04:30:38 +00001677 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001678 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001679 }
drh4b59ab52002-08-24 18:24:51 +00001680
1681 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1682 ** the end.
1683 */
drha76b5df2002-02-23 02:32:10 +00001684 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001685 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001686 sEnd.z += sEnd.n;
1687 }
1688 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001689 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001690 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001691 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001692 sEnd.z = &z[n-1];
1693 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001694
danielk19774adee202004-05-08 08:23:19 +00001695 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001696 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001697 return;
drh417be792002-03-03 18:59:40 +00001698}
drhb7f91642004-10-31 02:22:47 +00001699#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001700
danielk1977fe3fcbe22006-06-12 12:08:45 +00001701#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001702/*
1703** The Table structure pTable is really a VIEW. Fill in the names of
1704** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001705** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001706*/
danielk19774adee202004-05-08 08:23:19 +00001707int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001708 Table *pSelTab; /* A fake table from which we get the result set */
1709 Select *pSel; /* Copy of the SELECT that implements the view */
1710 int nErr = 0; /* Number of errors encountered */
1711 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001712 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001713 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001714
1715 assert( pTable );
1716
danielk1977fe3fcbe22006-06-12 12:08:45 +00001717#ifndef SQLITE_OMIT_VIRTUALTABLE
1718 if( sqlite3VtabCallConnect(pParse, pTable) ){
1719 return SQLITE_ERROR;
1720 }
drh4cbdda92006-06-14 19:00:20 +00001721 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001722#endif
1723
1724#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001725 /* A positive nCol means the columns names for this view are
1726 ** already known.
1727 */
1728 if( pTable->nCol>0 ) return 0;
1729
1730 /* A negative nCol is a special marker meaning that we are currently
1731 ** trying to compute the column names. If we enter this routine with
1732 ** a negative nCol, it means two or more views form a loop, like this:
1733 **
1734 ** CREATE VIEW one AS SELECT * FROM two;
1735 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001736 **
drh768578e2009-05-12 00:40:12 +00001737 ** Actually, the error above is now caught prior to reaching this point.
1738 ** But the following test is still important as it does come up
1739 ** in the following:
1740 **
1741 ** CREATE TABLE main.ex1(a);
1742 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1743 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001744 */
1745 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001746 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001747 return 1;
1748 }
drh85c23c62005-08-20 03:03:04 +00001749 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001750
1751 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001752 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1753 ** "*" elements in the results set of the view and will assign cursors
1754 ** to the elements of the FROM clause. But we do not want these changes
1755 ** to be permanent. So the computation is done on a copy of the SELECT
1756 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001757 */
drh9b3187e2005-01-18 14:45:47 +00001758 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001759 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001760 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001761 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001762 n = pParse->nTab;
1763 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1764 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001765 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001766#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001767 xAuth = db->xAuth;
1768 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001769 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001770 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001771#else
drh7d10d5a2008-08-20 16:35:10 +00001772 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001773#endif
drhd9da78a2009-03-24 15:08:09 +00001774 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001775 pParse->nTab = n;
1776 if( pSelTab ){
1777 assert( pTable->aCol==0 );
1778 pTable->nCol = pSelTab->nCol;
1779 pTable->aCol = pSelTab->aCol;
1780 pSelTab->nCol = 0;
1781 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001782 sqlite3DeleteTable(db, pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001783 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001784 }else{
1785 pTable->nCol = 0;
1786 nErr++;
1787 }
drh633e6d52008-07-28 19:34:53 +00001788 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001789 } else {
drh417be792002-03-03 18:59:40 +00001790 nErr++;
1791 }
drhb7f91642004-10-31 02:22:47 +00001792#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001793 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001794}
1795#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001796
drhb7f91642004-10-31 02:22:47 +00001797#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001798/*
drh8bf8dc92003-05-17 17:35:10 +00001799** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001800*/
drh9bb575f2004-09-06 17:24:11 +00001801static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001802 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001803 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001804 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001805 Table *pTab = sqliteHashData(i);
1806 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00001807 sqliteDeleteColumnNames(db, pTab);
1808 pTab->aCol = 0;
1809 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00001810 }
1811 }
drh8bf8dc92003-05-17 17:35:10 +00001812 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001813}
drhb7f91642004-10-31 02:22:47 +00001814#else
1815# define sqliteViewResetAll(A,B)
1816#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001817
drh75897232000-05-29 14:26:00 +00001818/*
danielk1977a0bf2652004-11-04 14:30:04 +00001819** This function is called by the VDBE to adjust the internal schema
1820** used by SQLite when the btree layer moves a table root page. The
1821** root-page of a table or index in database iDb has changed from iFrom
1822** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001823**
1824** Ticket #1728: The symbol table might still contain information
1825** on tables and/or indices that are the process of being deleted.
1826** If you are unlucky, one of those deleted indices or tables might
1827** have the same rootpage number as the real table or index that is
1828** being moved. So we cannot stop searching after the first match
1829** because the first match might be for one of the deleted indices
1830** or tables and not the table/index that is actually being moved.
1831** We must continue looping until all tables and indices with
1832** rootpage==iFrom have been converted to have a rootpage of iTo
1833** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001834*/
1835#ifndef SQLITE_OMIT_AUTOVACUUM
1836void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1837 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001838 Hash *pHash;
1839
1840 pHash = &pDb->pSchema->tblHash;
1841 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001842 Table *pTab = sqliteHashData(pElem);
1843 if( pTab->tnum==iFrom ){
1844 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001845 }
1846 }
danielk1977da184232006-01-05 11:34:32 +00001847 pHash = &pDb->pSchema->idxHash;
1848 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001849 Index *pIdx = sqliteHashData(pElem);
1850 if( pIdx->tnum==iFrom ){
1851 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001852 }
1853 }
danielk1977a0bf2652004-11-04 14:30:04 +00001854}
1855#endif
1856
1857/*
1858** Write code to erase the table with root-page iTable from database iDb.
1859** Also write code to modify the sqlite_master table and internal schema
1860** if a root-page of another table is moved by the btree-layer whilst
1861** erasing iTable (this can happen with an auto-vacuum database).
1862*/
drh4e0cff62004-11-05 05:10:28 +00001863static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1864 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001865 int r1 = sqlite3GetTempReg(pParse);
1866 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001867 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001868#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001869 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001870 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001871 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001872 ** reflect this.
1873 **
drh0fa991b2009-03-21 16:19:26 +00001874 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001875 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1876 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001877 */
danielk197763e3e9f2004-11-05 09:19:27 +00001878 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001879 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1880 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001881#endif
drhb7654112008-01-12 12:48:07 +00001882 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001883}
1884
1885/*
1886** Write VDBE code to erase table pTab and all associated indices on disk.
1887** Code to update the sqlite_master tables and internal schema definitions
1888** in case a root-page belonging to another table is moved by the btree layer
1889** is also added (this can happen with an auto-vacuum database).
1890*/
drh4e0cff62004-11-05 05:10:28 +00001891static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001892#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001893 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001894 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1895 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001896 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001897 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001898 }
1899#else
1900 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1901 ** is not defined), then it is important to call OP_Destroy on the
1902 ** table and index root-pages in order, starting with the numerically
1903 ** largest root-page number. This guarantees that none of the root-pages
1904 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1905 ** following were coded:
1906 **
1907 ** OP_Destroy 4 0
1908 ** ...
1909 ** OP_Destroy 5 0
1910 **
1911 ** and root page 5 happened to be the largest root-page number in the
1912 ** database, then root page 5 would be moved to page 4 by the
1913 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1914 ** a free-list page.
1915 */
1916 int iTab = pTab->tnum;
1917 int iDestroyed = 0;
1918
1919 while( 1 ){
1920 Index *pIdx;
1921 int iLargest = 0;
1922
1923 if( iDestroyed==0 || iTab<iDestroyed ){
1924 iLargest = iTab;
1925 }
1926 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1927 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001928 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001929 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1930 iLargest = iIdx;
1931 }
1932 }
danielk1977da184232006-01-05 11:34:32 +00001933 if( iLargest==0 ){
1934 return;
1935 }else{
1936 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1937 destroyRootPage(pParse, iLargest, iDb);
1938 iDestroyed = iLargest;
1939 }
danielk1977a0bf2652004-11-04 14:30:04 +00001940 }
1941#endif
1942}
1943
1944/*
drh75897232000-05-29 14:26:00 +00001945** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001946** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001947*/
drha0733842005-12-29 01:11:36 +00001948void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001949 Table *pTab;
drh75897232000-05-29 14:26:00 +00001950 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001951 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001952 int iDb;
drh75897232000-05-29 14:26:00 +00001953
drh8af73d42009-05-13 22:58:28 +00001954 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001955 goto exit_drop_table;
1956 }
drh8af73d42009-05-13 22:58:28 +00001957 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00001958 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00001959 if( noErr ) db->suppressErr++;
drhca424112008-01-25 15:04:48 +00001960 pTab = sqlite3LocateTable(pParse, isView,
1961 pName->a[0].zName, pName->a[0].zDatabase);
drha7564662010-02-22 19:32:31 +00001962 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00001963
drha0733842005-12-29 01:11:36 +00001964 if( pTab==0 ){
drha0733842005-12-29 01:11:36 +00001965 goto exit_drop_table;
1966 }
danielk1977da184232006-01-05 11:34:32 +00001967 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001968 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00001969
1970 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1971 ** it is initialized.
1972 */
1973 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1974 goto exit_drop_table;
1975 }
drhe5f9c642003-01-13 23:27:31 +00001976#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001977 {
1978 int code;
danielk1977da184232006-01-05 11:34:32 +00001979 const char *zTab = SCHEMA_TABLE(iDb);
1980 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00001981 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00001982 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001983 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001984 }
drhe5f9c642003-01-13 23:27:31 +00001985 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001986 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001987 code = SQLITE_DROP_TEMP_VIEW;
1988 }else{
1989 code = SQLITE_DROP_VIEW;
1990 }
danielk19774b2688a2006-06-20 11:01:07 +00001991#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00001992 }else if( IsVirtual(pTab) ){
1993 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00001994 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00001995#endif
drhe5f9c642003-01-13 23:27:31 +00001996 }else{
danielk197753c0f742005-03-29 03:10:59 +00001997 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001998 code = SQLITE_DROP_TEMP_TABLE;
1999 }else{
2000 code = SQLITE_DROP_TABLE;
2001 }
2002 }
danielk1977f1a381e2006-06-16 08:01:02 +00002003 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002004 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002005 }
danielk1977a8858102004-05-28 12:11:21 +00002006 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2007 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002008 }
drhe5f9c642003-01-13 23:27:31 +00002009 }
2010#endif
drhc456e572008-08-11 18:44:58 +00002011 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002012 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002013 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002014 }
danielk1977576ec6b2005-01-21 11:55:25 +00002015
2016#ifndef SQLITE_OMIT_VIEW
2017 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2018 ** on a table.
2019 */
danielk1977a8858102004-05-28 12:11:21 +00002020 if( isView && pTab->pSelect==0 ){
2021 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2022 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002023 }
danielk1977a8858102004-05-28 12:11:21 +00002024 if( !isView && pTab->pSelect ){
2025 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2026 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002027 }
danielk1977576ec6b2005-01-21 11:55:25 +00002028#endif
drh75897232000-05-29 14:26:00 +00002029
drh1ccde152000-06-17 13:12:39 +00002030 /* Generate code to remove the table from the master table
2031 ** on disk.
2032 */
danielk19774adee202004-05-08 08:23:19 +00002033 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002034 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002035 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002036 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002037 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002038
danielk197720b1eaf2006-07-26 16:22:14 +00002039#ifndef SQLITE_OMIT_VIRTUALTABLE
2040 if( IsVirtual(pTab) ){
drh768578e2009-05-12 00:40:12 +00002041 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002042 }
2043#endif
dand66c8302009-09-28 14:49:01 +00002044 sqlite3FkDropTable(pParse, pName, pTab);
danielk197720b1eaf2006-07-26 16:22:14 +00002045
danielk19778e227872004-06-07 07:52:17 +00002046 /* Drop all triggers associated with the table being dropped. Code
2047 ** is generated to remove entries from sqlite_master and/or
2048 ** sqlite_temp_master if required.
2049 */
danielk19772f886d12009-02-28 10:47:41 +00002050 pTrigger = sqlite3TriggerList(pParse, pTab);
drhe0bc4042002-06-25 01:09:11 +00002051 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002052 assert( pTrigger->pSchema==pTab->pSchema ||
2053 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002054 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002055 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002056 }
drh8bf8dc92003-05-17 17:35:10 +00002057
danielk19774d36b812004-11-19 07:07:30 +00002058#ifndef SQLITE_OMIT_AUTOINCREMENT
2059 /* Remove any entries of the sqlite_sequence table associated with
2060 ** the table being dropped. This is done before the table is dropped
2061 ** at the btree level, in case the sqlite_sequence table needs to
2062 ** move as a result of the drop (can happen in auto-vacuum mode).
2063 */
drh7d10d5a2008-08-20 16:35:10 +00002064 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002065 sqlite3NestedParse(pParse,
2066 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2067 pDb->zName, pTab->zName
2068 );
2069 }
2070#endif
2071
danielk19778e227872004-06-07 07:52:17 +00002072 /* Drop all SQLITE_MASTER table and index entries that refer to the
2073 ** table. The program name loops through the master table and deletes
2074 ** every row that refers to a table of the same name as the one being
2075 ** dropped. Triggers are handled seperately because a trigger can be
2076 ** created in the temp database that refers to a table in another
2077 ** database.
2078 */
drhf1974842004-11-05 03:56:00 +00002079 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002080 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002081 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002082
2083 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2084 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2085 sqlite3NestedParse(pParse,
2086 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2087 );
2088 }
2089
danielk19774b2688a2006-06-20 11:01:07 +00002090 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002091 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002092 }
drh2958a4e2004-11-12 03:56:15 +00002093
danielk1977a21c6b62005-01-24 10:25:59 +00002094 /* Remove the table entry from SQLite's internal schema and modify
2095 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002096 */
drh4cbdda92006-06-14 19:00:20 +00002097 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002098 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002099 }
drh66a51672008-01-03 00:01:23 +00002100 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002101 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002102 }
drhd24cc422003-03-27 12:51:24 +00002103 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002104
2105exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002106 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002107}
2108
2109/*
drhc2eef3b2002-08-31 18:53:06 +00002110** This routine is called to create a new foreign key on the table
2111** currently under construction. pFromCol determines which columns
2112** in the current table point to the foreign key. If pFromCol==0 then
2113** connect the key to the last column inserted. pTo is the name of
2114** the table referred to. pToCol is a list of tables in the other
2115** pTo table that the foreign key points to. flags contains all
2116** information about the conflict resolution algorithms specified
2117** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2118**
2119** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002120** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002121**
2122** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002123** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002124*/
danielk19774adee202004-05-08 08:23:19 +00002125void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002126 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002127 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002128 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002129 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002130 int flags /* Conflict resolution algorithms. */
2131){
danielk197718576932008-08-06 13:47:40 +00002132 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002133#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002134 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002135 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002136 Table *p = pParse->pNewTable;
2137 int nByte;
2138 int i;
2139 int nCol;
2140 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002141
2142 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002143 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002144 if( pFromCol==0 ){
2145 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002146 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002147 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002148 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002149 " should reference only one column of table %T",
2150 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002151 goto fk_end;
2152 }
2153 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002154 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002155 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002156 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002157 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002158 goto fk_end;
2159 }else{
danielk19770202b292004-06-09 09:55:16 +00002160 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002161 }
drhe61922a2009-05-02 13:29:37 +00002162 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002163 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002164 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002165 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002166 }
2167 }
drh633e6d52008-07-28 19:34:53 +00002168 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002169 if( pFKey==0 ){
2170 goto fk_end;
2171 }
drhc2eef3b2002-08-31 18:53:06 +00002172 pFKey->pFrom = p;
2173 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002174 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002175 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002176 memcpy(z, pTo->z, pTo->n);
2177 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002178 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002179 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002180 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002181 if( pFromCol==0 ){
2182 pFKey->aCol[0].iFrom = p->nCol-1;
2183 }else{
2184 for(i=0; i<nCol; i++){
2185 int j;
2186 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002187 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002188 pFKey->aCol[i].iFrom = j;
2189 break;
2190 }
2191 }
2192 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002193 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002194 "unknown column \"%s\" in foreign key definition",
2195 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002196 goto fk_end;
2197 }
2198 }
2199 }
2200 if( pToCol ){
2201 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002202 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002203 pFKey->aCol[i].zCol = z;
2204 memcpy(z, pToCol->a[i].zName, n);
2205 z[n] = 0;
2206 z += n+1;
2207 }
2208 }
2209 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002210 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2211 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002212
dan1da40a32009-09-19 17:00:31 +00002213 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2214 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2215 );
danf59c5ca2009-09-22 16:55:38 +00002216 if( pNextTo==pFKey ){
2217 db->mallocFailed = 1;
2218 goto fk_end;
2219 }
dan1da40a32009-09-19 17:00:31 +00002220 if( pNextTo ){
2221 assert( pNextTo->pPrevTo==0 );
2222 pFKey->pNextTo = pNextTo;
2223 pNextTo->pPrevTo = pFKey;
2224 }
2225
drhc2eef3b2002-08-31 18:53:06 +00002226 /* Link the foreign key to the table as the last step.
2227 */
2228 p->pFKey = pFKey;
2229 pFKey = 0;
2230
2231fk_end:
drh633e6d52008-07-28 19:34:53 +00002232 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002233#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002234 sqlite3ExprListDelete(db, pFromCol);
2235 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002236}
2237
2238/*
2239** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2240** clause is seen as part of a foreign key definition. The isDeferred
2241** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2242** The behavior of the most recently created foreign key is adjusted
2243** accordingly.
2244*/
danielk19774adee202004-05-08 08:23:19 +00002245void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002246#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002247 Table *pTab;
2248 FKey *pFKey;
2249 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002250 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002251 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002252#endif
drhc2eef3b2002-08-31 18:53:06 +00002253}
2254
2255/*
drh063336a2004-11-05 20:58:39 +00002256** Generate code that will erase and refill index *pIdx. This is
2257** used to initialize a newly created index or to recompute the
2258** content of an index in response to a REINDEX command.
2259**
2260** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002261** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002262** root page number of the index. If memRootPage is negative, then
2263** the index already exists and must be cleared before being refilled and
2264** the root page number of the index is taken from pIndex->tnum.
2265*/
2266static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2267 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002268 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2269 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drh063336a2004-11-05 20:58:39 +00002270 int addr1; /* Address of top of loop */
2271 int tnum; /* Root page of index */
2272 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002273 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002274 int regIdxKey; /* Registers containing the index key */
2275 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002276 sqlite3 *db = pParse->db; /* The database connection */
2277 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002278
danielk19771d54df82004-11-23 15:41:16 +00002279#ifndef SQLITE_OMIT_AUTHORIZATION
2280 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002281 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002282 return;
2283 }
2284#endif
2285
danielk1977c00da102006-01-07 13:21:04 +00002286 /* Require a write-lock on the table to perform this operation */
2287 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2288
drh063336a2004-11-05 20:58:39 +00002289 v = sqlite3GetVdbe(pParse);
2290 if( v==0 ) return;
2291 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002292 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002293 }else{
2294 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002295 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002296 }
danielk1977b3bf5562006-01-10 17:58:23 +00002297 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002298 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002299 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002300 if( memRootPage>=0 ){
2301 sqlite3VdbeChangeP5(v, 1);
2302 }
danielk1977c00da102006-01-07 13:21:04 +00002303 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002304 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002305 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002306 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002307 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002308 const int regRowid = regIdxKey + pIndex->nColumn;
2309 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2310 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002311
danielk1977de630352009-05-04 11:42:29 +00002312 /* The registers accessed by the OP_IsUnique opcode were allocated
2313 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2314 ** call above. Just before that function was freed they were released
2315 ** (made available to the compiler for reuse) using
2316 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2317 ** opcode use the values stored within seems dangerous. However, since
2318 ** we can be sure that no other temp registers have been allocated
2319 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2320 */
2321 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
dane0af83a2009-09-08 19:15:01 +00002322 sqlite3HaltConstraint(
2323 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002324 }
drh2d401ab2008-01-10 23:50:11 +00002325 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
danielk1977de630352009-05-04 11:42:29 +00002326 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002327 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002328 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002329 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002330 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2331 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002332}
2333
2334/*
drh23bf66d2004-12-14 03:34:34 +00002335** Create a new index for an SQL table. pName1.pName2 is the name of the index
2336** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002337** be NULL for a primary key or an index that is created to satisfy a
2338** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002339** as the table to be indexed. pParse->pNewTable is a table that is
2340** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002341**
drh382c0242001-10-06 16:33:02 +00002342** pList is a list of columns to be indexed. pList will be NULL if this
2343** is a primary key or unique-constraint on the most recent column added
2344** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002345**
2346** If the index is created successfully, return a pointer to the new Index
2347** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2348** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002349*/
dan1da40a32009-09-19 17:00:31 +00002350Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002351 Parse *pParse, /* All information about this parse */
2352 Token *pName1, /* First part of index name. May be NULL */
2353 Token *pName2, /* Second part of index name. May be NULL */
2354 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002355 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002356 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002357 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002358 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002359 int sortOrder, /* Sort order of primary key when pList==NULL */
2360 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002361){
dan1da40a32009-09-19 17:00:31 +00002362 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002363 Table *pTab = 0; /* Table to be indexed */
2364 Index *pIndex = 0; /* The index to be created */
2365 char *zName = 0; /* Name of the index */
2366 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002367 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002368 Token nullId; /* Fake token for an empty ID list */
2369 DbFixer sFix; /* For assigning database names to pTable */
2370 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002371 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002372 Db *pDb; /* The specific table containing the indexed database */
2373 int iDb; /* Index of the database that is being written */
2374 Token *pName = 0; /* Unqualified name of the index to create */
2375 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002376 int nCol;
2377 int nExtra = 0;
2378 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002379
drhd3001712009-05-12 17:46:53 +00002380 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
drh8af73d42009-05-13 22:58:28 +00002381 assert( pParse->nErr==0 ); /* Never called with prior errors */
2382 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002383 goto exit_create_index;
2384 }
2385 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002386 goto exit_create_index;
2387 }
drhdaffd0e2001-04-11 14:28:42 +00002388
drh75897232000-05-29 14:26:00 +00002389 /*
2390 ** Find the table that is to be indexed. Return early if not found.
2391 */
danielk1977cbb18d22004-05-28 11:37:27 +00002392 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002393
2394 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002395 ** to search for the table. 'Fix' the table name to this db
2396 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002397 */
2398 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002399 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002400 if( iDb<0 ) goto exit_create_index;
2401
danielk197753c0f742005-03-29 03:10:59 +00002402#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002403 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002404 ** is a temp table. If so, set the database to 1. Do not do this
2405 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002406 */
danielk1977fe910332007-12-02 11:46:34 +00002407 if( !db->init.busy ){
2408 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002409 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002410 iDb = 1;
2411 }
danielk1977ef2cb632004-05-29 02:37:19 +00002412 }
danielk197753c0f742005-03-29 03:10:59 +00002413#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002414
2415 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2416 sqlite3FixSrcList(&sFix, pTblName)
2417 ){
drh85c23c62005-08-20 03:03:04 +00002418 /* Because the parser constructs pTblName from a single identifier,
2419 ** sqlite3FixSrcList can never fail. */
2420 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002421 }
drhca424112008-01-25 15:04:48 +00002422 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002423 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002424 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002425 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002426 }else{
drhe3c41372001-09-17 20:25:58 +00002427 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002428 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002429 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002430 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002431 }
drhfdd6e852005-12-16 01:06:16 +00002432 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002433
drhd3001712009-05-12 17:46:53 +00002434 assert( pTab!=0 );
2435 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002436 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2437 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002438 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002439 goto exit_create_index;
2440 }
danielk1977576ec6b2005-01-21 11:55:25 +00002441#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002442 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002443 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002444 goto exit_create_index;
2445 }
danielk1977576ec6b2005-01-21 11:55:25 +00002446#endif
danielk19775ee9d692006-06-21 12:36:25 +00002447#ifndef SQLITE_OMIT_VIRTUALTABLE
2448 if( IsVirtual(pTab) ){
2449 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2450 goto exit_create_index;
2451 }
2452#endif
drh75897232000-05-29 14:26:00 +00002453
2454 /*
2455 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002456 ** index or table with the same name.
2457 **
2458 ** Exception: If we are reading the names of permanent indices from the
2459 ** sqlite_master table (because some other process changed the schema) and
2460 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002461 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002462 **
2463 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002464 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2465 ** own name.
drh75897232000-05-29 14:26:00 +00002466 */
danielk1977d8123362004-06-12 09:25:12 +00002467 if( pName ){
drh17435752007-08-16 04:30:38 +00002468 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002469 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002470 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002471 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002472 }
danielk1977d8123362004-06-12 09:25:12 +00002473 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002474 if( sqlite3FindTable(db, zName, 0)!=0 ){
2475 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2476 goto exit_create_index;
2477 }
2478 }
danielk197759a33f92007-03-17 10:26:59 +00002479 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2480 if( !ifNotExist ){
2481 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002482 }
danielk197759a33f92007-03-17 10:26:59 +00002483 goto exit_create_index;
2484 }
danielk1977a21c6b62005-01-24 10:25:59 +00002485 }else{
drhadbca9c2001-09-27 15:11:53 +00002486 int n;
2487 Index *pLoop;
2488 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002489 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002490 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002491 goto exit_create_index;
2492 }
drh75897232000-05-29 14:26:00 +00002493 }
2494
drhe5f9c642003-01-13 23:27:31 +00002495 /* Check for authorization to create an index.
2496 */
2497#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002498 {
drhfdd6e852005-12-16 01:06:16 +00002499 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002500 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002501 goto exit_create_index;
2502 }
2503 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002504 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002505 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002506 goto exit_create_index;
2507 }
drhe5f9c642003-01-13 23:27:31 +00002508 }
2509#endif
2510
drh75897232000-05-29 14:26:00 +00002511 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002512 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002513 ** So create a fake list to simulate this.
2514 */
2515 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002516 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002517 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002518 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002519 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002520 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002521 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002522 }
2523
danielk1977b3bf5562006-01-10 17:58:23 +00002524 /* Figure out how many bytes of space are required to store explicitly
2525 ** specified collation sequence names.
2526 */
2527 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002528 Expr *pExpr = pList->a[i].pExpr;
2529 if( pExpr ){
2530 CollSeq *pColl = pExpr->pColl;
2531 /* Either pColl!=0 or there was an OOM failure. But if an OOM
2532 ** failure we have quit before reaching this point. */
2533 if( ALWAYS(pColl) ){
2534 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2535 }
danielk1977b3bf5562006-01-10 17:58:23 +00002536 }
2537 }
2538
drh75897232000-05-29 14:26:00 +00002539 /*
2540 ** Allocate the index structure.
2541 */
drhea678832008-12-10 19:26:22 +00002542 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002543 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002544 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002545 sizeof(Index) + /* Index structure */
2546 sizeof(int)*nCol + /* Index.aiColumn */
2547 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2548 sizeof(char *)*nCol + /* Index.azColl */
2549 sizeof(u8)*nCol + /* Index.aSortOrder */
2550 nName + 1 + /* Index.zName */
2551 nExtra /* Collation sequence names */
2552 );
drh17435752007-08-16 04:30:38 +00002553 if( db->mallocFailed ){
2554 goto exit_create_index;
2555 }
drh78aecb72006-02-10 18:08:09 +00002556 pIndex->azColl = (char**)(&pIndex[1]);
2557 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002558 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002559 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002560 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2561 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002562 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002563 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002564 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002565 pIndex->onError = (u8)onError;
2566 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002567 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002568
drhfdd6e852005-12-16 01:06:16 +00002569 /* Check to see if we should honor DESC requests on index columns
2570 */
danielk1977da184232006-01-05 11:34:32 +00002571 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002572 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002573 }else{
2574 sortOrderMask = 0; /* Ignore DESC */
2575 }
2576
drh1ccde152000-06-17 13:12:39 +00002577 /* Scan the names of the columns of the table to be indexed and
2578 ** load the column indices into the Index structure. Report an error
2579 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002580 **
2581 ** TODO: Add a test to make sure that the same column is not named
2582 ** more than once within the same index. Only the first instance of
2583 ** the column will ever be used by the optimizer. Note that using the
2584 ** same column more than once cannot be an error because that would
2585 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002586 */
drhfdd6e852005-12-16 01:06:16 +00002587 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2588 const char *zColName = pListItem->zName;
2589 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002590 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002591 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002592
drhfdd6e852005-12-16 01:06:16 +00002593 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2594 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002595 }
2596 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002597 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002598 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00002599 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00002600 goto exit_create_index;
2601 }
drh967e8b72000-06-21 13:59:10 +00002602 pIndex->aiColumn[i] = j;
drhd3001712009-05-12 17:46:53 +00002603 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
2604 ** the way the "idxlist" non-terminal is constructed by the parser,
2605 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2606 ** must exist or else there must have been an OOM error. But if there
2607 ** was an OOM error, we would never reach this point. */
2608 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2609 int nColl;
2610 zColl = pListItem->pExpr->pColl->zName;
2611 nColl = sqlite3Strlen30(zColl) + 1;
2612 assert( nExtra>=nColl );
2613 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002614 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002615 zExtra += nColl;
2616 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002617 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002618 zColl = pTab->aCol[j].zColl;
2619 if( !zColl ){
2620 zColl = db->pDfltColl->zName;
2621 }
danielk19770202b292004-06-09 09:55:16 +00002622 }
drhb7f24de2009-05-13 17:35:23 +00002623 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002624 goto exit_create_index;
2625 }
danielk1977b3bf5562006-01-10 17:58:23 +00002626 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002627 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002628 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002629 }
drh51147ba2005-07-23 22:59:55 +00002630 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002631
danielk1977d8123362004-06-12 09:25:12 +00002632 if( pTab==pParse->pNewTable ){
2633 /* This routine has been called to create an automatic index as a
2634 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2635 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2636 ** i.e. one of:
2637 **
2638 ** CREATE TABLE t(x PRIMARY KEY, y);
2639 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2640 **
2641 ** Either way, check to see if the table already has such an index. If
2642 ** so, don't bother creating this one. This only applies to
2643 ** automatically created indices. Users can do as they wish with
2644 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002645 **
2646 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2647 ** (and thus suppressing the second one) even if they have different
2648 ** sort orders.
2649 **
2650 ** If there are different collating sequences or if the columns of
2651 ** the constraint occur in different orders, then the constraints are
2652 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002653 */
2654 Index *pIdx;
2655 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2656 int k;
2657 assert( pIdx->onError!=OE_None );
2658 assert( pIdx->autoIndex );
2659 assert( pIndex->onError!=OE_None );
2660
2661 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2662 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002663 const char *z1;
2664 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002665 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002666 z1 = pIdx->azColl[k];
2667 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002668 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002669 }
2670 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002671 if( pIdx->onError!=pIndex->onError ){
2672 /* This constraint creates the same index as a previous
2673 ** constraint specified somewhere in the CREATE TABLE statement.
2674 ** However the ON CONFLICT clauses are different. If both this
2675 ** constraint and the previous equivalent constraint have explicit
2676 ** ON CONFLICT clauses this is an error. Otherwise, use the
2677 ** explicitly specified behaviour for the index.
2678 */
2679 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2680 sqlite3ErrorMsg(pParse,
2681 "conflicting ON CONFLICT clauses specified", 0);
2682 }
2683 if( pIdx->onError==OE_Default ){
2684 pIdx->onError = pIndex->onError;
2685 }
2686 }
danielk1977d8123362004-06-12 09:25:12 +00002687 goto exit_create_index;
2688 }
2689 }
2690 }
2691
drh75897232000-05-29 14:26:00 +00002692 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002693 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002694 */
drh234c39d2004-07-24 03:30:47 +00002695 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002696 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002697 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002698 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002699 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002700 if( p ){
2701 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002702 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002703 goto exit_create_index;
2704 }
drh5e00f6c2001-09-13 13:46:56 +00002705 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002706 if( pTblName!=0 ){
2707 pIndex->tnum = db->init.newTnum;
2708 }
drhd78eeee2001-09-13 16:18:53 +00002709 }
2710
drh1d85d932004-02-14 23:05:52 +00002711 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002712 ** involves writing the index into the master table and filling in the
2713 ** index with the current table contents.
2714 **
drh1d85d932004-02-14 23:05:52 +00002715 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2716 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002717 ** CREATE INDEX statements are read out of the master table. In
2718 ** the latter case the index already exists on disk, which is why
2719 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002720 **
danielk1977cbb18d22004-05-28 11:37:27 +00002721 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002722 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2723 ** has just been created, it contains no data and the index initialization
2724 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002725 */
drhd3001712009-05-12 17:46:53 +00002726 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002727 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002728 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002729 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002730
danielk19774adee202004-05-08 08:23:19 +00002731 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002732 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002733
drhfdd6e852005-12-16 01:06:16 +00002734
drh063336a2004-11-05 20:58:39 +00002735 /* Create the rootpage for the index
2736 */
drhaee128d2005-02-14 20:48:18 +00002737 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002738 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002739
2740 /* Gather the complete text of the CREATE INDEX statement into
2741 ** the zStmt variable
2742 */
drhd3001712009-05-12 17:46:53 +00002743 if( pStart ){
2744 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002745 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002746 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002747 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002748 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002749 pName->z);
2750 }else{
2751 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002752 /* zStmt = sqlite3MPrintf(""); */
2753 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002754 }
drh063336a2004-11-05 20:58:39 +00002755
2756 /* Add an entry in sqlite_master for this index
2757 */
2758 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002759 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002760 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2761 pIndex->zName,
2762 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002763 iMem,
drh063336a2004-11-05 20:58:39 +00002764 zStmt
2765 );
drh633e6d52008-07-28 19:34:53 +00002766 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002767
danielk1977a21c6b62005-01-24 10:25:59 +00002768 /* Fill the index with data and reparse the schema. Code an OP_Expire
2769 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002770 */
danielk1977cbb18d22004-05-28 11:37:27 +00002771 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002772 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002773 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002774 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
dan39f1bcb2010-09-29 07:16:46 +00002775 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
2776 P4_DYNAMIC);
drh66a51672008-01-03 00:01:23 +00002777 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002778 }
drh75897232000-05-29 14:26:00 +00002779 }
2780
danielk1977d8123362004-06-12 09:25:12 +00002781 /* When adding an index to the list of indices for a table, make
2782 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002783 ** OE_Ignore. This is necessary for the correct constraint check
2784 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2785 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002786 */
drh234c39d2004-07-24 03:30:47 +00002787 if( db->init.busy || pTblName==0 ){
2788 if( onError!=OE_Replace || pTab->pIndex==0
2789 || pTab->pIndex->onError==OE_Replace){
2790 pIndex->pNext = pTab->pIndex;
2791 pTab->pIndex = pIndex;
2792 }else{
2793 Index *pOther = pTab->pIndex;
2794 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2795 pOther = pOther->pNext;
2796 }
2797 pIndex->pNext = pOther->pNext;
2798 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002799 }
dan1da40a32009-09-19 17:00:31 +00002800 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00002801 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002802 }
danielk1977d8123362004-06-12 09:25:12 +00002803
drh75897232000-05-29 14:26:00 +00002804 /* Clean up before exiting */
2805exit_create_index:
drh956bc922004-07-24 17:38:29 +00002806 if( pIndex ){
drhb9755982010-07-24 16:34:37 +00002807 sqlite3DbFree(db, pIndex->zColAff);
danielk1977cb9d8d82009-03-18 18:43:36 +00002808 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002809 }
drh633e6d52008-07-28 19:34:53 +00002810 sqlite3ExprListDelete(db, pList);
2811 sqlite3SrcListDelete(db, pTblName);
2812 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00002813 return pRet;
drh75897232000-05-29 14:26:00 +00002814}
2815
2816/*
drh51147ba2005-07-23 22:59:55 +00002817** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002818** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002819**
2820** aiRowEst[0] is suppose to contain the number of elements in the index.
2821** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2822** number of rows in the table that match any particular value of the
2823** first column of the index. aiRowEst[2] is an estimate of the number
2824** of rows that match any particular combiniation of the first 2 columns
2825** of the index. And so forth. It must always be the case that
2826*
2827** aiRowEst[N]<=aiRowEst[N-1]
2828** aiRowEst[N]>=1
2829**
2830** Apart from that, we have little to go on besides intuition as to
2831** how aiRowEst[] should be initialized. The numbers generated here
2832** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002833*/
2834void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002835 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002836 int i;
drh15564052010-09-25 22:32:56 +00002837 unsigned n;
drh28c4cf42005-07-27 20:41:43 +00002838 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00002839 a[0] = pIdx->pTable->nRowEst;
2840 if( a[0]<10 ) a[0] = 10;
2841 n = 10;
2842 for(i=1; i<=pIdx->nColumn; i++){
2843 a[i] = n;
2844 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00002845 }
2846 if( pIdx->onError!=OE_None ){
2847 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002848 }
2849}
2850
2851/*
drh74e24cd2002-01-09 03:19:59 +00002852** This routine will drop an existing named index. This routine
2853** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002854*/
drh4d91a702006-01-04 15:54:36 +00002855void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002856 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002857 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002858 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002859 int iDb;
drh75897232000-05-29 14:26:00 +00002860
drh8af73d42009-05-13 22:58:28 +00002861 assert( pParse->nErr==0 ); /* Never called with prior errors */
2862 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002863 goto exit_drop_index;
2864 }
drhd24cc422003-03-27 12:51:24 +00002865 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002866 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2867 goto exit_drop_index;
2868 }
danielk19774adee202004-05-08 08:23:19 +00002869 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002870 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002871 if( !ifExists ){
2872 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2873 }
drha6ecd332004-06-10 00:29:09 +00002874 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002875 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002876 }
drh485b39b2002-07-13 03:11:52 +00002877 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002878 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002879 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002880 goto exit_drop_index;
2881 }
danielk1977da184232006-01-05 11:34:32 +00002882 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002883#ifndef SQLITE_OMIT_AUTHORIZATION
2884 {
2885 int code = SQLITE_DROP_INDEX;
2886 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002887 const char *zDb = db->aDb[iDb].zName;
2888 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002889 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002890 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002891 }
danielk1977da184232006-01-05 11:34:32 +00002892 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002893 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002894 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002895 }
drhed6c8672003-01-12 18:02:16 +00002896 }
drhe5f9c642003-01-13 23:27:31 +00002897#endif
drh75897232000-05-29 14:26:00 +00002898
2899 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002900 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002901 if( v ){
drh77658e22007-12-04 16:54:52 +00002902 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002903 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00002904 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drhb17131a2004-11-05 22:18:49 +00002905 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2906 pIndex->zName
2907 );
danielk1977006015d2008-04-11 17:11:26 +00002908 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2909 sqlite3NestedParse(pParse,
2910 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2911 db->aDb[iDb].zName, pIndex->zName
2912 );
2913 }
drh9cbf3422008-01-17 16:22:13 +00002914 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002915 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002916 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002917 }
2918
drhd24cc422003-03-27 12:51:24 +00002919exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002920 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002921}
2922
2923/*
drhcf643722007-03-27 13:36:37 +00002924** pArray is a pointer to an array of objects. Each object in the
2925** array is szEntry bytes in size. This routine allocates a new
2926** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002927**
drhcf643722007-03-27 13:36:37 +00002928** *pnEntry is the number of entries already in use. *pnAlloc is
2929** the previously allocated size of the array. initSize is the
2930** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002931**
drhcf643722007-03-27 13:36:37 +00002932** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002933**
drhcf643722007-03-27 13:36:37 +00002934** This routine returns a pointer to the array of objects. This
2935** might be the same as the pArray parameter or it might be a different
2936** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002937*/
drhcf643722007-03-27 13:36:37 +00002938void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002939 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002940 void *pArray, /* Array of objects. Might be reallocated */
2941 int szEntry, /* Size of each object in the array */
2942 int initSize, /* Suggested initial allocation, in elements */
2943 int *pnEntry, /* Number of objects currently in use */
2944 int *pnAlloc, /* Current size of the allocation, in elements */
2945 int *pIdx /* Write the index of a new slot here */
2946){
2947 char *z;
2948 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002949 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002950 int newSize;
drhcf643722007-03-27 13:36:37 +00002951 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002952 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002953 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002954 *pIdx = -1;
2955 return pArray;
drh13449892005-09-07 21:22:45 +00002956 }
drh6a1e0712008-12-05 15:24:15 +00002957 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002958 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002959 }
drhcf643722007-03-27 13:36:37 +00002960 z = (char*)pArray;
2961 memset(&z[*pnEntry * szEntry], 0, szEntry);
2962 *pIdx = *pnEntry;
2963 ++*pnEntry;
2964 return pArray;
drh13449892005-09-07 21:22:45 +00002965}
2966
2967/*
drh75897232000-05-29 14:26:00 +00002968** Append a new element to the given IdList. Create a new IdList if
2969** need be.
drhdaffd0e2001-04-11 14:28:42 +00002970**
2971** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002972*/
drh17435752007-08-16 04:30:38 +00002973IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002974 int i;
drh75897232000-05-29 14:26:00 +00002975 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002976 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002977 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002978 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002979 }
drhcf643722007-03-27 13:36:37 +00002980 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002981 db,
drhcf643722007-03-27 13:36:37 +00002982 pList->a,
2983 sizeof(pList->a[0]),
2984 5,
2985 &pList->nId,
2986 &pList->nAlloc,
2987 &i
2988 );
drh13449892005-09-07 21:22:45 +00002989 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002990 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002991 return 0;
drh75897232000-05-29 14:26:00 +00002992 }
drh17435752007-08-16 04:30:38 +00002993 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002994 return pList;
2995}
2996
2997/*
drhfe05af82005-07-21 03:14:59 +00002998** Delete an IdList.
2999*/
drh633e6d52008-07-28 19:34:53 +00003000void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003001 int i;
3002 if( pList==0 ) return;
3003 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003004 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003005 }
drh633e6d52008-07-28 19:34:53 +00003006 sqlite3DbFree(db, pList->a);
3007 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003008}
3009
3010/*
3011** Return the index in pList of the identifier named zId. Return -1
3012** if not found.
3013*/
3014int sqlite3IdListIndex(IdList *pList, const char *zName){
3015 int i;
3016 if( pList==0 ) return -1;
3017 for(i=0; i<pList->nId; i++){
3018 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3019 }
3020 return -1;
3021}
3022
3023/*
drha78c22c2008-11-11 18:28:58 +00003024** Expand the space allocated for the given SrcList object by
3025** creating nExtra new slots beginning at iStart. iStart is zero based.
3026** New slots are zeroed.
3027**
3028** For example, suppose a SrcList initially contains two entries: A,B.
3029** To append 3 new entries onto the end, do this:
3030**
3031** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3032**
3033** After the call above it would contain: A, B, nil, nil, nil.
3034** If the iStart argument had been 1 instead of 2, then the result
3035** would have been: A, nil, nil, nil, B. To prepend the new slots,
3036** the iStart value would be 0. The result then would
3037** be: nil, nil, nil, A, B.
3038**
3039** If a memory allocation fails the SrcList is unchanged. The
3040** db->mallocFailed flag will be set to true.
3041*/
3042SrcList *sqlite3SrcListEnlarge(
3043 sqlite3 *db, /* Database connection to notify of OOM errors */
3044 SrcList *pSrc, /* The SrcList to be enlarged */
3045 int nExtra, /* Number of new slots to add to pSrc->a[] */
3046 int iStart /* Index in pSrc->a[] of first new slot */
3047){
3048 int i;
3049
3050 /* Sanity checking on calling parameters */
3051 assert( iStart>=0 );
3052 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003053 assert( pSrc!=0 );
3054 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003055
3056 /* Allocate additional space if needed */
3057 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3058 SrcList *pNew;
3059 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003060 int nGot;
drha78c22c2008-11-11 18:28:58 +00003061 pNew = sqlite3DbRealloc(db, pSrc,
3062 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3063 if( pNew==0 ){
3064 assert( db->mallocFailed );
3065 return pSrc;
3066 }
3067 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003068 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003069 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003070 }
3071
3072 /* Move existing slots that come after the newly inserted slots
3073 ** out of the way */
3074 for(i=pSrc->nSrc-1; i>=iStart; i--){
3075 pSrc->a[i+nExtra] = pSrc->a[i];
3076 }
shane18e526c2008-12-10 22:30:24 +00003077 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003078
3079 /* Zero the newly allocated slots */
3080 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3081 for(i=iStart; i<iStart+nExtra; i++){
3082 pSrc->a[i].iCursor = -1;
3083 }
3084
3085 /* Return a pointer to the enlarged SrcList */
3086 return pSrc;
3087}
3088
3089
3090/*
drhad3cab52002-05-24 02:04:32 +00003091** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003092** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003093**
drha78c22c2008-11-11 18:28:58 +00003094** A SrcList is returned, or NULL if there is an OOM error. The returned
3095** SrcList might be the same as the SrcList that was input or it might be
3096** a new one. If an OOM error does occurs, then the prior value of pList
3097** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003098**
3099** If pDatabase is not null, it means that the table has an optional
3100** database name prefix. Like this: "database.table". The pDatabase
3101** points to the table name and the pTable points to the database name.
3102** The SrcList.a[].zName field is filled with the table name which might
3103** come from pTable (if pDatabase is NULL) or from pDatabase.
3104** SrcList.a[].zDatabase is filled with the database name from pTable,
3105** or with NULL if no database is specified.
3106**
3107** In other words, if call like this:
3108**
drh17435752007-08-16 04:30:38 +00003109** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003110**
3111** Then B is a table name and the database name is unspecified. If called
3112** like this:
3113**
drh17435752007-08-16 04:30:38 +00003114** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003115**
drhd3001712009-05-12 17:46:53 +00003116** Then C is the table name and B is the database name. If C is defined
3117** then so is B. In other words, we never have a case where:
3118**
3119** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003120**
3121** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3122** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003123*/
drh17435752007-08-16 04:30:38 +00003124SrcList *sqlite3SrcListAppend(
3125 sqlite3 *db, /* Connection to notify of malloc failures */
3126 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3127 Token *pTable, /* Table to append */
3128 Token *pDatabase /* Database of the table */
3129){
drha99db3b2004-06-19 14:49:12 +00003130 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003131 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003132 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003133 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003134 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003135 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003136 }
drha78c22c2008-11-11 18:28:58 +00003137 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3138 if( db->mallocFailed ){
3139 sqlite3SrcListDelete(db, pList);
3140 return 0;
drhad3cab52002-05-24 02:04:32 +00003141 }
drha78c22c2008-11-11 18:28:58 +00003142 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003143 if( pDatabase && pDatabase->z==0 ){
3144 pDatabase = 0;
3145 }
drhd3001712009-05-12 17:46:53 +00003146 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003147 Token *pTemp = pDatabase;
3148 pDatabase = pTable;
3149 pTable = pTemp;
3150 }
drh17435752007-08-16 04:30:38 +00003151 pItem->zName = sqlite3NameFromToken(db, pTable);
3152 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003153 return pList;
3154}
3155
3156/*
drhdfe88ec2008-11-03 20:55:06 +00003157** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003158*/
danielk19774adee202004-05-08 08:23:19 +00003159void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003160 int i;
drh9b3187e2005-01-18 14:45:47 +00003161 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003162 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003163 if( pList ){
3164 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3165 if( pItem->iCursor>=0 ) break;
3166 pItem->iCursor = pParse->nTab++;
3167 if( pItem->pSelect ){
3168 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3169 }
drh63eb5f22003-04-29 16:20:44 +00003170 }
3171 }
3172}
3173
3174/*
drhad3cab52002-05-24 02:04:32 +00003175** Delete an entire SrcList including all its substructure.
3176*/
drh633e6d52008-07-28 19:34:53 +00003177void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003178 int i;
drhbe5c89a2004-07-26 00:31:09 +00003179 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003180 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003181 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003182 sqlite3DbFree(db, pItem->zDatabase);
3183 sqlite3DbFree(db, pItem->zName);
3184 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003185 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003186 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003187 sqlite3SelectDelete(db, pItem->pSelect);
3188 sqlite3ExprDelete(db, pItem->pOn);
3189 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003190 }
drh633e6d52008-07-28 19:34:53 +00003191 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003192}
3193
drh982cef72000-05-30 16:27:03 +00003194/*
drh61dfc312006-12-16 16:25:15 +00003195** This routine is called by the parser to add a new term to the
3196** end of a growing FROM clause. The "p" parameter is the part of
3197** the FROM clause that has already been constructed. "p" is NULL
3198** if this is the first term of the FROM clause. pTable and pDatabase
3199** are the name of the table and database named in the FROM clause term.
3200** pDatabase is NULL if the database name qualifier is missing - the
3201** usual case. If the term has a alias, then pAlias points to the
3202** alias token. If the term is a subquery, then pSubquery is the
3203** SELECT statement that the subquery encodes. The pTable and
3204** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3205** parameters are the content of the ON and USING clauses.
3206**
3207** Return a new SrcList which encodes is the FROM with the new
3208** term added.
3209*/
3210SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003211 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003212 SrcList *p, /* The left part of the FROM clause already seen */
3213 Token *pTable, /* Name of the table to add to the FROM clause */
3214 Token *pDatabase, /* Name of the database containing pTable */
3215 Token *pAlias, /* The right-hand side of the AS subexpression */
3216 Select *pSubquery, /* A subquery used in place of a table name */
3217 Expr *pOn, /* The ON clause of a join */
3218 IdList *pUsing /* The USING clause of a join */
3219){
3220 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003221 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003222 if( !p && (pOn || pUsing) ){
3223 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3224 (pOn ? "ON" : "USING")
3225 );
3226 goto append_from_error;
3227 }
drh17435752007-08-16 04:30:38 +00003228 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003229 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003230 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003231 }
3232 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003233 assert( pAlias!=0 );
3234 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003235 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003236 }
3237 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003238 pItem->pOn = pOn;
3239 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003240 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003241
3242 append_from_error:
3243 assert( p==0 );
3244 sqlite3ExprDelete(db, pOn);
3245 sqlite3IdListDelete(db, pUsing);
3246 sqlite3SelectDelete(db, pSubquery);
3247 return 0;
drh61dfc312006-12-16 16:25:15 +00003248}
3249
3250/*
danielk1977b1c685b2008-10-06 16:18:39 +00003251** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3252** element of the source-list passed as the second argument.
3253*/
3254void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003255 assert( pIndexedBy!=0 );
3256 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003257 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3258 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3259 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3260 /* A "NOT INDEXED" clause was supplied. See parse.y
3261 ** construct "indexed_opt" for details. */
3262 pItem->notIndexed = 1;
3263 }else{
3264 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3265 }
3266 }
3267}
3268
3269/*
drh61dfc312006-12-16 16:25:15 +00003270** When building up a FROM clause in the parser, the join operator
3271** is initially attached to the left operand. But the code generator
3272** expects the join operator to be on the right operand. This routine
3273** Shifts all join operators from left to right for an entire FROM
3274** clause.
3275**
3276** Example: Suppose the join is like this:
3277**
3278** A natural cross join B
3279**
3280** The operator is "natural cross join". The A and B operands are stored
3281** in p->a[0] and p->a[1], respectively. The parser initially stores the
3282** operator with A. This routine shifts that operator over to B.
3283*/
3284void sqlite3SrcListShiftJoinType(SrcList *p){
3285 if( p && p->a ){
3286 int i;
3287 for(i=p->nSrc-1; i>0; i--){
3288 p->a[i].jointype = p->a[i-1].jointype;
3289 }
3290 p->a[0].jointype = 0;
3291 }
3292}
3293
3294/*
drhc4a3c772001-04-04 11:48:57 +00003295** Begin a transaction
3296*/
drh684917c2004-10-05 02:41:42 +00003297void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003298 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003299 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003300 int i;
drh5e00f6c2001-09-13 13:46:56 +00003301
drhd3001712009-05-12 17:46:53 +00003302 assert( pParse!=0 );
3303 db = pParse->db;
3304 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003305/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003306 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3307 return;
3308 }
danielk19771d850a72004-05-31 08:26:49 +00003309 v = sqlite3GetVdbe(pParse);
3310 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003311 if( type!=TK_DEFERRED ){
3312 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003313 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003314 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003315 }
3316 }
drh66a51672008-01-03 00:01:23 +00003317 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003318}
3319
3320/*
3321** Commit a transaction
3322*/
danielk19774adee202004-05-08 08:23:19 +00003323void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003324 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003325 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003326
drhd3001712009-05-12 17:46:53 +00003327 assert( pParse!=0 );
3328 db = pParse->db;
3329 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003330/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003331 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3332 return;
3333 }
danielk19771d850a72004-05-31 08:26:49 +00003334 v = sqlite3GetVdbe(pParse);
3335 if( v ){
drh66a51672008-01-03 00:01:23 +00003336 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003337 }
drhc4a3c772001-04-04 11:48:57 +00003338}
3339
3340/*
3341** Rollback a transaction
3342*/
danielk19774adee202004-05-08 08:23:19 +00003343void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003344 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003345 Vdbe *v;
3346
drhd3001712009-05-12 17:46:53 +00003347 assert( pParse!=0 );
3348 db = pParse->db;
3349 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003350/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003351 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3352 return;
3353 }
danielk19774adee202004-05-08 08:23:19 +00003354 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003355 if( v ){
drh66a51672008-01-03 00:01:23 +00003356 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003357 }
drhc4a3c772001-04-04 11:48:57 +00003358}
drhf57b14a2001-09-14 18:54:08 +00003359
3360/*
danielk1977fd7f0452008-12-17 17:30:26 +00003361** This function is called by the parser when it parses a command to create,
3362** release or rollback an SQL savepoint.
3363*/
3364void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003365 char *zName = sqlite3NameFromToken(pParse->db, pName);
3366 if( zName ){
3367 Vdbe *v = sqlite3GetVdbe(pParse);
3368#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003369 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003370 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3371#endif
3372 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3373 sqlite3DbFree(pParse->db, zName);
3374 return;
3375 }
3376 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003377 }
3378}
3379
3380/*
drhdc3ff9c2004-08-18 02:10:15 +00003381** Make sure the TEMP database is open and available for use. Return
3382** the number of errors. Leave any error messages in the pParse structure.
3383*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003384int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003385 sqlite3 *db = pParse->db;
3386 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003387 int rc;
drh10a76c92010-01-26 01:25:26 +00003388 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003389 static const int flags =
3390 SQLITE_OPEN_READWRITE |
3391 SQLITE_OPEN_CREATE |
3392 SQLITE_OPEN_EXCLUSIVE |
3393 SQLITE_OPEN_DELETEONCLOSE |
3394 SQLITE_OPEN_TEMP_DB;
3395
drh75c014c2010-08-30 15:02:28 +00003396 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003397 if( rc!=SQLITE_OK ){
3398 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3399 "file for storing temporary tables");
3400 pParse->rc = rc;
3401 return 1;
3402 }
drh10a76c92010-01-26 01:25:26 +00003403 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003404 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003405 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3406 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003407 return 1;
drh10a76c92010-01-26 01:25:26 +00003408 }
drhdc3ff9c2004-08-18 02:10:15 +00003409 }
3410 return 0;
3411}
3412
3413/*
drh80242052004-06-09 00:48:12 +00003414** Generate VDBE code that will verify the schema cookie and start
3415** a read-transaction for all named database files.
3416**
3417** It is important that all schema cookies be verified and all
3418** read transactions be started before anything else happens in
3419** the VDBE program. But this routine can be called after much other
3420** code has been generated. So here is what we do:
3421**
drhc275b4e2004-07-19 17:25:24 +00003422** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003423** will jump to a subroutine at the end of the program. Then we
3424** record every database that needs its schema verified in the
3425** pParse->cookieMask field. Later, after all other code has been
3426** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003427** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003428** will be made to point to that subroutine. The generation of the
3429** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003430**
3431** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3432** schema on any databases. This can be used to position the OP_Goto
3433** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003434*/
danielk19774adee202004-05-08 08:23:19 +00003435void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003436 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003437
dan65a7cd12009-09-01 12:16:01 +00003438 if( pToplevel->cookieGoto==0 ){
3439 Vdbe *v = sqlite3GetVdbe(pToplevel);
3440 if( v==0 ) return; /* This only happens if there was a prior error */
3441 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003442 }
drhc275b4e2004-07-19 17:25:24 +00003443 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003444 sqlite3 *db = pToplevel->db;
3445 int mask;
3446
drhc275b4e2004-07-19 17:25:24 +00003447 assert( iDb<db->nDb );
3448 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003449 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003450 mask = 1<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003451 if( (pToplevel->cookieMask & mask)==0 ){
3452 pToplevel->cookieMask |= mask;
3453 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003454 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003455 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003456 }
drhc275b4e2004-07-19 17:25:24 +00003457 }
drh001bbcb2003-03-19 03:14:00 +00003458 }
drh001bbcb2003-03-19 03:14:00 +00003459}
3460
3461/*
drh1c928532002-01-31 15:54:21 +00003462** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003463** might change the database.
3464**
3465** This routine starts a new transaction if we are not already within
3466** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003467** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003468** be set for operations that might fail (due to a constraint) part of
3469** the way through and which will need to undo some writes without having to
3470** rollback the whole transaction. For operations where all constraints
3471** can be checked before any changes are made to the database, it is never
3472** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003473*/
drh7f0f12e2004-05-21 13:39:50 +00003474void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003475 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003476 sqlite3CodeVerifySchema(pParse, iDb);
dan65a7cd12009-09-01 12:16:01 +00003477 pToplevel->writeMask |= 1<<iDb;
dane0af83a2009-09-08 19:15:01 +00003478 pToplevel->isMultiWrite |= setStatement;
3479}
3480
drhff738bc2009-09-24 00:09:58 +00003481/*
3482** Indicate that the statement currently under construction might write
3483** more than one entry (example: deleting one row then inserting another,
3484** inserting multiple rows in a table, or inserting a row and index entries.)
3485** If an abort occurs after some of these writes have completed, then it will
3486** be necessary to undo the completed writes.
3487*/
3488void sqlite3MultiWrite(Parse *pParse){
3489 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3490 pToplevel->isMultiWrite = 1;
3491}
3492
dane0af83a2009-09-08 19:15:01 +00003493/*
drhff738bc2009-09-24 00:09:58 +00003494** The code generator calls this routine if is discovers that it is
3495** possible to abort a statement prior to completion. In order to
3496** perform this abort without corrupting the database, we need to make
3497** sure that the statement is protected by a statement transaction.
3498**
3499** Technically, we only need to set the mayAbort flag if the
3500** isMultiWrite flag was previously set. There is a time dependency
3501** such that the abort must occur after the multiwrite. This makes
3502** some statements involving the REPLACE conflict resolution algorithm
3503** go a little faster. But taking advantage of this time dependency
3504** makes it more difficult to prove that the code is correct (in
3505** particular, it prevents us from writing an effective
3506** implementation of sqlite3AssertMayAbort()) and so we have chosen
3507** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003508*/
3509void sqlite3MayAbort(Parse *pParse){
3510 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3511 pToplevel->mayAbort = 1;
3512}
3513
3514/*
3515** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3516** error. The onError parameter determines which (if any) of the statement
3517** and/or current transaction is rolled back.
3518*/
3519void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3520 Vdbe *v = sqlite3GetVdbe(pParse);
3521 if( onError==OE_Abort ){
3522 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003523 }
dane0af83a2009-09-08 19:15:01 +00003524 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003525}
3526
drh4343fea2004-11-05 23:46:15 +00003527/*
3528** Check to see if pIndex uses the collating sequence pColl. Return
3529** true if it does and false if it does not.
3530*/
3531#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003532static int collationMatch(const char *zColl, Index *pIndex){
3533 int i;
drh04491712009-05-13 17:21:13 +00003534 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003535 for(i=0; i<pIndex->nColumn; i++){
3536 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003537 assert( z!=0 );
3538 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003539 return 1;
3540 }
drh4343fea2004-11-05 23:46:15 +00003541 }
3542 return 0;
3543}
3544#endif
3545
3546/*
3547** Recompute all indices of pTab that use the collating sequence pColl.
3548** If pColl==0 then recompute all indices of pTab.
3549*/
3550#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003551static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003552 Index *pIndex; /* An index associated with pTab */
3553
3554 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003555 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003556 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3557 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003558 sqlite3RefillIndex(pParse, pIndex, -1);
3559 }
3560 }
3561}
3562#endif
3563
3564/*
3565** Recompute all indices of all tables in all databases where the
3566** indices use the collating sequence pColl. If pColl==0 then recompute
3567** all indices everywhere.
3568*/
3569#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003570static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003571 Db *pDb; /* A single database */
3572 int iDb; /* The database index number */
3573 sqlite3 *db = pParse->db; /* The database connection */
3574 HashElem *k; /* For looping over tables in pDb */
3575 Table *pTab; /* A table in the database */
3576
3577 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003578 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003579 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003580 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003581 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003582 }
3583 }
3584}
3585#endif
3586
3587/*
drheee46cf2004-11-06 00:02:48 +00003588** Generate code for the REINDEX command.
3589**
3590** REINDEX -- 1
3591** REINDEX <collation> -- 2
3592** REINDEX ?<database>.?<tablename> -- 3
3593** REINDEX ?<database>.?<indexname> -- 4
3594**
3595** Form 1 causes all indices in all attached databases to be rebuilt.
3596** Form 2 rebuilds all indices in all databases that use the named
3597** collating function. Forms 3 and 4 rebuild the named index or all
3598** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003599*/
3600#ifndef SQLITE_OMIT_REINDEX
3601void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3602 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3603 char *z; /* Name of a table or index */
3604 const char *zDb; /* Name of the database */
3605 Table *pTab; /* A table in the database */
3606 Index *pIndex; /* An index associated with pTab */
3607 int iDb; /* The database index number */
3608 sqlite3 *db = pParse->db; /* The database connection */
3609 Token *pObjName; /* Name of the table or index to be reindexed */
3610
danielk197733a5edc2005-01-27 00:22:02 +00003611 /* Read the database schema. If an error occurs, leave an error message
3612 ** and code in pParse and return NULL. */
3613 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003614 return;
danielk197733a5edc2005-01-27 00:22:02 +00003615 }
3616
drh8af73d42009-05-13 22:58:28 +00003617 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003618 reindexDatabases(pParse, 0);
3619 return;
drhd3001712009-05-12 17:46:53 +00003620 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003621 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003622 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003623 zColl = sqlite3NameFromToken(pParse->db, pName1);
3624 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003625 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003626 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003627 reindexDatabases(pParse, zColl);
3628 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003629 return;
3630 }
drh633e6d52008-07-28 19:34:53 +00003631 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003632 }
3633 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3634 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003635 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003636 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003637 zDb = db->aDb[iDb].zName;
3638 pTab = sqlite3FindTable(db, z, zDb);
3639 if( pTab ){
3640 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003641 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003642 return;
3643 }
3644 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003645 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003646 if( pIndex ){
3647 sqlite3BeginWriteOperation(pParse, 0, iDb);
3648 sqlite3RefillIndex(pParse, pIndex, -1);
3649 return;
3650 }
3651 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3652}
3653#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003654
3655/*
3656** Return a dynamicly allocated KeyInfo structure that can be used
3657** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3658**
3659** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003660** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003661** pointer. If an error occurs (out of memory or missing collation
3662** sequence), NULL is returned and the state of pParse updated to reflect
3663** the error.
3664*/
3665KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3666 int i;
3667 int nCol = pIdx->nColumn;
3668 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003669 sqlite3 *db = pParse->db;
3670 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003671
3672 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003673 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003674 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3675 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3676 for(i=0; i<nCol; i++){
3677 char *zColl = pIdx->azColl[i];
3678 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003679 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003680 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3681 }
drh1bd10f82008-12-10 21:19:56 +00003682 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003683 }
3684
3685 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003686 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003687 pKey = 0;
3688 }
3689 return pKey;
3690}