blob: 5d063f0726574af05ad02c33980a1ae30dd6d915 [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
danf78baaf2012-12-06 19:37:22 +0000130 assert( pParse->pToplevel==0 );
drh17435752007-08-16 04:30:38 +0000131 db = pParse->db;
132 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000133 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000134 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000135
drh80242052004-06-09 00:48:12 +0000136 /* Begin by generating some termination code at the end of the
137 ** vdbe program
138 */
drh80242052004-06-09 00:48:12 +0000139 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000140 assert( !pParse->isMultiWrite
141 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000142 if( v ){
drh66a51672008-01-03 00:01:23 +0000143 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000144
145 /* The cookie mask contains one bit for each database file open.
146 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
147 ** set for each database that is used. Generate code to start a
148 ** transaction on each used database and to verify the schema cookie
149 ** on each used database.
150 */
drhc275b4e2004-07-19 17:25:24 +0000151 if( pParse->cookieGoto>0 ){
drh64123582011-04-02 20:01:02 +0000152 yDbMask mask;
drh26e4a8b2008-05-01 17:16:52 +0000153 int iDb;
drhd654be82005-09-20 17:42:23 +0000154 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000155 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
156 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000157 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000158 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drh8a939192009-04-20 17:43:03 +0000159 if( db->init.busy==0 ){
drh21206082011-04-04 18:22:02 +0000160 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhc2a75552011-03-18 21:55:46 +0000161 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
162 iDb, pParse->cookieValue[iDb],
163 db->aDb[iDb].pSchema->iGeneration);
drh8a939192009-04-20 17:43:03 +0000164 }
drh80242052004-06-09 00:48:12 +0000165 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000166#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000167 {
168 int i;
169 for(i=0; i<pParse->nVtabLock; i++){
danielk1977595a5232009-07-24 17:58:53 +0000170 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
drh26e4a8b2008-05-01 17:16:52 +0000171 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
172 }
173 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000174 }
175#endif
danielk1977c00da102006-01-07 13:21:04 +0000176
177 /* Once all the cookies have been verified and transactions opened,
178 ** obtain the required table-locks. This is a no-op unless the
179 ** shared-cache feature is enabled.
180 */
181 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000182
183 /* Initialize any AUTOINCREMENT data structures required.
184 */
185 sqlite3AutoincrementBegin(pParse);
186
187 /* Finally, jump back to the beginning of the executable code. */
drh66a51672008-01-03 00:01:23 +0000188 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000189 }
drh71c697e2004-08-08 23:39:19 +0000190 }
191
drh3f7d4e42004-07-24 14:35:58 +0000192
drh80242052004-06-09 00:48:12 +0000193 /* Get the VDBE program ready for execution
194 */
drh04491712009-05-13 17:21:13 +0000195 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000196#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000197 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000198 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000199#endif
drhceea3322009-04-23 13:22:42 +0000200 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000201 /* A minimum of one cursor is required if autoincrement is used
202 * See ticket [a696379c1f08866] */
203 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000204 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000205 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000206 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000207 }else{
drh483750b2003-01-29 18:46:51 +0000208 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000209 }
drha226d052002-09-25 19:04:07 +0000210 pParse->nTab = 0;
211 pParse->nMem = 0;
212 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000213 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000214 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000215 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000216}
217
218/*
drh205f48e2004-11-05 00:43:11 +0000219** Run the parser and code generator recursively in order to generate
220** code for the SQL statement given onto the end of the pParse context
221** currently under construction. When the parser is run recursively
222** this way, the final OP_Halt is not appended and other initialization
223** and finalization steps are omitted because those are handling by the
224** outermost parser.
225**
226** Not everything is nestable. This facility is designed to permit
227** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000228** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000229*/
230void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
231 va_list ap;
232 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000233 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000234 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000235# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
236 char saveBuf[SAVE_SZ];
237
drh205f48e2004-11-05 00:43:11 +0000238 if( pParse->nErr ) return;
239 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
240 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000241 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000242 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000243 if( zSql==0 ){
244 return; /* A malloc must have failed */
245 }
drh205f48e2004-11-05 00:43:11 +0000246 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000247 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
248 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000249 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000250 sqlite3DbFree(db, zErrMsg);
251 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000252 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000253 pParse->nested--;
254}
255
256/*
danielk19778a414492004-06-29 08:59:35 +0000257** Locate the in-memory structure that describes a particular database
258** table given the name of that table and (optionally) the name of the
259** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000260**
danielk19778a414492004-06-29 08:59:35 +0000261** If zDatabase is 0, all databases are searched for the table and the
262** first matching table is returned. (No checking for duplicate table
263** names is done.) The search order is TEMP first, then MAIN, then any
264** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000265**
danielk19774adee202004-05-08 08:23:19 +0000266** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000267*/
drh9bb575f2004-09-06 17:24:11 +0000268Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000269 Table *p = 0;
270 int i;
drh0a687d12008-07-08 14:52:07 +0000271 int nName;
drh645f63e2004-06-22 13:22:40 +0000272 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000273 nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000274 /* All mutexes are required for schema access. Make sure we hold them. */
275 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000276 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000277 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000278 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000279 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh0a687d12008-07-08 14:52:07 +0000280 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000281 if( p ) break;
282 }
drh74e24cd2002-01-09 03:19:59 +0000283 return p;
drh75897232000-05-29 14:26:00 +0000284}
285
286/*
danielk19778a414492004-06-29 08:59:35 +0000287** Locate the in-memory structure that describes a particular database
288** table given the name of that table and (optionally) the name of the
289** database containing the table. Return NULL if not found. Also leave an
290** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000291**
danielk19778a414492004-06-29 08:59:35 +0000292** The difference between this routine and sqlite3FindTable() is that this
293** routine leaves an error message in pParse->zErrMsg where
294** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000295*/
drhca424112008-01-25 15:04:48 +0000296Table *sqlite3LocateTable(
297 Parse *pParse, /* context in which to report errors */
298 int isView, /* True if looking for a VIEW rather than a TABLE */
299 const char *zName, /* Name of the table we are looking for */
300 const char *zDbase /* Name of the database. Might be NULL */
301){
drha69d9162003-04-17 22:57:53 +0000302 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000303
danielk19778a414492004-06-29 08:59:35 +0000304 /* Read the database schema. If an error occurs, leave an error message
305 ** and code in pParse and return NULL. */
306 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
307 return 0;
308 }
309
danielk19774adee202004-05-08 08:23:19 +0000310 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000311 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000312 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000313 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000314 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000315 }else{
drhca424112008-01-25 15:04:48 +0000316 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000317 }
drha6ecd332004-06-10 00:29:09 +0000318 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000319 }
320 return p;
321}
322
323/*
dan41fb5cd2012-10-04 19:33:00 +0000324** Locate the table identified by *p.
325**
326** This is a wrapper around sqlite3LocateTable(). The difference between
327** sqlite3LocateTable() and this function is that this function restricts
328** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
329** non-NULL if it is part of a view or trigger program definition. See
330** sqlite3FixSrcList() for details.
331*/
332Table *sqlite3LocateTableItem(
333 Parse *pParse,
334 int isView,
335 struct SrcList_item *p
336){
337 const char *zDb;
338 assert( p->pSchema==0 || p->zDatabase==0 );
339 if( p->pSchema ){
340 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
341 zDb = pParse->db->aDb[iDb].zName;
342 }else{
343 zDb = p->zDatabase;
344 }
345 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
346}
347
348/*
drha69d9162003-04-17 22:57:53 +0000349** Locate the in-memory structure that describes
350** a particular index given the name of that index
351** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000352** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000353**
354** If zDatabase is 0, all databases are searched for the
355** table and the first matching index is returned. (No checking
356** for duplicate index names is done.) The search order is
357** TEMP first, then MAIN, then any auxiliary databases added
358** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000359*/
drh9bb575f2004-09-06 17:24:11 +0000360Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000361 Index *p = 0;
362 int i;
drhdee0e402009-05-03 20:23:53 +0000363 int nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000364 /* All mutexes are required for schema access. Make sure we hold them. */
365 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000366 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000367 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000368 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000369 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000370 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000371 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh04491712009-05-13 17:21:13 +0000372 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000373 if( p ) break;
374 }
drh74e24cd2002-01-09 03:19:59 +0000375 return p;
drh75897232000-05-29 14:26:00 +0000376}
377
378/*
drh956bc922004-07-24 17:38:29 +0000379** Reclaim the memory used by an index
380*/
dan1feeaed2010-07-23 15:41:47 +0000381static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000382#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000383 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000384#endif
drh633e6d52008-07-28 19:34:53 +0000385 sqlite3DbFree(db, p->zColAff);
386 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000387}
388
389/*
drhc96d8532005-05-03 12:30:33 +0000390** For the index called zIdxName which is found in the database iDb,
391** unlike that index from its Table then remove the index from
392** the index hash table and free all memory structures associated
393** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000394*/
drh9bb575f2004-09-06 17:24:11 +0000395void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000396 Index *pIndex;
397 int len;
drh21206082011-04-04 18:22:02 +0000398 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000399
drh21206082011-04-04 18:22:02 +0000400 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
401 pHash = &db->aDb[iDb].pSchema->idxHash;
drhdee0e402009-05-03 20:23:53 +0000402 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000403 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh22645842011-03-24 01:34:03 +0000404 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000405 if( pIndex->pTable->pIndex==pIndex ){
406 pIndex->pTable->pIndex = pIndex->pNext;
407 }else{
408 Index *p;
drh04491712009-05-13 17:21:13 +0000409 /* Justification of ALWAYS(); The index must be on the list of
410 ** indices. */
411 p = pIndex->pTable->pIndex;
412 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
413 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000414 p->pNext = pIndex->pNext;
415 }
drh5e00f6c2001-09-13 13:46:56 +0000416 }
dan1feeaed2010-07-23 15:41:47 +0000417 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000418 }
drh956bc922004-07-24 17:38:29 +0000419 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000420}
421
422/*
drh81028a42012-05-15 18:28:27 +0000423** Look through the list of open database files in db->aDb[] and if
424** any have been closed, remove them from the list. Reallocate the
425** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000426**
drh81028a42012-05-15 18:28:27 +0000427** Entry 0 (the "main" database) and entry 1 (the "temp" database)
428** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000429*/
drh81028a42012-05-15 18:28:27 +0000430void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000431 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000432 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000433 struct Db *pDb = &db->aDb[i];
434 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000435 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000436 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000437 continue;
438 }
439 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000440 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000441 }
drh8bf8dc92003-05-17 17:35:10 +0000442 j++;
drh1c2d8412003-03-31 00:30:47 +0000443 }
444 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
445 db->nDb = j;
446 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
447 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000448 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000449 db->aDb = db->aDbStatic;
450 }
drhe0bc4042002-06-25 01:09:11 +0000451}
452
453/*
drh81028a42012-05-15 18:28:27 +0000454** Reset the schema for the database at index iDb. Also reset the
455** TEMP schema.
456*/
457void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000458 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000459 assert( iDb<db->nDb );
460
461 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000462 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000463 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
464 assert( pDb->pSchema!=0 );
465 sqlite3SchemaClear(pDb->pSchema);
466
467 /* If any database other than TEMP is reset, then also reset TEMP
468 ** since TEMP might be holding triggers that reference tables in the
469 ** other database.
470 */
471 if( iDb!=1 ){
472 pDb = &db->aDb[1];
473 assert( pDb->pSchema!=0 );
474 sqlite3SchemaClear(pDb->pSchema);
475 }
476 return;
477}
478
479/*
480** Erase all schema information from all attached databases (including
481** "main" and "temp") for a single database connection.
482*/
483void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
484 int i;
485 sqlite3BtreeEnterAll(db);
486 for(i=0; i<db->nDb; i++){
487 Db *pDb = &db->aDb[i];
488 if( pDb->pSchema ){
489 sqlite3SchemaClear(pDb->pSchema);
490 }
491 }
492 db->flags &= ~SQLITE_InternChanges;
493 sqlite3VtabUnlockList(db);
494 sqlite3BtreeLeaveAll(db);
495 sqlite3CollapseDatabaseArray(db);
496}
497
498/*
drhe0bc4042002-06-25 01:09:11 +0000499** This routine is called when a commit occurs.
500*/
drh9bb575f2004-09-06 17:24:11 +0000501void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000502 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000503}
504
505/*
dand46def72010-07-24 11:28:28 +0000506** Delete memory allocated for the column names of a table or view (the
507** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000508*/
dand46def72010-07-24 11:28:28 +0000509static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000510 int i;
511 Column *pCol;
512 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000513 if( (pCol = pTable->aCol)!=0 ){
514 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000515 sqlite3DbFree(db, pCol->zName);
516 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000517 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000518 sqlite3DbFree(db, pCol->zType);
519 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000520 }
drh633e6d52008-07-28 19:34:53 +0000521 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000522 }
drh956bc922004-07-24 17:38:29 +0000523}
524
525/*
drh75897232000-05-29 14:26:00 +0000526** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000527** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000528**
529** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000530** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000531** memory structures of the indices and foreign keys associated with
532** the table.
drh29ddd3a2012-05-15 12:49:32 +0000533**
534** The db parameter is optional. It is needed if the Table object
535** contains lookaside memory. (Table objects in the schema do not use
536** lookaside memory, but some ephemeral Table objects do.) Or the
537** db parameter can be used with db->pnBytesFreed to measure the memory
538** used by the Table object.
drh75897232000-05-29 14:26:00 +0000539*/
dan1feeaed2010-07-23 15:41:47 +0000540void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000541 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000542 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000543
dand46def72010-07-24 11:28:28 +0000544 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000545
drhed8a3bb2005-06-06 21:19:56 +0000546 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000547 if( !pTable ) return;
548 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000549
drh29ddd3a2012-05-15 12:49:32 +0000550 /* Record the number of outstanding lookaside allocations in schema Tables
551 ** prior to doing any free() operations. Since schema Tables do not use
552 ** lookaside, this number should not change. */
553 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
554 db->lookaside.nOut : 0 );
555
dand46def72010-07-24 11:28:28 +0000556 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000557 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
558 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000559 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000560 if( !db || db->pnBytesFreed==0 ){
561 char *zName = pIndex->zName;
562 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhf2f105d2012-08-20 15:53:54 +0000563 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
dand46def72010-07-24 11:28:28 +0000564 );
drh21206082011-04-04 18:22:02 +0000565 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000566 assert( pOld==pIndex || pOld==0 );
567 }
568 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000569 }
570
dan1da40a32009-09-19 17:00:31 +0000571 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000572 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000573
574 /* Delete the Table structure itself.
575 */
dand46def72010-07-24 11:28:28 +0000576 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000577 sqlite3DbFree(db, pTable->zName);
578 sqlite3DbFree(db, pTable->zColAff);
579 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000580#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000581 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000582#endif
drh078e4082010-07-28 19:17:51 +0000583#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000584 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000585#endif
drh633e6d52008-07-28 19:34:53 +0000586 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000587
588 /* Verify that no lookaside memory was used by schema tables */
589 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000590}
591
592/*
drh5edc3122001-09-13 21:53:09 +0000593** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000594** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000595*/
drh9bb575f2004-09-06 17:24:11 +0000596void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000597 Table *p;
drh956bc922004-07-24 17:38:29 +0000598 Db *pDb;
599
drhd229ca92002-01-09 13:30:41 +0000600 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000601 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000602 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000603 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000604 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000605 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000606 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000607 sqlite3Strlen30(zTabName),0);
dan1feeaed2010-07-23 15:41:47 +0000608 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000609 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000610}
611
612/*
drha99db3b2004-06-19 14:49:12 +0000613** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000614** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000615** is obtained from sqliteMalloc() and must be freed by the calling
616** function.
drh75897232000-05-29 14:26:00 +0000617**
drh24fb6272009-05-01 21:13:36 +0000618** Any quotation marks (ex: "name", 'name', [name], or `name`) that
619** surround the body of the token are removed.
620**
drhc96d8532005-05-03 12:30:33 +0000621** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000622** are not \000 terminated and are not persistent. The returned string
623** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000624*/
drh17435752007-08-16 04:30:38 +0000625char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000626 char *zName;
627 if( pName ){
drh17435752007-08-16 04:30:38 +0000628 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000629 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000630 }else{
631 zName = 0;
632 }
drh75897232000-05-29 14:26:00 +0000633 return zName;
634}
635
636/*
danielk1977cbb18d22004-05-28 11:37:27 +0000637** Open the sqlite_master table stored in database number iDb for
638** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000639*/
danielk1977c00da102006-01-07 13:21:04 +0000640void sqlite3OpenMasterTable(Parse *p, int iDb){
641 Vdbe *v = sqlite3GetVdbe(p);
642 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000643 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000644 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000645 if( p->nTab==0 ){
646 p->nTab = 1;
647 }
drhe0bc4042002-06-25 01:09:11 +0000648}
649
650/*
danielk197704103022009-02-03 16:51:24 +0000651** Parameter zName points to a nul-terminated buffer containing the name
652** of a database ("main", "temp" or the name of an attached db). This
653** function returns the index of the named database in db->aDb[], or
654** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000655*/
danielk197704103022009-02-03 16:51:24 +0000656int sqlite3FindDbName(sqlite3 *db, const char *zName){
657 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000658 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000659 Db *pDb;
660 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000661 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000662 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000663 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000664 break;
drh73c42a12004-11-20 18:13:10 +0000665 }
danielk1977cbb18d22004-05-28 11:37:27 +0000666 }
667 }
danielk1977576ec6b2005-01-21 11:55:25 +0000668 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000669}
670
danielk197704103022009-02-03 16:51:24 +0000671/*
672** The token *pName contains the name of a database (either "main" or
673** "temp" or the name of an attached db). This routine returns the
674** index of the named database in db->aDb[], or -1 if the named db
675** does not exist.
676*/
677int sqlite3FindDb(sqlite3 *db, Token *pName){
678 int i; /* Database number */
679 char *zName; /* Name we are searching for */
680 zName = sqlite3NameFromToken(db, pName);
681 i = sqlite3FindDbName(db, zName);
682 sqlite3DbFree(db, zName);
683 return i;
684}
685
drh0e3d7472004-06-19 17:33:07 +0000686/* The table or view or trigger name is passed to this routine via tokens
687** pName1 and pName2. If the table name was fully qualified, for example:
688**
689** CREATE TABLE xxx.yyy (...);
690**
691** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
692** the table name is not fully qualified, i.e.:
693**
694** CREATE TABLE yyy(...);
695**
696** Then pName1 is set to "yyy" and pName2 is "".
697**
698** This routine sets the *ppUnqual pointer to point at the token (pName1 or
699** pName2) that stores the unqualified table name. The index of the
700** database "xxx" is returned.
701*/
danielk1977ef2cb632004-05-29 02:37:19 +0000702int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000703 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000704 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000705 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
706 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000707){
drh0e3d7472004-06-19 17:33:07 +0000708 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000709 sqlite3 *db = pParse->db;
710
drhc4a64fa2009-05-11 20:53:28 +0000711 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000712 if( db->init.busy ) {
713 sqlite3ErrorMsg(pParse, "corrupt database");
714 pParse->nErr++;
715 return -1;
716 }
danielk1977cbb18d22004-05-28 11:37:27 +0000717 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000718 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000719 if( iDb<0 ){
720 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
721 pParse->nErr++;
722 return -1;
723 }
724 }else{
725 assert( db->init.iDb==0 || db->init.busy );
726 iDb = db->init.iDb;
727 *pUnqual = pName1;
728 }
729 return iDb;
730}
731
732/*
danielk1977d8123362004-06-12 09:25:12 +0000733** This routine is used to check if the UTF-8 string zName is a legal
734** unqualified name for a new schema object (table, index, view or
735** trigger). All names are legal except those that begin with the string
736** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
737** is reserved for internal use.
738*/
739int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000740 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000741 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000742 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000743 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
744 return SQLITE_ERROR;
745 }
746 return SQLITE_OK;
747}
748
749/*
drh75897232000-05-29 14:26:00 +0000750** Begin constructing a new table representation in memory. This is
751** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000752** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000753** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000754** flag is true if the table should be stored in the auxiliary database
755** file instead of in the main database file. This is normally the case
756** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000757** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000758**
drhf57b3392001-10-08 13:22:32 +0000759** The new table record is initialized and put in pParse->pNewTable.
760** As more of the CREATE TABLE statement is parsed, additional action
761** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000762** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000763** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000764*/
danielk19774adee202004-05-08 08:23:19 +0000765void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000766 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000767 Token *pName1, /* First part of the name of the table or view */
768 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000769 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000770 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000771 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000772 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000773){
drh75897232000-05-29 14:26:00 +0000774 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000775 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000776 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000777 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000778 int iDb; /* Database number to create the table in */
779 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000780
danielk1977cbb18d22004-05-28 11:37:27 +0000781 /* The table or view name to create is passed to this routine via tokens
782 ** pName1 and pName2. If the table name was fully qualified, for example:
783 **
784 ** CREATE TABLE xxx.yyy (...);
785 **
786 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
787 ** the table name is not fully qualified, i.e.:
788 **
789 ** CREATE TABLE yyy(...);
790 **
791 ** Then pName1 is set to "yyy" and pName2 is "".
792 **
793 ** The call below sets the pName pointer to point at the token (pName1 or
794 ** pName2) that stores the unqualified table name. The variable iDb is
795 ** set to the index of the database that the table or view is to be
796 ** created in.
797 */
danielk1977ef2cb632004-05-29 02:37:19 +0000798 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000799 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000800 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
801 /* If creating a temp table, the name may not be qualified. Unless
802 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000803 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000804 return;
805 }
danielk197753c0f742005-03-29 03:10:59 +0000806 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000807
808 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000809 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000810 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000811 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000812 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000813 }
drh1d85d932004-02-14 23:05:52 +0000814 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000815#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000816 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000817 {
818 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000819 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000820 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000821 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000822 }
drhe5f9c642003-01-13 23:27:31 +0000823 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000824 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000825 code = SQLITE_CREATE_TEMP_VIEW;
826 }else{
827 code = SQLITE_CREATE_VIEW;
828 }
829 }else{
danielk197753c0f742005-03-29 03:10:59 +0000830 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000831 code = SQLITE_CREATE_TEMP_TABLE;
832 }else{
833 code = SQLITE_CREATE_TABLE;
834 }
835 }
danielk1977f1a381e2006-06-16 08:01:02 +0000836 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000837 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000838 }
839 }
840#endif
drhf57b3392001-10-08 13:22:32 +0000841
drhf57b3392001-10-08 13:22:32 +0000842 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000843 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000844 ** it does. The exception is if the statement being parsed was passed
845 ** to an sqlite3_declare_vtab() call. In that case only the column names
846 ** and types will be used, so there is no need to test for namespace
847 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000848 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000849 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000850 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000851 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
852 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000853 }
dana16d1062010-09-28 17:37:28 +0000854 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000855 if( pTable ){
856 if( !noErr ){
857 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000858 }else{
859 assert( !db->init.busy );
860 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000861 }
862 goto begin_table_error;
863 }
drh8a8a0d12010-09-28 20:26:44 +0000864 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000865 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
866 goto begin_table_error;
867 }
drh75897232000-05-29 14:26:00 +0000868 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000869
danielk197726783a52007-08-29 14:06:22 +0000870 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000871 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000872 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000873 pParse->rc = SQLITE_NOMEM;
874 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000875 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000876 }
drh75897232000-05-29 14:26:00 +0000877 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000878 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000879 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000880 pTable->nRef = 1;
drh15564052010-09-25 22:32:56 +0000881 pTable->nRowEst = 1000000;
drhc4a64fa2009-05-11 20:53:28 +0000882 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000883 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000884
drh4794f732004-11-05 17:17:50 +0000885 /* If this is the magic sqlite_sequence table used by autoincrement,
886 ** then record a pointer to this table in the main database structure
887 ** so that INSERT can find the table easily.
888 */
889#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000890 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000891 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000892 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000893 }
894#endif
895
drh17f71932002-02-21 12:01:27 +0000896 /* Begin generating the code that will insert the table record into
897 ** the SQLITE_MASTER table. Note in particular that we must go ahead
898 ** and allocate the record number for the table entry now. Before any
899 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
900 ** indices to be created and the table record must come before the
901 ** indices. Hence, the record number for the table must be allocated
902 ** now.
903 */
danielk19774adee202004-05-08 08:23:19 +0000904 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000905 int j1;
drhe321c292006-01-12 01:56:43 +0000906 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000907 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000908 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000909
danielk197720b1eaf2006-07-26 16:22:14 +0000910#ifndef SQLITE_OMIT_VIRTUALTABLE
911 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000912 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000913 }
914#endif
915
danielk197736963fd2005-02-19 08:18:05 +0000916 /* If the file format and encoding in the database have not been set,
917 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000918 */
drhb7654112008-01-12 12:48:07 +0000919 reg1 = pParse->regRowid = ++pParse->nMem;
920 reg2 = pParse->regRoot = ++pParse->nMem;
921 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000922 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000923 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000924 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000925 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000926 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000927 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000928 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000929 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000930 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000931 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000932
drh4794f732004-11-05 17:17:50 +0000933 /* This just creates a place-holder record in the sqlite_master table.
934 ** The record created does not contain anything yet. It will be replaced
935 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000936 **
drh0fa991b2009-03-21 16:19:26 +0000937 ** The rowid for the new entry is left in register pParse->regRowid.
938 ** The root page number of the new table is left in reg pParse->regRoot.
939 ** The rowid and root page number values are needed by the code that
940 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000941 */
danielk1977f1a381e2006-06-16 08:01:02 +0000942#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
943 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000944 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000945 }else
946#endif
947 {
drhb7654112008-01-12 12:48:07 +0000948 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000949 }
danielk1977c00da102006-01-07 13:21:04 +0000950 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000951 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
952 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
953 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
954 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000955 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000956 }
drh23bf66d2004-12-14 03:34:34 +0000957
958 /* Normal (non-error) return. */
959 return;
960
961 /* If an error occurs, we jump here */
962begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000963 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000964 return;
drh75897232000-05-29 14:26:00 +0000965}
966
967/*
danielk1977c60e9b82005-01-31 12:42:29 +0000968** This macro is used to compare two strings in a case-insensitive manner.
969** It is slightly faster than calling sqlite3StrICmp() directly, but
970** produces larger code.
971**
972** WARNING: This macro is not compatible with the strcmp() family. It
973** returns true if the two strings are equal, otherwise false.
974*/
975#define STRICMP(x, y) (\
976sqlite3UpperToLower[*(unsigned char *)(x)]== \
977sqlite3UpperToLower[*(unsigned char *)(y)] \
978&& sqlite3StrICmp((x)+1,(y)+1)==0 )
979
980/*
drh75897232000-05-29 14:26:00 +0000981** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000982**
983** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000984** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000985** first to get things going. Then this routine is called for each
986** column.
drh75897232000-05-29 14:26:00 +0000987*/
danielk19774adee202004-05-08 08:23:19 +0000988void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000989 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000990 int i;
drha99db3b2004-06-19 14:49:12 +0000991 char *z;
drhc9b84a12002-06-20 11:36:48 +0000992 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000993 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000994 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000995#if SQLITE_MAX_COLUMN
996 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000997 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
998 return;
999 }
drhbb4957f2008-03-20 14:03:29 +00001000#endif
danielk1977ae74e032008-12-23 11:11:51 +00001001 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001002 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001003 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001004 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001005 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001006 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001007 return;
1008 }
1009 }
drh75897232000-05-29 14:26:00 +00001010 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001011 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001012 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001013 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001014 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001015 return;
1016 }
drh6d4abfb2001-10-22 02:58:08 +00001017 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001018 }
drhc9b84a12002-06-20 11:36:48 +00001019 pCol = &p->aCol[p->nCol];
1020 memset(pCol, 0, sizeof(p->aCol[0]));
1021 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001022
1023 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001024 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1025 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001026 */
danielk19774f057f92004-06-08 00:02:33 +00001027 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +00001028 p->nCol++;
drh75897232000-05-29 14:26:00 +00001029}
1030
1031/*
drh382c0242001-10-06 16:33:02 +00001032** This routine is called by the parser while in the middle of
1033** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1034** been seen on a column. This routine sets the notNull flag on
1035** the column currently under construction.
1036*/
danielk19774adee202004-05-08 08:23:19 +00001037void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001038 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001039 p = pParse->pNewTable;
1040 if( p==0 || NEVER(p->nCol<1) ) return;
1041 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001042}
1043
1044/*
danielk197752a83fb2005-01-31 12:56:44 +00001045** Scan the column type name zType (length nType) and return the
1046** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001047**
1048** This routine does a case-independent search of zType for the
1049** substrings in the following table. If one of the substrings is
1050** found, the corresponding affinity is returned. If zType contains
1051** more than one of the substrings, entries toward the top of
1052** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001053** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001054**
1055** Substring | Affinity
1056** --------------------------------
1057** 'INT' | SQLITE_AFF_INTEGER
1058** 'CHAR' | SQLITE_AFF_TEXT
1059** 'CLOB' | SQLITE_AFF_TEXT
1060** 'TEXT' | SQLITE_AFF_TEXT
1061** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001062** 'REAL' | SQLITE_AFF_REAL
1063** 'FLOA' | SQLITE_AFF_REAL
1064** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001065**
1066** If none of the substrings in the above table are found,
1067** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001068*/
drhb7916a72009-05-27 10:31:29 +00001069char sqlite3AffinityType(const char *zIn){
danielk1977b3dff962005-02-01 01:21:55 +00001070 u32 h = 0;
1071 char aff = SQLITE_AFF_NUMERIC;
danielk197752a83fb2005-01-31 12:56:44 +00001072
drhb7916a72009-05-27 10:31:29 +00001073 if( zIn ) while( zIn[0] ){
1074 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001075 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001076 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1077 aff = SQLITE_AFF_TEXT;
1078 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1079 aff = SQLITE_AFF_TEXT;
1080 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1081 aff = SQLITE_AFF_TEXT;
1082 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001083 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001084 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001085#ifndef SQLITE_OMIT_FLOATING_POINT
1086 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1087 && aff==SQLITE_AFF_NUMERIC ){
1088 aff = SQLITE_AFF_REAL;
1089 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1090 && aff==SQLITE_AFF_NUMERIC ){
1091 aff = SQLITE_AFF_REAL;
1092 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1093 && aff==SQLITE_AFF_NUMERIC ){
1094 aff = SQLITE_AFF_REAL;
1095#endif
danielk1977201f7162005-02-01 02:13:29 +00001096 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001097 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001098 break;
danielk197752a83fb2005-01-31 12:56:44 +00001099 }
1100 }
danielk1977b3dff962005-02-01 01:21:55 +00001101
1102 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001103}
1104
1105/*
drh382c0242001-10-06 16:33:02 +00001106** This routine is called by the parser while in the middle of
1107** parsing a CREATE TABLE statement. The pFirst token is the first
1108** token in the sequence of tokens that describe the type of the
1109** column currently under construction. pLast is the last token
1110** in the sequence. Use this information to construct a string
1111** that contains the typename of the column and store that string
1112** in zType.
1113*/
drh487e2622005-06-25 18:42:14 +00001114void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001115 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001116 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001117
drhc4a64fa2009-05-11 20:53:28 +00001118 p = pParse->pNewTable;
1119 if( p==0 || NEVER(p->nCol<1) ) return;
1120 pCol = &p->aCol[p->nCol-1];
1121 assert( pCol->zType==0 );
1122 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhb7916a72009-05-27 10:31:29 +00001123 pCol->affinity = sqlite3AffinityType(pCol->zType);
drh382c0242001-10-06 16:33:02 +00001124}
1125
1126/*
danielk19777977a172004-11-09 12:44:37 +00001127** The expression is the default value for the most recently added column
1128** of the table currently under construction.
1129**
1130** Default value expressions must be constant. Raise an exception if this
1131** is not the case.
drhd9b02572001-04-15 00:37:09 +00001132**
1133** This routine is called by the parser while in the middle of
1134** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001135*/
drhb7916a72009-05-27 10:31:29 +00001136void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001137 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001138 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001139 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001140 p = pParse->pNewTable;
1141 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001142 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001143 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001144 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1145 pCol->zName);
1146 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001147 /* A copy of pExpr is used instead of the original, as pExpr contains
1148 ** tokens that point to volatile memory. The 'span' of the expression
1149 ** is required by pragma table_info.
1150 */
drh633e6d52008-07-28 19:34:53 +00001151 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001152 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1153 sqlite3DbFree(db, pCol->zDflt);
1154 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001155 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001156 }
danielk19777977a172004-11-09 12:44:37 +00001157 }
drhb7916a72009-05-27 10:31:29 +00001158 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001159}
1160
1161/*
drh4a324312001-12-21 14:30:42 +00001162** Designate the PRIMARY KEY for the table. pList is a list of names
1163** of columns that form the primary key. If pList is NULL, then the
1164** most recently added column of the table is the primary key.
1165**
1166** A table can have at most one primary key. If the table already has
1167** a primary key (and this is the second primary key) then create an
1168** error.
1169**
1170** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001171** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001172** field of the table under construction to be the index of the
1173** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1174** no INTEGER PRIMARY KEY.
1175**
1176** If the key is not an INTEGER PRIMARY KEY, then create a unique
1177** index for the key. No index is created for INTEGER PRIMARY KEYs.
1178*/
drh205f48e2004-11-05 00:43:11 +00001179void sqlite3AddPrimaryKey(
1180 Parse *pParse, /* Parsing context */
1181 ExprList *pList, /* List of field names to be indexed */
1182 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001183 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1184 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001185){
drh4a324312001-12-21 14:30:42 +00001186 Table *pTab = pParse->pNewTable;
1187 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001188 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001189 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001190 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001191 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001192 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001193 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001194 }
drh7d10d5a2008-08-20 16:35:10 +00001195 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001196 if( pList==0 ){
1197 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001198 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh78100cc2003-08-23 22:40:53 +00001199 }else{
danielk19770202b292004-06-09 09:55:16 +00001200 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001201 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001202 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1203 break;
1204 }
drh78100cc2003-08-23 22:40:53 +00001205 }
drh6e4fc2c2005-09-15 21:24:51 +00001206 if( iCol<pTab->nCol ){
drha371ace2012-09-13 14:22:47 +00001207 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh6e4fc2c2005-09-15 21:24:51 +00001208 }
drh4a324312001-12-21 14:30:42 +00001209 }
danielk19770202b292004-06-09 09:55:16 +00001210 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001211 }
1212 if( iCol>=0 && iCol<pTab->nCol ){
1213 zType = pTab->aCol[iCol].zType;
1214 }
drhfdd6e852005-12-16 01:06:16 +00001215 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1216 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001217 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001218 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001219 assert( autoInc==0 || autoInc==1 );
1220 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001221 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001222#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001223 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1224 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001225#endif
drh4a324312001-12-21 14:30:42 +00001226 }else{
dan1da40a32009-09-19 17:00:31 +00001227 Index *p;
1228 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1229 if( p ){
1230 p->autoIndex = 2;
1231 }
drhe0194f22003-02-26 13:52:51 +00001232 pList = 0;
drh4a324312001-12-21 14:30:42 +00001233 }
drhe0194f22003-02-26 13:52:51 +00001234
1235primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001236 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001237 return;
drh4a324312001-12-21 14:30:42 +00001238}
1239
1240/*
drhffe07b22005-11-03 00:41:17 +00001241** Add a new CHECK constraint to the table currently under construction.
1242*/
1243void sqlite3AddCheckConstraint(
1244 Parse *pParse, /* Parsing context */
1245 Expr *pCheckExpr /* The check expression */
1246){
1247#ifndef SQLITE_OMIT_CHECK
1248 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001249 if( pTab && !IN_DECLARE_VTAB ){
drh2938f922012-03-07 19:13:29 +00001250 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1251 if( pParse->constraintName.n ){
1252 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1253 }
drh33e619f2009-05-28 01:00:55 +00001254 }else
drhffe07b22005-11-03 00:41:17 +00001255#endif
drh33e619f2009-05-28 01:00:55 +00001256 {
drh2938f922012-03-07 19:13:29 +00001257 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001258 }
drhffe07b22005-11-03 00:41:17 +00001259}
1260
1261/*
drhd3d39e92004-05-20 22:16:29 +00001262** Set the collation function of the most recently parsed table column
1263** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001264*/
danielk197739002502007-11-12 09:50:26 +00001265void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001266 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001267 int i;
danielk197739002502007-11-12 09:50:26 +00001268 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001269 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001270
danielk1977b8cbb872006-06-19 05:33:45 +00001271 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001272 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001273 db = pParse->db;
1274 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001275 if( !zColl ) return;
1276
drhc4a64fa2009-05-11 20:53:28 +00001277 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001278 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001279 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001280
1281 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1282 ** then an index may have been created on this column before the
1283 ** collation type was added. Correct this if it is the case.
1284 */
1285 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1286 assert( pIdx->nColumn==1 );
1287 if( pIdx->aiColumn[0]==i ){
1288 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001289 }
1290 }
danielk197739002502007-11-12 09:50:26 +00001291 }else{
drh633e6d52008-07-28 19:34:53 +00001292 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001293 }
danielk19777cedc8d2004-06-10 10:50:08 +00001294}
1295
danielk1977466be562004-06-10 02:16:01 +00001296/*
1297** This function returns the collation sequence for database native text
1298** encoding identified by the string zName, length nName.
1299**
1300** If the requested collation sequence is not available, or not available
1301** in the database native encoding, the collation factory is invoked to
1302** request it. If the collation factory does not supply such a sequence,
1303** and the sequence is available in another text encoding, then that is
1304** returned instead.
1305**
1306** If no versions of the requested collations sequence are available, or
1307** another error occurs, NULL is returned and an error message written into
1308** pParse.
drha34001c2007-02-02 12:44:37 +00001309**
1310** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1311** invokes the collation factory if the named collation cannot be found
1312** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001313**
1314** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001315*/
drhc4a64fa2009-05-11 20:53:28 +00001316CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001317 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001318 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001319 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001320 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001321
drhc4a64fa2009-05-11 20:53:28 +00001322 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001323 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001324 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001325 }
1326
danielk19770202b292004-06-09 09:55:16 +00001327 return pColl;
1328}
1329
1330
drh8e2ca022002-06-17 17:07:19 +00001331/*
drh3f7d4e42004-07-24 14:35:58 +00001332** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001333**
1334** The schema cookie is used to determine when the schema for the
1335** database changes. After each schema change, the cookie value
1336** changes. When a process first reads the schema it records the
1337** cookie. Thereafter, whenever it goes to access the database,
1338** it checks the cookie to make sure the schema has not changed
1339** since it was last read.
1340**
1341** This plan is not completely bullet-proof. It is possible for
1342** the schema to change multiple times and for the cookie to be
1343** set back to prior value. But schema changes are infrequent
1344** and the probability of hitting the same cookie value is only
1345** 1 chance in 2^32. So we're safe enough.
1346*/
drh9cbf3422008-01-17 16:22:13 +00001347void sqlite3ChangeCookie(Parse *pParse, int iDb){
1348 int r1 = sqlite3GetTempReg(pParse);
1349 sqlite3 *db = pParse->db;
1350 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001351 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001352 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001353 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001354 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001355}
1356
1357/*
drh969fa7c2002-02-18 18:30:32 +00001358** Measure the number of characters needed to output the given
1359** identifier. The number returned includes any quotes used
1360** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001361**
1362** The estimate is conservative. It might be larger that what is
1363** really needed.
drh969fa7c2002-02-18 18:30:32 +00001364*/
1365static int identLength(const char *z){
1366 int n;
drh17f71932002-02-21 12:01:27 +00001367 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001368 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001369 }
drh234c39d2004-07-24 03:30:47 +00001370 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001371}
1372
1373/*
danielk19771b870de2009-03-14 08:37:23 +00001374** The first parameter is a pointer to an output buffer. The second
1375** parameter is a pointer to an integer that contains the offset at
1376** which to write into the output buffer. This function copies the
1377** nul-terminated string pointed to by the third parameter, zSignedIdent,
1378** to the specified offset in the buffer and updates *pIdx to refer
1379** to the first byte after the last byte written before returning.
1380**
1381** If the string zSignedIdent consists entirely of alpha-numeric
1382** characters, does not begin with a digit and is not an SQL keyword,
1383** then it is copied to the output buffer exactly as it is. Otherwise,
1384** it is quoted using double-quotes.
1385*/
drhc4a64fa2009-05-11 20:53:28 +00001386static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001387 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001388 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001389 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001390
drh17f71932002-02-21 12:01:27 +00001391 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001392 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001393 }
danielk19771b870de2009-03-14 08:37:23 +00001394 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1395 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001396 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001397 }
1398
drh234c39d2004-07-24 03:30:47 +00001399 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001400 for(j=0; zIdent[j]; j++){
1401 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001402 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001403 }
drh234c39d2004-07-24 03:30:47 +00001404 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001405 z[i] = 0;
1406 *pIdx = i;
1407}
1408
1409/*
1410** Generate a CREATE TABLE statement appropriate for the given
1411** table. Memory to hold the text of the statement is obtained
1412** from sqliteMalloc() and must be freed by the calling function.
1413*/
drh1d34fde2009-02-03 15:50:33 +00001414static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001415 int i, k, n;
1416 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001417 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001418 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001419 n = 0;
drh234c39d2004-07-24 03:30:47 +00001420 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001421 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001422 }
1423 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001424 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001425 zSep = "";
1426 zSep2 = ",";
1427 zEnd = ")";
1428 }else{
1429 zSep = "\n ";
1430 zSep2 = ",\n ";
1431 zEnd = "\n)";
1432 }
drhe0bc4042002-06-25 01:09:11 +00001433 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001434 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001435 if( zStmt==0 ){
1436 db->mallocFailed = 1;
1437 return 0;
1438 }
drhbdb339f2009-02-02 18:03:21 +00001439 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001440 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001441 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001442 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001443 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001444 static const char * const azType[] = {
1445 /* SQLITE_AFF_TEXT */ " TEXT",
1446 /* SQLITE_AFF_NONE */ "",
1447 /* SQLITE_AFF_NUMERIC */ " NUM",
1448 /* SQLITE_AFF_INTEGER */ " INT",
1449 /* SQLITE_AFF_REAL */ " REAL"
1450 };
1451 int len;
1452 const char *zType;
1453
drh5bb3eb92007-05-04 13:15:55 +00001454 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001455 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001456 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001457 identPut(zStmt, &k, pCol->zName);
1458 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001459 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001460 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1461 testcase( pCol->affinity==SQLITE_AFF_NONE );
1462 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1463 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1464 testcase( pCol->affinity==SQLITE_AFF_REAL );
1465
1466 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1467 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001468 assert( pCol->affinity==SQLITE_AFF_NONE
1469 || pCol->affinity==sqlite3AffinityType(zType) );
drhc4a64fa2009-05-11 20:53:28 +00001470 memcpy(&zStmt[k], zType, len);
1471 k += len;
1472 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001473 }
drh5bb3eb92007-05-04 13:15:55 +00001474 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001475 return zStmt;
1476}
1477
1478/*
drh75897232000-05-29 14:26:00 +00001479** This routine is called to report the final ")" that terminates
1480** a CREATE TABLE statement.
1481**
drhf57b3392001-10-08 13:22:32 +00001482** The table structure that other action routines have been building
1483** is added to the internal hash tables, assuming no errors have
1484** occurred.
drh75897232000-05-29 14:26:00 +00001485**
drh1d85d932004-02-14 23:05:52 +00001486** An entry for the table is made in the master table on disk, unless
1487** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001488** it means we are reading the sqlite_master table because we just
1489** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001490** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001491** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001492**
1493** If the pSelect argument is not NULL, it means that this routine
1494** was called to create a table generated from a
1495** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1496** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001497*/
danielk197719a8e7e2005-03-17 05:03:38 +00001498void sqlite3EndTable(
1499 Parse *pParse, /* Parse context */
1500 Token *pCons, /* The ',' token after the last column defn. */
1501 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1502 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1503){
drh75897232000-05-29 14:26:00 +00001504 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001505 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001506 int iDb;
drh75897232000-05-29 14:26:00 +00001507
drh8af73d42009-05-13 22:58:28 +00001508 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001509 return;
1510 }
drh28037572000-08-02 13:47:41 +00001511 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001512 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001513
danielk1977517eb642004-06-07 10:00:31 +00001514 assert( !db->init.busy || !pSelect );
1515
drhb9bb7c12006-06-11 23:41:55 +00001516 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001517
drhffe07b22005-11-03 00:41:17 +00001518#ifndef SQLITE_OMIT_CHECK
1519 /* Resolve names in all CHECK constraint expressions.
1520 */
1521 if( p->pCheck ){
1522 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1523 NameContext sNC; /* Name context for pParse->pNewTable */
drh2938f922012-03-07 19:13:29 +00001524 ExprList *pList; /* List of all CHECK constraints */
1525 int i; /* Loop counter */
drhffe07b22005-11-03 00:41:17 +00001526
1527 memset(&sNC, 0, sizeof(sNC));
1528 memset(&sSrc, 0, sizeof(sSrc));
1529 sSrc.nSrc = 1;
1530 sSrc.a[0].zName = p->zName;
1531 sSrc.a[0].pTab = p;
1532 sSrc.a[0].iCursor = -1;
1533 sNC.pParse = pParse;
1534 sNC.pSrcList = &sSrc;
drha51009b2012-05-21 19:11:25 +00001535 sNC.ncFlags = NC_IsCheck;
drh2938f922012-03-07 19:13:29 +00001536 pList = p->pCheck;
1537 for(i=0; i<pList->nExpr; i++){
1538 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
1539 return;
1540 }
drhffe07b22005-11-03 00:41:17 +00001541 }
1542 }
1543#endif /* !defined(SQLITE_OMIT_CHECK) */
1544
drh1d85d932004-02-14 23:05:52 +00001545 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001546 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1547 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001548 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001549 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001550 */
drh1d85d932004-02-14 23:05:52 +00001551 if( db->init.busy ){
1552 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001553 }
1554
drhe3c41372001-09-17 20:25:58 +00001555 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001556 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001557 **
drhe0bc4042002-06-25 01:09:11 +00001558 ** If this is a TEMPORARY table, write the entry into the auxiliary
1559 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001560 */
drh1d85d932004-02-14 23:05:52 +00001561 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001562 int n;
drhd8bc7082000-06-07 23:51:50 +00001563 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001564 char *zType; /* "view" or "table" */
1565 char *zType2; /* "VIEW" or "TABLE" */
1566 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001567
danielk19774adee202004-05-08 08:23:19 +00001568 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001569 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001570
drh66a51672008-01-03 00:01:23 +00001571 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001572
drh0fa991b2009-03-21 16:19:26 +00001573 /*
1574 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001575 */
drh4ff6dfa2002-03-03 23:06:00 +00001576 if( p->pSelect==0 ){
1577 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001578 zType = "table";
1579 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001580#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001581 }else{
1582 /* A view */
drh4794f732004-11-05 17:17:50 +00001583 zType = "view";
1584 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001585#endif
drh4ff6dfa2002-03-03 23:06:00 +00001586 }
danielk1977517eb642004-06-07 10:00:31 +00001587
danielk1977517eb642004-06-07 10:00:31 +00001588 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1589 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001590 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001591 **
1592 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1593 ** suitable state to query for the column names and types to be used
1594 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001595 **
1596 ** A shared-cache write-lock is not required to write to the new table,
1597 ** as a schema-lock must have already been obtained to create it. Since
1598 ** a schema-lock excludes all other database users, the write-lock would
1599 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001600 */
1601 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001602 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001603 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001604
danielk19776ab3a2e2009-02-19 14:39:25 +00001605 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001606 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001607 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001608 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001609 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001610 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001611 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001612 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001613 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001614 if( pSelTab==0 ) return;
1615 assert( p->aCol==0 );
1616 p->nCol = pSelTab->nCol;
1617 p->aCol = pSelTab->aCol;
1618 pSelTab->nCol = 0;
1619 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001620 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001621 }
1622 }
drh4794f732004-11-05 17:17:50 +00001623
drh4794f732004-11-05 17:17:50 +00001624 /* Compute the complete text of the CREATE statement */
1625 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001626 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001627 }else{
drh1bd10f82008-12-10 21:19:56 +00001628 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001629 zStmt = sqlite3MPrintf(db,
1630 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1631 );
drh4794f732004-11-05 17:17:50 +00001632 }
1633
1634 /* A slot for the record has already been allocated in the
1635 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001636 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001637 */
1638 sqlite3NestedParse(pParse,
1639 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001640 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1641 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001642 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001643 zType,
1644 p->zName,
1645 p->zName,
drhb7654112008-01-12 12:48:07 +00001646 pParse->regRoot,
1647 zStmt,
1648 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001649 );
drh633e6d52008-07-28 19:34:53 +00001650 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001651 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001652
1653#ifndef SQLITE_OMIT_AUTOINCREMENT
1654 /* Check to see if we need to create an sqlite_sequence table for
1655 ** keeping track of autoincrement keys.
1656 */
drh7d10d5a2008-08-20 16:35:10 +00001657 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001658 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001659 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001660 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001661 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001662 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1663 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001664 );
1665 }
1666 }
1667#endif
drh4794f732004-11-05 17:17:50 +00001668
1669 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001670 sqlite3VdbeAddParseSchemaOp(v, iDb,
1671 sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
drh75897232000-05-29 14:26:00 +00001672 }
drh17e9e292003-02-01 13:53:28 +00001673
drh2958a4e2004-11-12 03:56:15 +00001674
drh17e9e292003-02-01 13:53:28 +00001675 /* Add the table to the in-memory representation of the database.
1676 */
drh8af73d42009-05-13 22:58:28 +00001677 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001678 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001679 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001680 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001681 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001682 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001683 if( pOld ){
1684 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001685 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001686 return;
1687 }
drh17e9e292003-02-01 13:53:28 +00001688 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001689 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001690
1691#ifndef SQLITE_OMIT_ALTERTABLE
1692 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001693 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001694 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001695 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001696 if( pCons->z==0 ){
1697 pCons = pEnd;
1698 }
drh1bd10f82008-12-10 21:19:56 +00001699 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001700 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001701 }
1702#endif
drh17e9e292003-02-01 13:53:28 +00001703 }
drh75897232000-05-29 14:26:00 +00001704}
1705
drhb7f91642004-10-31 02:22:47 +00001706#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001707/*
drha76b5df2002-02-23 02:32:10 +00001708** The parser calls this routine in order to create a new VIEW
1709*/
danielk19774adee202004-05-08 08:23:19 +00001710void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001711 Parse *pParse, /* The parsing context */
1712 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001713 Token *pName1, /* The token that holds the name of the view */
1714 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001715 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001716 int isTemp, /* TRUE for a TEMPORARY view */
1717 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001718){
drha76b5df2002-02-23 02:32:10 +00001719 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001720 int n;
drhb7916a72009-05-27 10:31:29 +00001721 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001722 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001723 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00001724 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00001725 int iDb;
drh17435752007-08-16 04:30:38 +00001726 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001727
drh7c3d64f2005-06-06 15:32:08 +00001728 if( pParse->nVar>0 ){
1729 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001730 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001731 return;
1732 }
drhfdd48a72006-09-11 23:45:48 +00001733 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001734 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001735 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001736 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001737 return;
1738 }
danielk1977ef2cb632004-05-29 02:37:19 +00001739 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001740 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001741 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001742 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001743 ){
drh633e6d52008-07-28 19:34:53 +00001744 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001745 return;
1746 }
drh174b6192002-12-03 02:22:52 +00001747
drh4b59ab52002-08-24 18:24:51 +00001748 /* Make a copy of the entire SELECT statement that defines the view.
1749 ** This will force all the Expr.token.z values to be dynamically
1750 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001751 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001752 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001753 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001754 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001755 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001756 return;
1757 }
drh17435752007-08-16 04:30:38 +00001758 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001759 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001760 }
drh4b59ab52002-08-24 18:24:51 +00001761
1762 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1763 ** the end.
1764 */
drha76b5df2002-02-23 02:32:10 +00001765 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001766 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001767 sEnd.z += sEnd.n;
1768 }
1769 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001770 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001771 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001772 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001773 sEnd.z = &z[n-1];
1774 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001775
danielk19774adee202004-05-08 08:23:19 +00001776 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001777 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001778 return;
drh417be792002-03-03 18:59:40 +00001779}
drhb7f91642004-10-31 02:22:47 +00001780#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001781
danielk1977fe3fcbe22006-06-12 12:08:45 +00001782#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001783/*
1784** The Table structure pTable is really a VIEW. Fill in the names of
1785** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001786** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001787*/
danielk19774adee202004-05-08 08:23:19 +00001788int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001789 Table *pSelTab; /* A fake table from which we get the result set */
1790 Select *pSel; /* Copy of the SELECT that implements the view */
1791 int nErr = 0; /* Number of errors encountered */
1792 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001793 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001794 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001795
1796 assert( pTable );
1797
danielk1977fe3fcbe22006-06-12 12:08:45 +00001798#ifndef SQLITE_OMIT_VIRTUALTABLE
1799 if( sqlite3VtabCallConnect(pParse, pTable) ){
1800 return SQLITE_ERROR;
1801 }
drh4cbdda92006-06-14 19:00:20 +00001802 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001803#endif
1804
1805#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001806 /* A positive nCol means the columns names for this view are
1807 ** already known.
1808 */
1809 if( pTable->nCol>0 ) return 0;
1810
1811 /* A negative nCol is a special marker meaning that we are currently
1812 ** trying to compute the column names. If we enter this routine with
1813 ** a negative nCol, it means two or more views form a loop, like this:
1814 **
1815 ** CREATE VIEW one AS SELECT * FROM two;
1816 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001817 **
drh768578e2009-05-12 00:40:12 +00001818 ** Actually, the error above is now caught prior to reaching this point.
1819 ** But the following test is still important as it does come up
1820 ** in the following:
1821 **
1822 ** CREATE TABLE main.ex1(a);
1823 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1824 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001825 */
1826 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001827 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001828 return 1;
1829 }
drh85c23c62005-08-20 03:03:04 +00001830 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001831
1832 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001833 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1834 ** "*" elements in the results set of the view and will assign cursors
1835 ** to the elements of the FROM clause. But we do not want these changes
1836 ** to be permanent. So the computation is done on a copy of the SELECT
1837 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001838 */
drh9b3187e2005-01-18 14:45:47 +00001839 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001840 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001841 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001842 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001843 n = pParse->nTab;
1844 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1845 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001846 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001847#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001848 xAuth = db->xAuth;
1849 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001850 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001851 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001852#else
drh7d10d5a2008-08-20 16:35:10 +00001853 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001854#endif
drhd9da78a2009-03-24 15:08:09 +00001855 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001856 pParse->nTab = n;
1857 if( pSelTab ){
1858 assert( pTable->aCol==0 );
1859 pTable->nCol = pSelTab->nCol;
1860 pTable->aCol = pSelTab->aCol;
1861 pSelTab->nCol = 0;
1862 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001863 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00001864 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00001865 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001866 }else{
1867 pTable->nCol = 0;
1868 nErr++;
1869 }
drh633e6d52008-07-28 19:34:53 +00001870 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001871 } else {
drh417be792002-03-03 18:59:40 +00001872 nErr++;
1873 }
drhb7f91642004-10-31 02:22:47 +00001874#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001875 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001876}
1877#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001878
drhb7f91642004-10-31 02:22:47 +00001879#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001880/*
drh8bf8dc92003-05-17 17:35:10 +00001881** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001882*/
drh9bb575f2004-09-06 17:24:11 +00001883static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001884 HashElem *i;
drh21206082011-04-04 18:22:02 +00001885 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00001886 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001887 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001888 Table *pTab = sqliteHashData(i);
1889 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00001890 sqliteDeleteColumnNames(db, pTab);
1891 pTab->aCol = 0;
1892 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00001893 }
1894 }
drh8bf8dc92003-05-17 17:35:10 +00001895 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001896}
drhb7f91642004-10-31 02:22:47 +00001897#else
1898# define sqliteViewResetAll(A,B)
1899#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001900
drh75897232000-05-29 14:26:00 +00001901/*
danielk1977a0bf2652004-11-04 14:30:04 +00001902** This function is called by the VDBE to adjust the internal schema
1903** used by SQLite when the btree layer moves a table root page. The
1904** root-page of a table or index in database iDb has changed from iFrom
1905** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001906**
1907** Ticket #1728: The symbol table might still contain information
1908** on tables and/or indices that are the process of being deleted.
1909** If you are unlucky, one of those deleted indices or tables might
1910** have the same rootpage number as the real table or index that is
1911** being moved. So we cannot stop searching after the first match
1912** because the first match might be for one of the deleted indices
1913** or tables and not the table/index that is actually being moved.
1914** We must continue looping until all tables and indices with
1915** rootpage==iFrom have been converted to have a rootpage of iTo
1916** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001917*/
1918#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00001919void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00001920 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001921 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00001922 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00001923
drhcdf011d2011-04-04 21:25:28 +00001924 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1925 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00001926 pHash = &pDb->pSchema->tblHash;
1927 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001928 Table *pTab = sqliteHashData(pElem);
1929 if( pTab->tnum==iFrom ){
1930 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001931 }
1932 }
danielk1977da184232006-01-05 11:34:32 +00001933 pHash = &pDb->pSchema->idxHash;
1934 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001935 Index *pIdx = sqliteHashData(pElem);
1936 if( pIdx->tnum==iFrom ){
1937 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001938 }
1939 }
danielk1977a0bf2652004-11-04 14:30:04 +00001940}
1941#endif
1942
1943/*
1944** Write code to erase the table with root-page iTable from database iDb.
1945** Also write code to modify the sqlite_master table and internal schema
1946** if a root-page of another table is moved by the btree-layer whilst
1947** erasing iTable (this can happen with an auto-vacuum database).
1948*/
drh4e0cff62004-11-05 05:10:28 +00001949static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1950 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001951 int r1 = sqlite3GetTempReg(pParse);
1952 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001953 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001954#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001955 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001956 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001957 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001958 ** reflect this.
1959 **
drh0fa991b2009-03-21 16:19:26 +00001960 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00001961 ** is in register NNN. See grammar rules associated with the TK_REGISTER
1962 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00001963 */
danielk197763e3e9f2004-11-05 09:19:27 +00001964 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001965 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1966 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001967#endif
drhb7654112008-01-12 12:48:07 +00001968 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001969}
1970
1971/*
1972** Write VDBE code to erase table pTab and all associated indices on disk.
1973** Code to update the sqlite_master tables and internal schema definitions
1974** in case a root-page belonging to another table is moved by the btree layer
1975** is also added (this can happen with an auto-vacuum database).
1976*/
drh4e0cff62004-11-05 05:10:28 +00001977static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001978#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001979 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001980 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1981 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001982 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001983 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001984 }
1985#else
1986 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1987 ** is not defined), then it is important to call OP_Destroy on the
1988 ** table and index root-pages in order, starting with the numerically
1989 ** largest root-page number. This guarantees that none of the root-pages
1990 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1991 ** following were coded:
1992 **
1993 ** OP_Destroy 4 0
1994 ** ...
1995 ** OP_Destroy 5 0
1996 **
1997 ** and root page 5 happened to be the largest root-page number in the
1998 ** database, then root page 5 would be moved to page 4 by the
1999 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2000 ** a free-list page.
2001 */
2002 int iTab = pTab->tnum;
2003 int iDestroyed = 0;
2004
2005 while( 1 ){
2006 Index *pIdx;
2007 int iLargest = 0;
2008
2009 if( iDestroyed==0 || iTab<iDestroyed ){
2010 iLargest = iTab;
2011 }
2012 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2013 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002014 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002015 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2016 iLargest = iIdx;
2017 }
2018 }
danielk1977da184232006-01-05 11:34:32 +00002019 if( iLargest==0 ){
2020 return;
2021 }else{
2022 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002023 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002024 destroyRootPage(pParse, iLargest, iDb);
2025 iDestroyed = iLargest;
2026 }
danielk1977a0bf2652004-11-04 14:30:04 +00002027 }
2028#endif
2029}
2030
2031/*
drh74e7c8f2011-10-21 19:06:32 +00002032** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002033** after a DROP INDEX or DROP TABLE command.
2034*/
2035static void sqlite3ClearStatTables(
2036 Parse *pParse, /* The parsing context */
2037 int iDb, /* The database number */
2038 const char *zType, /* "idx" or "tbl" */
2039 const char *zName /* Name of index or table */
2040){
drha5ae4c32011-08-07 01:31:52 +00002041 int i;
2042 const char *zDbName = pParse->db->aDb[iDb].zName;
drh74e7c8f2011-10-21 19:06:32 +00002043 for(i=1; i<=3; i++){
2044 char zTab[24];
2045 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2046 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002047 sqlite3NestedParse(pParse,
2048 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002049 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002050 );
2051 }
2052 }
2053}
2054
2055/*
drhfaacf172011-08-12 01:51:45 +00002056** Generate code to drop a table.
2057*/
2058void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2059 Vdbe *v;
2060 sqlite3 *db = pParse->db;
2061 Trigger *pTrigger;
2062 Db *pDb = &db->aDb[iDb];
2063
2064 v = sqlite3GetVdbe(pParse);
2065 assert( v!=0 );
2066 sqlite3BeginWriteOperation(pParse, 1, iDb);
2067
2068#ifndef SQLITE_OMIT_VIRTUALTABLE
2069 if( IsVirtual(pTab) ){
2070 sqlite3VdbeAddOp0(v, OP_VBegin);
2071 }
2072#endif
2073
2074 /* Drop all triggers associated with the table being dropped. Code
2075 ** is generated to remove entries from sqlite_master and/or
2076 ** sqlite_temp_master if required.
2077 */
2078 pTrigger = sqlite3TriggerList(pParse, pTab);
2079 while( pTrigger ){
2080 assert( pTrigger->pSchema==pTab->pSchema ||
2081 pTrigger->pSchema==db->aDb[1].pSchema );
2082 sqlite3DropTriggerPtr(pParse, pTrigger);
2083 pTrigger = pTrigger->pNext;
2084 }
2085
2086#ifndef SQLITE_OMIT_AUTOINCREMENT
2087 /* Remove any entries of the sqlite_sequence table associated with
2088 ** the table being dropped. This is done before the table is dropped
2089 ** at the btree level, in case the sqlite_sequence table needs to
2090 ** move as a result of the drop (can happen in auto-vacuum mode).
2091 */
2092 if( pTab->tabFlags & TF_Autoincrement ){
2093 sqlite3NestedParse(pParse,
2094 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2095 pDb->zName, pTab->zName
2096 );
2097 }
2098#endif
2099
2100 /* Drop all SQLITE_MASTER table and index entries that refer to the
2101 ** table. The program name loops through the master table and deletes
2102 ** every row that refers to a table of the same name as the one being
2103 ** dropped. Triggers are handled seperately because a trigger can be
2104 ** created in the temp database that refers to a table in another
2105 ** database.
2106 */
2107 sqlite3NestedParse(pParse,
2108 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2109 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002110 if( !isView && !IsVirtual(pTab) ){
2111 destroyTable(pParse, pTab);
2112 }
2113
2114 /* Remove the table entry from SQLite's internal schema and modify
2115 ** the schema cookie.
2116 */
2117 if( IsVirtual(pTab) ){
2118 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2119 }
2120 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2121 sqlite3ChangeCookie(pParse, iDb);
2122 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002123}
2124
2125/*
drh75897232000-05-29 14:26:00 +00002126** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002127** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002128*/
drha0733842005-12-29 01:11:36 +00002129void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002130 Table *pTab;
drh75897232000-05-29 14:26:00 +00002131 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002132 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002133 int iDb;
drh75897232000-05-29 14:26:00 +00002134
drh8af73d42009-05-13 22:58:28 +00002135 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002136 goto exit_drop_table;
2137 }
drh8af73d42009-05-13 22:58:28 +00002138 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002139 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002140 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002141 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002142 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002143
drha0733842005-12-29 01:11:36 +00002144 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002145 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002146 goto exit_drop_table;
2147 }
danielk1977da184232006-01-05 11:34:32 +00002148 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002149 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002150
2151 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2152 ** it is initialized.
2153 */
2154 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2155 goto exit_drop_table;
2156 }
drhe5f9c642003-01-13 23:27:31 +00002157#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002158 {
2159 int code;
danielk1977da184232006-01-05 11:34:32 +00002160 const char *zTab = SCHEMA_TABLE(iDb);
2161 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002162 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002163 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002164 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002165 }
drhe5f9c642003-01-13 23:27:31 +00002166 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002167 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002168 code = SQLITE_DROP_TEMP_VIEW;
2169 }else{
2170 code = SQLITE_DROP_VIEW;
2171 }
danielk19774b2688a2006-06-20 11:01:07 +00002172#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002173 }else if( IsVirtual(pTab) ){
2174 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002175 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002176#endif
drhe5f9c642003-01-13 23:27:31 +00002177 }else{
danielk197753c0f742005-03-29 03:10:59 +00002178 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002179 code = SQLITE_DROP_TEMP_TABLE;
2180 }else{
2181 code = SQLITE_DROP_TABLE;
2182 }
2183 }
danielk1977f1a381e2006-06-16 08:01:02 +00002184 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002185 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002186 }
danielk1977a8858102004-05-28 12:11:21 +00002187 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2188 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002189 }
drhe5f9c642003-01-13 23:27:31 +00002190 }
2191#endif
drh08ccfaa2011-10-07 23:52:25 +00002192 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2193 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002194 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002195 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002196 }
danielk1977576ec6b2005-01-21 11:55:25 +00002197
2198#ifndef SQLITE_OMIT_VIEW
2199 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2200 ** on a table.
2201 */
danielk1977a8858102004-05-28 12:11:21 +00002202 if( isView && pTab->pSelect==0 ){
2203 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2204 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002205 }
danielk1977a8858102004-05-28 12:11:21 +00002206 if( !isView && pTab->pSelect ){
2207 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2208 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002209 }
danielk1977576ec6b2005-01-21 11:55:25 +00002210#endif
drh75897232000-05-29 14:26:00 +00002211
drh1ccde152000-06-17 13:12:39 +00002212 /* Generate code to remove the table from the master table
2213 ** on disk.
2214 */
danielk19774adee202004-05-08 08:23:19 +00002215 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002216 if( v ){
drh77658e22007-12-04 16:54:52 +00002217 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002218 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002219 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002220 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002221 }
danielk1977a8858102004-05-28 12:11:21 +00002222
2223exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002224 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002225}
2226
2227/*
drhc2eef3b2002-08-31 18:53:06 +00002228** This routine is called to create a new foreign key on the table
2229** currently under construction. pFromCol determines which columns
2230** in the current table point to the foreign key. If pFromCol==0 then
2231** connect the key to the last column inserted. pTo is the name of
2232** the table referred to. pToCol is a list of tables in the other
2233** pTo table that the foreign key points to. flags contains all
2234** information about the conflict resolution algorithms specified
2235** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2236**
2237** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002238** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002239**
2240** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002241** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002242*/
danielk19774adee202004-05-08 08:23:19 +00002243void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002244 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002245 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002246 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002247 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002248 int flags /* Conflict resolution algorithms. */
2249){
danielk197718576932008-08-06 13:47:40 +00002250 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002251#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002252 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002253 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002254 Table *p = pParse->pNewTable;
2255 int nByte;
2256 int i;
2257 int nCol;
2258 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002259
2260 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002261 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002262 if( pFromCol==0 ){
2263 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002264 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002265 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002266 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002267 " should reference only one column of table %T",
2268 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002269 goto fk_end;
2270 }
2271 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002272 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002273 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002274 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002275 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002276 goto fk_end;
2277 }else{
danielk19770202b292004-06-09 09:55:16 +00002278 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002279 }
drhe61922a2009-05-02 13:29:37 +00002280 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002281 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002282 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002283 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002284 }
2285 }
drh633e6d52008-07-28 19:34:53 +00002286 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002287 if( pFKey==0 ){
2288 goto fk_end;
2289 }
drhc2eef3b2002-08-31 18:53:06 +00002290 pFKey->pFrom = p;
2291 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002292 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002293 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002294 memcpy(z, pTo->z, pTo->n);
2295 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002296 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002297 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002298 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002299 if( pFromCol==0 ){
2300 pFKey->aCol[0].iFrom = p->nCol-1;
2301 }else{
2302 for(i=0; i<nCol; i++){
2303 int j;
2304 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002305 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002306 pFKey->aCol[i].iFrom = j;
2307 break;
2308 }
2309 }
2310 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002311 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002312 "unknown column \"%s\" in foreign key definition",
2313 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002314 goto fk_end;
2315 }
2316 }
2317 }
2318 if( pToCol ){
2319 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002320 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002321 pFKey->aCol[i].zCol = z;
2322 memcpy(z, pToCol->a[i].zName, n);
2323 z[n] = 0;
2324 z += n+1;
2325 }
2326 }
2327 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002328 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2329 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002330
drh21206082011-04-04 18:22:02 +00002331 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002332 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2333 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2334 );
danf59c5ca2009-09-22 16:55:38 +00002335 if( pNextTo==pFKey ){
2336 db->mallocFailed = 1;
2337 goto fk_end;
2338 }
dan1da40a32009-09-19 17:00:31 +00002339 if( pNextTo ){
2340 assert( pNextTo->pPrevTo==0 );
2341 pFKey->pNextTo = pNextTo;
2342 pNextTo->pPrevTo = pFKey;
2343 }
2344
drhc2eef3b2002-08-31 18:53:06 +00002345 /* Link the foreign key to the table as the last step.
2346 */
2347 p->pFKey = pFKey;
2348 pFKey = 0;
2349
2350fk_end:
drh633e6d52008-07-28 19:34:53 +00002351 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002352#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002353 sqlite3ExprListDelete(db, pFromCol);
2354 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002355}
2356
2357/*
2358** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2359** clause is seen as part of a foreign key definition. The isDeferred
2360** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2361** The behavior of the most recently created foreign key is adjusted
2362** accordingly.
2363*/
danielk19774adee202004-05-08 08:23:19 +00002364void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002365#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002366 Table *pTab;
2367 FKey *pFKey;
2368 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002369 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002370 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002371#endif
drhc2eef3b2002-08-31 18:53:06 +00002372}
2373
2374/*
drh063336a2004-11-05 20:58:39 +00002375** Generate code that will erase and refill index *pIdx. This is
2376** used to initialize a newly created index or to recompute the
2377** content of an index in response to a REINDEX command.
2378**
2379** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002380** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002381** root page number of the index. If memRootPage is negative, then
2382** the index already exists and must be cleared before being refilled and
2383** the root page number of the index is taken from pIndex->tnum.
2384*/
2385static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2386 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002387 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2388 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002389 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002390 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002391 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002392 int tnum; /* Root page of index */
2393 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002394 KeyInfo *pKey; /* KeyInfo for index */
drhb07028f2011-10-14 21:49:18 +00002395#ifdef SQLITE_OMIT_MERGE_SORT
drh2d401ab2008-01-10 23:50:11 +00002396 int regIdxKey; /* Registers containing the index key */
drhb07028f2011-10-14 21:49:18 +00002397#endif
drh2d401ab2008-01-10 23:50:11 +00002398 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002399 sqlite3 *db = pParse->db; /* The database connection */
2400 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002401
danielk19771d54df82004-11-23 15:41:16 +00002402#ifndef SQLITE_OMIT_AUTHORIZATION
2403 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002404 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002405 return;
2406 }
2407#endif
2408
danielk1977c00da102006-01-07 13:21:04 +00002409 /* Require a write-lock on the table to perform this operation */
2410 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2411
drh063336a2004-11-05 20:58:39 +00002412 v = sqlite3GetVdbe(pParse);
2413 if( v==0 ) return;
2414 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002415 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002416 }else{
2417 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002418 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002419 }
danielk1977b3bf5562006-01-10 17:58:23 +00002420 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002421 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002422 (char *)pKey, P4_KEYINFO_HANDOFF);
dan428c2182012-08-06 18:50:11 +00002423 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
dana20fde62011-07-12 14:28:05 +00002424
drhca892a72011-09-03 00:17:51 +00002425#ifndef SQLITE_OMIT_MERGE_SORT
dan689ab892011-08-12 15:02:00 +00002426 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002427 iSorter = pParse->nTab++;
2428 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
drhb07028f2011-10-14 21:49:18 +00002429#else
2430 iSorter = iTab;
drhca892a72011-09-03 00:17:51 +00002431#endif
dana20fde62011-07-12 14:28:05 +00002432
2433 /* Open the table. Loop through all rows of the table, inserting index
2434 ** records into the sorter. */
danielk1977c00da102006-01-07 13:21:04 +00002435 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002436 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002437 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002438
drhca892a72011-09-03 00:17:51 +00002439#ifndef SQLITE_OMIT_MERGE_SORT
drhb07028f2011-10-14 21:49:18 +00002440 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drhca892a72011-09-03 00:17:51 +00002441 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
2442 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2443 sqlite3VdbeJumpHere(v, addr1);
2444 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
2445 if( pIndex->onError!=OE_None ){
2446 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2447 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2448 addr2 = sqlite3VdbeCurrentAddr(v);
2449 sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
drhd91c1a12013-02-09 13:58:25 +00002450 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
2451 OE_Abort, "indexed columns are not unique", P4_STATIC
drhca892a72011-09-03 00:17:51 +00002452 );
2453 }else{
2454 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002455 }
drhca892a72011-09-03 00:17:51 +00002456 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2457 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2458 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2459#else
drhb07028f2011-10-14 21:49:18 +00002460 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2461 addr2 = addr1 + 1;
drh7f057c92005-06-24 03:53:06 +00002462 if( pIndex->onError!=OE_None ){
danielk1977de630352009-05-04 11:42:29 +00002463 const int regRowid = regIdxKey + pIndex->nColumn;
2464 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2465 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
drh2d401ab2008-01-10 23:50:11 +00002466
danielk1977de630352009-05-04 11:42:29 +00002467 /* The registers accessed by the OP_IsUnique opcode were allocated
2468 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2469 ** call above. Just before that function was freed they were released
2470 ** (made available to the compiler for reuse) using
2471 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2472 ** opcode use the values stored within seems dangerous. However, since
2473 ** we can be sure that no other temp registers have been allocated
2474 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2475 */
2476 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
drhd91c1a12013-02-09 13:58:25 +00002477 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
2478 "indexed columns are not unique", P4_STATIC);
drh4343fea2004-11-05 23:46:15 +00002479 }
drhca892a72011-09-03 00:17:51 +00002480 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
danielk1977de630352009-05-04 11:42:29 +00002481 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drhca892a72011-09-03 00:17:51 +00002482#endif
drh2d401ab2008-01-10 23:50:11 +00002483 sqlite3ReleaseTempReg(pParse, regRecord);
drhca892a72011-09-03 00:17:51 +00002484 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
drhd654be82005-09-20 17:42:23 +00002485 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002486
drh66a51672008-01-03 00:01:23 +00002487 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2488 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002489 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002490}
2491
2492/*
drh23bf66d2004-12-14 03:34:34 +00002493** Create a new index for an SQL table. pName1.pName2 is the name of the index
2494** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002495** be NULL for a primary key or an index that is created to satisfy a
2496** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002497** as the table to be indexed. pParse->pNewTable is a table that is
2498** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002499**
drh382c0242001-10-06 16:33:02 +00002500** pList is a list of columns to be indexed. pList will be NULL if this
2501** is a primary key or unique-constraint on the most recent column added
2502** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002503**
2504** If the index is created successfully, return a pointer to the new Index
2505** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2506** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002507*/
dan1da40a32009-09-19 17:00:31 +00002508Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002509 Parse *pParse, /* All information about this parse */
2510 Token *pName1, /* First part of index name. May be NULL */
2511 Token *pName2, /* Second part of index name. May be NULL */
2512 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002513 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002514 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002515 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002516 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002517 int sortOrder, /* Sort order of primary key when pList==NULL */
2518 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002519){
dan1da40a32009-09-19 17:00:31 +00002520 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002521 Table *pTab = 0; /* Table to be indexed */
2522 Index *pIndex = 0; /* The index to be created */
2523 char *zName = 0; /* Name of the index */
2524 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002525 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002526 Token nullId; /* Fake token for an empty ID list */
2527 DbFixer sFix; /* For assigning database names to pTable */
2528 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002529 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002530 Db *pDb; /* The specific table containing the indexed database */
2531 int iDb; /* Index of the database that is being written */
2532 Token *pName = 0; /* Unqualified name of the index to create */
2533 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002534 int nCol;
2535 int nExtra = 0;
2536 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002537
drhd3001712009-05-12 17:46:53 +00002538 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
drh8af73d42009-05-13 22:58:28 +00002539 assert( pParse->nErr==0 ); /* Never called with prior errors */
2540 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002541 goto exit_create_index;
2542 }
2543 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002544 goto exit_create_index;
2545 }
drhdaffd0e2001-04-11 14:28:42 +00002546
drh75897232000-05-29 14:26:00 +00002547 /*
2548 ** Find the table that is to be indexed. Return early if not found.
2549 */
danielk1977cbb18d22004-05-28 11:37:27 +00002550 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002551
2552 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002553 ** to search for the table. 'Fix' the table name to this db
2554 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002555 */
2556 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002557 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002558 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002559 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002560
danielk197753c0f742005-03-29 03:10:59 +00002561#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002562 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002563 ** is a temp table. If so, set the database to 1. Do not do this
2564 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002565 */
danielk1977fe910332007-12-02 11:46:34 +00002566 if( !db->init.busy ){
2567 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002568 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002569 iDb = 1;
2570 }
danielk1977ef2cb632004-05-29 02:37:19 +00002571 }
danielk197753c0f742005-03-29 03:10:59 +00002572#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002573
2574 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2575 sqlite3FixSrcList(&sFix, pTblName)
2576 ){
drh85c23c62005-08-20 03:03:04 +00002577 /* Because the parser constructs pTblName from a single identifier,
2578 ** sqlite3FixSrcList can never fail. */
2579 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002580 }
dan41fb5cd2012-10-04 19:33:00 +00002581 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002582 assert( db->mallocFailed==0 || pTab==0 );
2583 if( pTab==0 ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002584 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002585 }else{
drhe3c41372001-09-17 20:25:58 +00002586 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002587 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002588 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002589 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002590 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002591 }
drhfdd6e852005-12-16 01:06:16 +00002592 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002593
drhd3001712009-05-12 17:46:53 +00002594 assert( pTab!=0 );
2595 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002596 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh503a6862013-03-01 01:07:17 +00002597 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002598 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002599 goto exit_create_index;
2600 }
danielk1977576ec6b2005-01-21 11:55:25 +00002601#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002602 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002603 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002604 goto exit_create_index;
2605 }
danielk1977576ec6b2005-01-21 11:55:25 +00002606#endif
danielk19775ee9d692006-06-21 12:36:25 +00002607#ifndef SQLITE_OMIT_VIRTUALTABLE
2608 if( IsVirtual(pTab) ){
2609 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2610 goto exit_create_index;
2611 }
2612#endif
drh75897232000-05-29 14:26:00 +00002613
2614 /*
2615 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002616 ** index or table with the same name.
2617 **
2618 ** Exception: If we are reading the names of permanent indices from the
2619 ** sqlite_master table (because some other process changed the schema) and
2620 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002621 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002622 **
2623 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002624 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2625 ** own name.
drh75897232000-05-29 14:26:00 +00002626 */
danielk1977d8123362004-06-12 09:25:12 +00002627 if( pName ){
drh17435752007-08-16 04:30:38 +00002628 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002629 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002630 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002631 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002632 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002633 }
danielk1977d8123362004-06-12 09:25:12 +00002634 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002635 if( sqlite3FindTable(db, zName, 0)!=0 ){
2636 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2637 goto exit_create_index;
2638 }
2639 }
danielk197759a33f92007-03-17 10:26:59 +00002640 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2641 if( !ifNotExist ){
2642 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002643 }else{
2644 assert( !db->init.busy );
2645 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002646 }
danielk197759a33f92007-03-17 10:26:59 +00002647 goto exit_create_index;
2648 }
danielk1977a21c6b62005-01-24 10:25:59 +00002649 }else{
drhadbca9c2001-09-27 15:11:53 +00002650 int n;
2651 Index *pLoop;
2652 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002653 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002654 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002655 goto exit_create_index;
2656 }
drh75897232000-05-29 14:26:00 +00002657 }
2658
drhe5f9c642003-01-13 23:27:31 +00002659 /* Check for authorization to create an index.
2660 */
2661#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002662 {
drhfdd6e852005-12-16 01:06:16 +00002663 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002664 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002665 goto exit_create_index;
2666 }
2667 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002668 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002669 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002670 goto exit_create_index;
2671 }
drhe5f9c642003-01-13 23:27:31 +00002672 }
2673#endif
2674
drh75897232000-05-29 14:26:00 +00002675 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002676 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002677 ** So create a fake list to simulate this.
2678 */
2679 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002680 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002681 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002682 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002683 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002684 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002685 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002686 }
2687
danielk1977b3bf5562006-01-10 17:58:23 +00002688 /* Figure out how many bytes of space are required to store explicitly
2689 ** specified collation sequence names.
2690 */
2691 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002692 Expr *pExpr = pList->a[i].pExpr;
2693 if( pExpr ){
drhae80dde2012-12-06 21:16:43 +00002694 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
2695 if( pColl ){
drhd3001712009-05-12 17:46:53 +00002696 nExtra += (1 + sqlite3Strlen30(pColl->zName));
2697 }
danielk1977b3bf5562006-01-10 17:58:23 +00002698 }
2699 }
2700
drh75897232000-05-29 14:26:00 +00002701 /*
2702 ** Allocate the index structure.
2703 */
drhea678832008-12-10 19:26:22 +00002704 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002705 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002706 pIndex = sqlite3DbMallocZero(db,
drhe0711b42012-01-05 12:38:02 +00002707 ROUND8(sizeof(Index)) + /* Index structure */
drhe09b84c2011-11-14 02:53:54 +00002708 ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
2709 sizeof(char *)*nCol + /* Index.azColl */
2710 sizeof(int)*nCol + /* Index.aiColumn */
2711 sizeof(u8)*nCol + /* Index.aSortOrder */
2712 nName + 1 + /* Index.zName */
2713 nExtra /* Collation sequence names */
danielk1977b3bf5562006-01-10 17:58:23 +00002714 );
drh17435752007-08-16 04:30:38 +00002715 if( db->mallocFailed ){
2716 goto exit_create_index;
2717 }
drhe0711b42012-01-05 12:38:02 +00002718 zExtra = (char*)pIndex;
2719 pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
drhe09b84c2011-11-14 02:53:54 +00002720 pIndex->azColl = (char**)
2721 ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
2722 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
2723 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh78aecb72006-02-10 18:08:09 +00002724 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
drhfaacf172011-08-12 01:51:45 +00002725 pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
danielk1977b3bf5562006-01-10 17:58:23 +00002726 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2727 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002728 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002729 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002730 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002731 pIndex->onError = (u8)onError;
2732 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002733 pIndex->pSchema = db->aDb[iDb].pSchema;
drh21206082011-04-04 18:22:02 +00002734 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002735
drhfdd6e852005-12-16 01:06:16 +00002736 /* Check to see if we should honor DESC requests on index columns
2737 */
danielk1977da184232006-01-05 11:34:32 +00002738 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002739 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002740 }else{
2741 sortOrderMask = 0; /* Ignore DESC */
2742 }
2743
drh1ccde152000-06-17 13:12:39 +00002744 /* Scan the names of the columns of the table to be indexed and
2745 ** load the column indices into the Index structure. Report an error
2746 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002747 **
2748 ** TODO: Add a test to make sure that the same column is not named
2749 ** more than once within the same index. Only the first instance of
2750 ** the column will ever be used by the optimizer. Note that using the
2751 ** same column more than once cannot be an error because that would
2752 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002753 */
drhfdd6e852005-12-16 01:06:16 +00002754 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2755 const char *zColName = pListItem->zName;
2756 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002757 int requestedSortOrder;
drhae80dde2012-12-06 21:16:43 +00002758 CollSeq *pColl; /* Collating sequence */
drha34001c2007-02-02 12:44:37 +00002759 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002760
drhfdd6e852005-12-16 01:06:16 +00002761 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2762 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002763 }
2764 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002765 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002766 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00002767 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00002768 goto exit_create_index;
2769 }
drh967e8b72000-06-21 13:59:10 +00002770 pIndex->aiColumn[i] = j;
drhae80dde2012-12-06 21:16:43 +00002771 if( pListItem->pExpr
2772 && (pColl = sqlite3ExprCollSeq(pParse, pListItem->pExpr))!=0
2773 ){
drhd3001712009-05-12 17:46:53 +00002774 int nColl;
drhae80dde2012-12-06 21:16:43 +00002775 zColl = pColl->zName;
drhd3001712009-05-12 17:46:53 +00002776 nColl = sqlite3Strlen30(zColl) + 1;
2777 assert( nExtra>=nColl );
2778 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002779 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002780 zExtra += nColl;
2781 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002782 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002783 zColl = pTab->aCol[j].zColl;
2784 if( !zColl ){
drha19b8962012-06-06 10:56:22 +00002785 zColl = "BINARY";
danielk1977b3bf5562006-01-10 17:58:23 +00002786 }
danielk19770202b292004-06-09 09:55:16 +00002787 }
drhb7f24de2009-05-13 17:35:23 +00002788 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002789 goto exit_create_index;
2790 }
danielk1977b3bf5562006-01-10 17:58:23 +00002791 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002792 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002793 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002794 }
drh51147ba2005-07-23 22:59:55 +00002795 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002796
danielk1977d8123362004-06-12 09:25:12 +00002797 if( pTab==pParse->pNewTable ){
2798 /* This routine has been called to create an automatic index as a
2799 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2800 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2801 ** i.e. one of:
2802 **
2803 ** CREATE TABLE t(x PRIMARY KEY, y);
2804 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2805 **
2806 ** Either way, check to see if the table already has such an index. If
2807 ** so, don't bother creating this one. This only applies to
2808 ** automatically created indices. Users can do as they wish with
2809 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002810 **
2811 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2812 ** (and thus suppressing the second one) even if they have different
2813 ** sort orders.
2814 **
2815 ** If there are different collating sequences or if the columns of
2816 ** the constraint occur in different orders, then the constraints are
2817 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002818 */
2819 Index *pIdx;
2820 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2821 int k;
2822 assert( pIdx->onError!=OE_None );
2823 assert( pIdx->autoIndex );
2824 assert( pIndex->onError!=OE_None );
2825
2826 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2827 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002828 const char *z1;
2829 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002830 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002831 z1 = pIdx->azColl[k];
2832 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002833 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002834 }
2835 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002836 if( pIdx->onError!=pIndex->onError ){
2837 /* This constraint creates the same index as a previous
2838 ** constraint specified somewhere in the CREATE TABLE statement.
2839 ** However the ON CONFLICT clauses are different. If both this
2840 ** constraint and the previous equivalent constraint have explicit
2841 ** ON CONFLICT clauses this is an error. Otherwise, use the
2842 ** explicitly specified behaviour for the index.
2843 */
2844 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2845 sqlite3ErrorMsg(pParse,
2846 "conflicting ON CONFLICT clauses specified", 0);
2847 }
2848 if( pIdx->onError==OE_Default ){
2849 pIdx->onError = pIndex->onError;
2850 }
2851 }
danielk1977d8123362004-06-12 09:25:12 +00002852 goto exit_create_index;
2853 }
2854 }
2855 }
2856
drh75897232000-05-29 14:26:00 +00002857 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002858 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002859 */
drh234c39d2004-07-24 03:30:47 +00002860 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002861 Index *p;
drh21206082011-04-04 18:22:02 +00002862 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002863 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002864 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002865 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002866 if( p ){
2867 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002868 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002869 goto exit_create_index;
2870 }
drh5e00f6c2001-09-13 13:46:56 +00002871 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002872 if( pTblName!=0 ){
2873 pIndex->tnum = db->init.newTnum;
2874 }
drhd78eeee2001-09-13 16:18:53 +00002875 }
2876
drh1d85d932004-02-14 23:05:52 +00002877 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002878 ** involves writing the index into the master table and filling in the
2879 ** index with the current table contents.
2880 **
drh1d85d932004-02-14 23:05:52 +00002881 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2882 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002883 ** CREATE INDEX statements are read out of the master table. In
2884 ** the latter case the index already exists on disk, which is why
2885 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002886 **
danielk1977cbb18d22004-05-28 11:37:27 +00002887 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002888 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2889 ** has just been created, it contains no data and the index initialization
2890 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002891 */
drhd3001712009-05-12 17:46:53 +00002892 else{ /* if( db->init.busy==0 ) */
drhadbca9c2001-09-27 15:11:53 +00002893 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002894 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002895 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002896
danielk19774adee202004-05-08 08:23:19 +00002897 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002898 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002899
drhfdd6e852005-12-16 01:06:16 +00002900
drh063336a2004-11-05 20:58:39 +00002901 /* Create the rootpage for the index
2902 */
drhaee128d2005-02-14 20:48:18 +00002903 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002904 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002905
2906 /* Gather the complete text of the CREATE INDEX statement into
2907 ** the zStmt variable
2908 */
drhd3001712009-05-12 17:46:53 +00002909 if( pStart ){
2910 assert( pEnd!=0 );
drh063336a2004-11-05 20:58:39 +00002911 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002912 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002913 onError==OE_None ? "" : " UNIQUE",
dan28e4e352011-06-24 18:43:23 +00002914 (int)(pEnd->z - pName->z) + 1,
drh063336a2004-11-05 20:58:39 +00002915 pName->z);
2916 }else{
2917 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002918 /* zStmt = sqlite3MPrintf(""); */
2919 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002920 }
drh063336a2004-11-05 20:58:39 +00002921
2922 /* Add an entry in sqlite_master for this index
2923 */
2924 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002925 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002926 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2927 pIndex->zName,
2928 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002929 iMem,
drh063336a2004-11-05 20:58:39 +00002930 zStmt
2931 );
drh633e6d52008-07-28 19:34:53 +00002932 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002933
danielk1977a21c6b62005-01-24 10:25:59 +00002934 /* Fill the index with data and reparse the schema. Code an OP_Expire
2935 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002936 */
danielk1977cbb18d22004-05-28 11:37:27 +00002937 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002938 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002939 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00002940 sqlite3VdbeAddParseSchemaOp(v, iDb,
2941 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00002942 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002943 }
drh75897232000-05-29 14:26:00 +00002944 }
2945
danielk1977d8123362004-06-12 09:25:12 +00002946 /* When adding an index to the list of indices for a table, make
2947 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002948 ** OE_Ignore. This is necessary for the correct constraint check
2949 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2950 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002951 */
drh234c39d2004-07-24 03:30:47 +00002952 if( db->init.busy || pTblName==0 ){
2953 if( onError!=OE_Replace || pTab->pIndex==0
2954 || pTab->pIndex->onError==OE_Replace){
2955 pIndex->pNext = pTab->pIndex;
2956 pTab->pIndex = pIndex;
2957 }else{
2958 Index *pOther = pTab->pIndex;
2959 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2960 pOther = pOther->pNext;
2961 }
2962 pIndex->pNext = pOther->pNext;
2963 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002964 }
dan1da40a32009-09-19 17:00:31 +00002965 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00002966 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002967 }
danielk1977d8123362004-06-12 09:25:12 +00002968
drh75897232000-05-29 14:26:00 +00002969 /* Clean up before exiting */
2970exit_create_index:
drh956bc922004-07-24 17:38:29 +00002971 if( pIndex ){
drhb9755982010-07-24 16:34:37 +00002972 sqlite3DbFree(db, pIndex->zColAff);
danielk1977cb9d8d82009-03-18 18:43:36 +00002973 sqlite3DbFree(db, pIndex);
drh956bc922004-07-24 17:38:29 +00002974 }
drh633e6d52008-07-28 19:34:53 +00002975 sqlite3ExprListDelete(db, pList);
2976 sqlite3SrcListDelete(db, pTblName);
2977 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00002978 return pRet;
drh75897232000-05-29 14:26:00 +00002979}
2980
2981/*
drh51147ba2005-07-23 22:59:55 +00002982** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002983** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002984**
2985** aiRowEst[0] is suppose to contain the number of elements in the index.
2986** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2987** number of rows in the table that match any particular value of the
2988** first column of the index. aiRowEst[2] is an estimate of the number
2989** of rows that match any particular combiniation of the first 2 columns
2990** of the index. And so forth. It must always be the case that
2991*
2992** aiRowEst[N]<=aiRowEst[N-1]
2993** aiRowEst[N]>=1
2994**
2995** Apart from that, we have little to go on besides intuition as to
2996** how aiRowEst[] should be initialized. The numbers generated here
2997** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002998*/
2999void sqlite3DefaultRowEst(Index *pIdx){
drhfaacf172011-08-12 01:51:45 +00003000 tRowcnt *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00003001 int i;
drhfaacf172011-08-12 01:51:45 +00003002 tRowcnt n;
drh28c4cf42005-07-27 20:41:43 +00003003 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00003004 a[0] = pIdx->pTable->nRowEst;
3005 if( a[0]<10 ) a[0] = 10;
3006 n = 10;
3007 for(i=1; i<=pIdx->nColumn; i++){
3008 a[i] = n;
3009 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00003010 }
3011 if( pIdx->onError!=OE_None ){
3012 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00003013 }
3014}
3015
3016/*
drh74e24cd2002-01-09 03:19:59 +00003017** This routine will drop an existing named index. This routine
3018** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003019*/
drh4d91a702006-01-04 15:54:36 +00003020void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003021 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003022 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003023 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003024 int iDb;
drh75897232000-05-29 14:26:00 +00003025
drh8af73d42009-05-13 22:58:28 +00003026 assert( pParse->nErr==0 ); /* Never called with prior errors */
3027 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003028 goto exit_drop_index;
3029 }
drhd24cc422003-03-27 12:51:24 +00003030 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003031 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3032 goto exit_drop_index;
3033 }
danielk19774adee202004-05-08 08:23:19 +00003034 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003035 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003036 if( !ifExists ){
3037 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003038 }else{
3039 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003040 }
drha6ecd332004-06-10 00:29:09 +00003041 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003042 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003043 }
drh485b39b2002-07-13 03:11:52 +00003044 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00003045 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003046 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003047 goto exit_drop_index;
3048 }
danielk1977da184232006-01-05 11:34:32 +00003049 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003050#ifndef SQLITE_OMIT_AUTHORIZATION
3051 {
3052 int code = SQLITE_DROP_INDEX;
3053 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003054 const char *zDb = db->aDb[iDb].zName;
3055 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003056 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003057 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003058 }
danielk1977da184232006-01-05 11:34:32 +00003059 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003060 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003061 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003062 }
drhed6c8672003-01-12 18:02:16 +00003063 }
drhe5f9c642003-01-13 23:27:31 +00003064#endif
drh75897232000-05-29 14:26:00 +00003065
3066 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003067 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003068 if( v ){
drh77658e22007-12-04 16:54:52 +00003069 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003070 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003071 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003072 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003073 );
drha5ae4c32011-08-07 01:31:52 +00003074 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003075 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003076 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003077 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003078 }
3079
drhd24cc422003-03-27 12:51:24 +00003080exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003081 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003082}
3083
3084/*
dan9ace1122012-03-29 07:51:45 +00003085** pArray is a pointer to an array of objects. Each object in the
3086** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3087** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003088**
dan9ace1122012-03-29 07:51:45 +00003089** When this function is called, *pnEntry contains the current size of
3090** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3091** in total).
drh13449892005-09-07 21:22:45 +00003092**
dan9ace1122012-03-29 07:51:45 +00003093** If the realloc() is successful (i.e. if no OOM condition occurs), the
3094** space allocated for the new object is zeroed, *pnEntry updated to
3095** reflect the new size of the array and a pointer to the new allocation
3096** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003097**
dan9ace1122012-03-29 07:51:45 +00003098** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3099** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003100*/
drhcf643722007-03-27 13:36:37 +00003101void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003102 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003103 void *pArray, /* Array of objects. Might be reallocated */
3104 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003105 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003106 int *pIdx /* Write the index of a new slot here */
3107){
3108 char *z;
drh6c535152012-02-02 03:38:30 +00003109 int n = *pnEntry;
3110 if( (n & (n-1))==0 ){
3111 int sz = (n==0) ? 1 : 2*n;
3112 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003113 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003114 *pIdx = -1;
3115 return pArray;
drh13449892005-09-07 21:22:45 +00003116 }
drhcf643722007-03-27 13:36:37 +00003117 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003118 }
drhcf643722007-03-27 13:36:37 +00003119 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003120 memset(&z[n * szEntry], 0, szEntry);
3121 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003122 ++*pnEntry;
3123 return pArray;
drh13449892005-09-07 21:22:45 +00003124}
3125
3126/*
drh75897232000-05-29 14:26:00 +00003127** Append a new element to the given IdList. Create a new IdList if
3128** need be.
drhdaffd0e2001-04-11 14:28:42 +00003129**
3130** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003131*/
drh17435752007-08-16 04:30:38 +00003132IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003133 int i;
drh75897232000-05-29 14:26:00 +00003134 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003135 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003136 if( pList==0 ) return 0;
3137 }
drhcf643722007-03-27 13:36:37 +00003138 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003139 db,
drhcf643722007-03-27 13:36:37 +00003140 pList->a,
3141 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003142 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003143 &i
3144 );
drh13449892005-09-07 21:22:45 +00003145 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003146 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003147 return 0;
drh75897232000-05-29 14:26:00 +00003148 }
drh17435752007-08-16 04:30:38 +00003149 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003150 return pList;
3151}
3152
3153/*
drhfe05af82005-07-21 03:14:59 +00003154** Delete an IdList.
3155*/
drh633e6d52008-07-28 19:34:53 +00003156void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003157 int i;
3158 if( pList==0 ) return;
3159 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003160 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003161 }
drh633e6d52008-07-28 19:34:53 +00003162 sqlite3DbFree(db, pList->a);
3163 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003164}
3165
3166/*
3167** Return the index in pList of the identifier named zId. Return -1
3168** if not found.
3169*/
3170int sqlite3IdListIndex(IdList *pList, const char *zName){
3171 int i;
3172 if( pList==0 ) return -1;
3173 for(i=0; i<pList->nId; i++){
3174 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3175 }
3176 return -1;
3177}
3178
3179/*
drha78c22c2008-11-11 18:28:58 +00003180** Expand the space allocated for the given SrcList object by
3181** creating nExtra new slots beginning at iStart. iStart is zero based.
3182** New slots are zeroed.
3183**
3184** For example, suppose a SrcList initially contains two entries: A,B.
3185** To append 3 new entries onto the end, do this:
3186**
3187** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3188**
3189** After the call above it would contain: A, B, nil, nil, nil.
3190** If the iStart argument had been 1 instead of 2, then the result
3191** would have been: A, nil, nil, nil, B. To prepend the new slots,
3192** the iStart value would be 0. The result then would
3193** be: nil, nil, nil, A, B.
3194**
3195** If a memory allocation fails the SrcList is unchanged. The
3196** db->mallocFailed flag will be set to true.
3197*/
3198SrcList *sqlite3SrcListEnlarge(
3199 sqlite3 *db, /* Database connection to notify of OOM errors */
3200 SrcList *pSrc, /* The SrcList to be enlarged */
3201 int nExtra, /* Number of new slots to add to pSrc->a[] */
3202 int iStart /* Index in pSrc->a[] of first new slot */
3203){
3204 int i;
3205
3206 /* Sanity checking on calling parameters */
3207 assert( iStart>=0 );
3208 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003209 assert( pSrc!=0 );
3210 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003211
3212 /* Allocate additional space if needed */
3213 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3214 SrcList *pNew;
3215 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003216 int nGot;
drha78c22c2008-11-11 18:28:58 +00003217 pNew = sqlite3DbRealloc(db, pSrc,
3218 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3219 if( pNew==0 ){
3220 assert( db->mallocFailed );
3221 return pSrc;
3222 }
3223 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003224 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003225 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003226 }
3227
3228 /* Move existing slots that come after the newly inserted slots
3229 ** out of the way */
3230 for(i=pSrc->nSrc-1; i>=iStart; i--){
3231 pSrc->a[i+nExtra] = pSrc->a[i];
3232 }
shane18e526c2008-12-10 22:30:24 +00003233 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003234
3235 /* Zero the newly allocated slots */
3236 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3237 for(i=iStart; i<iStart+nExtra; i++){
3238 pSrc->a[i].iCursor = -1;
3239 }
3240
3241 /* Return a pointer to the enlarged SrcList */
3242 return pSrc;
3243}
3244
3245
3246/*
drhad3cab52002-05-24 02:04:32 +00003247** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003248** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003249**
drha78c22c2008-11-11 18:28:58 +00003250** A SrcList is returned, or NULL if there is an OOM error. The returned
3251** SrcList might be the same as the SrcList that was input or it might be
3252** a new one. If an OOM error does occurs, then the prior value of pList
3253** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003254**
3255** If pDatabase is not null, it means that the table has an optional
3256** database name prefix. Like this: "database.table". The pDatabase
3257** points to the table name and the pTable points to the database name.
3258** The SrcList.a[].zName field is filled with the table name which might
3259** come from pTable (if pDatabase is NULL) or from pDatabase.
3260** SrcList.a[].zDatabase is filled with the database name from pTable,
3261** or with NULL if no database is specified.
3262**
3263** In other words, if call like this:
3264**
drh17435752007-08-16 04:30:38 +00003265** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003266**
3267** Then B is a table name and the database name is unspecified. If called
3268** like this:
3269**
drh17435752007-08-16 04:30:38 +00003270** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003271**
drhd3001712009-05-12 17:46:53 +00003272** Then C is the table name and B is the database name. If C is defined
3273** then so is B. In other words, we never have a case where:
3274**
3275** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003276**
3277** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3278** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003279*/
drh17435752007-08-16 04:30:38 +00003280SrcList *sqlite3SrcListAppend(
3281 sqlite3 *db, /* Connection to notify of malloc failures */
3282 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3283 Token *pTable, /* Table to append */
3284 Token *pDatabase /* Database of the table */
3285){
drha99db3b2004-06-19 14:49:12 +00003286 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003287 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003288 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003289 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003290 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003291 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003292 }
drha78c22c2008-11-11 18:28:58 +00003293 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3294 if( db->mallocFailed ){
3295 sqlite3SrcListDelete(db, pList);
3296 return 0;
drhad3cab52002-05-24 02:04:32 +00003297 }
drha78c22c2008-11-11 18:28:58 +00003298 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003299 if( pDatabase && pDatabase->z==0 ){
3300 pDatabase = 0;
3301 }
drhd3001712009-05-12 17:46:53 +00003302 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003303 Token *pTemp = pDatabase;
3304 pDatabase = pTable;
3305 pTable = pTemp;
3306 }
drh17435752007-08-16 04:30:38 +00003307 pItem->zName = sqlite3NameFromToken(db, pTable);
3308 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003309 return pList;
3310}
3311
3312/*
drhdfe88ec2008-11-03 20:55:06 +00003313** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003314*/
danielk19774adee202004-05-08 08:23:19 +00003315void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003316 int i;
drh9b3187e2005-01-18 14:45:47 +00003317 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003318 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003319 if( pList ){
3320 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3321 if( pItem->iCursor>=0 ) break;
3322 pItem->iCursor = pParse->nTab++;
3323 if( pItem->pSelect ){
3324 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3325 }
drh63eb5f22003-04-29 16:20:44 +00003326 }
3327 }
3328}
3329
3330/*
drhad3cab52002-05-24 02:04:32 +00003331** Delete an entire SrcList including all its substructure.
3332*/
drh633e6d52008-07-28 19:34:53 +00003333void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003334 int i;
drhbe5c89a2004-07-26 00:31:09 +00003335 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003336 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003337 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003338 sqlite3DbFree(db, pItem->zDatabase);
3339 sqlite3DbFree(db, pItem->zName);
3340 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003341 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003342 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003343 sqlite3SelectDelete(db, pItem->pSelect);
3344 sqlite3ExprDelete(db, pItem->pOn);
3345 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003346 }
drh633e6d52008-07-28 19:34:53 +00003347 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003348}
3349
drh982cef72000-05-30 16:27:03 +00003350/*
drh61dfc312006-12-16 16:25:15 +00003351** This routine is called by the parser to add a new term to the
3352** end of a growing FROM clause. The "p" parameter is the part of
3353** the FROM clause that has already been constructed. "p" is NULL
3354** if this is the first term of the FROM clause. pTable and pDatabase
3355** are the name of the table and database named in the FROM clause term.
3356** pDatabase is NULL if the database name qualifier is missing - the
3357** usual case. If the term has a alias, then pAlias points to the
3358** alias token. If the term is a subquery, then pSubquery is the
3359** SELECT statement that the subquery encodes. The pTable and
3360** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3361** parameters are the content of the ON and USING clauses.
3362**
3363** Return a new SrcList which encodes is the FROM with the new
3364** term added.
3365*/
3366SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003367 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003368 SrcList *p, /* The left part of the FROM clause already seen */
3369 Token *pTable, /* Name of the table to add to the FROM clause */
3370 Token *pDatabase, /* Name of the database containing pTable */
3371 Token *pAlias, /* The right-hand side of the AS subexpression */
3372 Select *pSubquery, /* A subquery used in place of a table name */
3373 Expr *pOn, /* The ON clause of a join */
3374 IdList *pUsing /* The USING clause of a join */
3375){
3376 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003377 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003378 if( !p && (pOn || pUsing) ){
3379 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3380 (pOn ? "ON" : "USING")
3381 );
3382 goto append_from_error;
3383 }
drh17435752007-08-16 04:30:38 +00003384 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003385 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003386 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003387 }
3388 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003389 assert( pAlias!=0 );
3390 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003391 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003392 }
3393 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003394 pItem->pOn = pOn;
3395 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003396 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003397
3398 append_from_error:
3399 assert( p==0 );
3400 sqlite3ExprDelete(db, pOn);
3401 sqlite3IdListDelete(db, pUsing);
3402 sqlite3SelectDelete(db, pSubquery);
3403 return 0;
drh61dfc312006-12-16 16:25:15 +00003404}
3405
3406/*
danielk1977b1c685b2008-10-06 16:18:39 +00003407** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3408** element of the source-list passed as the second argument.
3409*/
3410void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003411 assert( pIndexedBy!=0 );
3412 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003413 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3414 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3415 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3416 /* A "NOT INDEXED" clause was supplied. See parse.y
3417 ** construct "indexed_opt" for details. */
3418 pItem->notIndexed = 1;
3419 }else{
3420 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3421 }
3422 }
3423}
3424
3425/*
drh61dfc312006-12-16 16:25:15 +00003426** When building up a FROM clause in the parser, the join operator
3427** is initially attached to the left operand. But the code generator
3428** expects the join operator to be on the right operand. This routine
3429** Shifts all join operators from left to right for an entire FROM
3430** clause.
3431**
3432** Example: Suppose the join is like this:
3433**
3434** A natural cross join B
3435**
3436** The operator is "natural cross join". The A and B operands are stored
3437** in p->a[0] and p->a[1], respectively. The parser initially stores the
3438** operator with A. This routine shifts that operator over to B.
3439*/
3440void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003441 if( p ){
drh61dfc312006-12-16 16:25:15 +00003442 int i;
drhd017ab92011-08-23 00:01:58 +00003443 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003444 for(i=p->nSrc-1; i>0; i--){
3445 p->a[i].jointype = p->a[i-1].jointype;
3446 }
3447 p->a[0].jointype = 0;
3448 }
3449}
3450
3451/*
drhc4a3c772001-04-04 11:48:57 +00003452** Begin a transaction
3453*/
drh684917c2004-10-05 02:41:42 +00003454void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003455 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003456 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003457 int i;
drh5e00f6c2001-09-13 13:46:56 +00003458
drhd3001712009-05-12 17:46:53 +00003459 assert( pParse!=0 );
3460 db = pParse->db;
3461 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003462/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003463 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3464 return;
3465 }
danielk19771d850a72004-05-31 08:26:49 +00003466 v = sqlite3GetVdbe(pParse);
3467 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003468 if( type!=TK_DEFERRED ){
3469 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003470 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003471 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003472 }
3473 }
drh66a51672008-01-03 00:01:23 +00003474 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003475}
3476
3477/*
3478** Commit a transaction
3479*/
danielk19774adee202004-05-08 08:23:19 +00003480void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003481 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003482
drhd3001712009-05-12 17:46:53 +00003483 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003484 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003485 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3486 return;
3487 }
danielk19771d850a72004-05-31 08:26:49 +00003488 v = sqlite3GetVdbe(pParse);
3489 if( v ){
drh66a51672008-01-03 00:01:23 +00003490 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003491 }
drhc4a3c772001-04-04 11:48:57 +00003492}
3493
3494/*
3495** Rollback a transaction
3496*/
danielk19774adee202004-05-08 08:23:19 +00003497void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003498 Vdbe *v;
3499
drhd3001712009-05-12 17:46:53 +00003500 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003501 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003502 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3503 return;
3504 }
danielk19774adee202004-05-08 08:23:19 +00003505 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003506 if( v ){
drh66a51672008-01-03 00:01:23 +00003507 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003508 }
drhc4a3c772001-04-04 11:48:57 +00003509}
drhf57b14a2001-09-14 18:54:08 +00003510
3511/*
danielk1977fd7f0452008-12-17 17:30:26 +00003512** This function is called by the parser when it parses a command to create,
3513** release or rollback an SQL savepoint.
3514*/
3515void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003516 char *zName = sqlite3NameFromToken(pParse->db, pName);
3517 if( zName ){
3518 Vdbe *v = sqlite3GetVdbe(pParse);
3519#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003520 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003521 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3522#endif
3523 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3524 sqlite3DbFree(pParse->db, zName);
3525 return;
3526 }
3527 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003528 }
3529}
3530
3531/*
drhdc3ff9c2004-08-18 02:10:15 +00003532** Make sure the TEMP database is open and available for use. Return
3533** the number of errors. Leave any error messages in the pParse structure.
3534*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003535int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003536 sqlite3 *db = pParse->db;
3537 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003538 int rc;
drh10a76c92010-01-26 01:25:26 +00003539 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003540 static const int flags =
3541 SQLITE_OPEN_READWRITE |
3542 SQLITE_OPEN_CREATE |
3543 SQLITE_OPEN_EXCLUSIVE |
3544 SQLITE_OPEN_DELETEONCLOSE |
3545 SQLITE_OPEN_TEMP_DB;
3546
dan3a6d8ae2011-04-23 15:54:54 +00003547 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003548 if( rc!=SQLITE_OK ){
3549 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3550 "file for storing temporary tables");
3551 pParse->rc = rc;
3552 return 1;
3553 }
drh10a76c92010-01-26 01:25:26 +00003554 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003555 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003556 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3557 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003558 return 1;
drh10a76c92010-01-26 01:25:26 +00003559 }
drhdc3ff9c2004-08-18 02:10:15 +00003560 }
3561 return 0;
3562}
3563
3564/*
drh80242052004-06-09 00:48:12 +00003565** Generate VDBE code that will verify the schema cookie and start
3566** a read-transaction for all named database files.
3567**
3568** It is important that all schema cookies be verified and all
3569** read transactions be started before anything else happens in
3570** the VDBE program. But this routine can be called after much other
3571** code has been generated. So here is what we do:
3572**
drhc275b4e2004-07-19 17:25:24 +00003573** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003574** will jump to a subroutine at the end of the program. Then we
3575** record every database that needs its schema verified in the
3576** pParse->cookieMask field. Later, after all other code has been
3577** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003578** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003579** will be made to point to that subroutine. The generation of the
3580** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003581**
3582** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3583** schema on any databases. This can be used to position the OP_Goto
3584** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003585*/
danielk19774adee202004-05-08 08:23:19 +00003586void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003587 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003588
danf78baaf2012-12-06 19:37:22 +00003589#ifndef SQLITE_OMIT_TRIGGER
3590 if( pToplevel!=pParse ){
3591 /* This branch is taken if a trigger is currently being coded. In this
3592 ** case, set cookieGoto to a non-zero value to show that this function
3593 ** has been called. This is used by the sqlite3ExprCodeConstants()
3594 ** function. */
3595 pParse->cookieGoto = -1;
3596 }
3597#endif
dan65a7cd12009-09-01 12:16:01 +00003598 if( pToplevel->cookieGoto==0 ){
3599 Vdbe *v = sqlite3GetVdbe(pToplevel);
3600 if( v==0 ) return; /* This only happens if there was a prior error */
3601 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003602 }
drhc275b4e2004-07-19 17:25:24 +00003603 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003604 sqlite3 *db = pToplevel->db;
drh64123582011-04-02 20:01:02 +00003605 yDbMask mask;
dan65a7cd12009-09-01 12:16:01 +00003606
drhc275b4e2004-07-19 17:25:24 +00003607 assert( iDb<db->nDb );
3608 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003609 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drh21206082011-04-04 18:22:02 +00003610 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh64123582011-04-02 20:01:02 +00003611 mask = ((yDbMask)1)<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003612 if( (pToplevel->cookieMask & mask)==0 ){
3613 pToplevel->cookieMask |= mask;
3614 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003615 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003616 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003617 }
drhc275b4e2004-07-19 17:25:24 +00003618 }
drh001bbcb2003-03-19 03:14:00 +00003619 }
drh001bbcb2003-03-19 03:14:00 +00003620}
3621
3622/*
dan57966752011-04-09 17:32:58 +00003623** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3624** attached database. Otherwise, invoke it for the database named zDb only.
3625*/
3626void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3627 sqlite3 *db = pParse->db;
3628 int i;
3629 for(i=0; i<db->nDb; i++){
3630 Db *pDb = &db->aDb[i];
3631 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3632 sqlite3CodeVerifySchema(pParse, i);
3633 }
3634 }
3635}
3636
3637/*
drh1c928532002-01-31 15:54:21 +00003638** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003639** might change the database.
3640**
3641** This routine starts a new transaction if we are not already within
3642** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003643** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003644** be set for operations that might fail (due to a constraint) part of
3645** the way through and which will need to undo some writes without having to
3646** rollback the whole transaction. For operations where all constraints
3647** can be checked before any changes are made to the database, it is never
3648** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003649*/
drh7f0f12e2004-05-21 13:39:50 +00003650void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003651 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003652 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003653 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003654 pToplevel->isMultiWrite |= setStatement;
3655}
3656
drhff738bc2009-09-24 00:09:58 +00003657/*
3658** Indicate that the statement currently under construction might write
3659** more than one entry (example: deleting one row then inserting another,
3660** inserting multiple rows in a table, or inserting a row and index entries.)
3661** If an abort occurs after some of these writes have completed, then it will
3662** be necessary to undo the completed writes.
3663*/
3664void sqlite3MultiWrite(Parse *pParse){
3665 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3666 pToplevel->isMultiWrite = 1;
3667}
3668
dane0af83a2009-09-08 19:15:01 +00003669/*
drhff738bc2009-09-24 00:09:58 +00003670** The code generator calls this routine if is discovers that it is
3671** possible to abort a statement prior to completion. In order to
3672** perform this abort without corrupting the database, we need to make
3673** sure that the statement is protected by a statement transaction.
3674**
3675** Technically, we only need to set the mayAbort flag if the
3676** isMultiWrite flag was previously set. There is a time dependency
3677** such that the abort must occur after the multiwrite. This makes
3678** some statements involving the REPLACE conflict resolution algorithm
3679** go a little faster. But taking advantage of this time dependency
3680** makes it more difficult to prove that the code is correct (in
3681** particular, it prevents us from writing an effective
3682** implementation of sqlite3AssertMayAbort()) and so we have chosen
3683** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003684*/
3685void sqlite3MayAbort(Parse *pParse){
3686 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3687 pToplevel->mayAbort = 1;
3688}
3689
3690/*
3691** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3692** error. The onError parameter determines which (if any) of the statement
3693** and/or current transaction is rolled back.
3694*/
drhd91c1a12013-02-09 13:58:25 +00003695void sqlite3HaltConstraint(
3696 Parse *pParse, /* Parsing context */
3697 int errCode, /* extended error code */
3698 int onError, /* Constraint type */
3699 char *p4, /* Error message */
3700 int p4type /* P4_STATIC or P4_TRANSIENT */
3701){
dane0af83a2009-09-08 19:15:01 +00003702 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003703 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003704 if( onError==OE_Abort ){
3705 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003706 }
drhd91c1a12013-02-09 13:58:25 +00003707 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003708}
3709
drh4343fea2004-11-05 23:46:15 +00003710/*
3711** Check to see if pIndex uses the collating sequence pColl. Return
3712** true if it does and false if it does not.
3713*/
3714#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003715static int collationMatch(const char *zColl, Index *pIndex){
3716 int i;
drh04491712009-05-13 17:21:13 +00003717 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003718 for(i=0; i<pIndex->nColumn; i++){
3719 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003720 assert( z!=0 );
3721 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003722 return 1;
3723 }
drh4343fea2004-11-05 23:46:15 +00003724 }
3725 return 0;
3726}
3727#endif
3728
3729/*
3730** Recompute all indices of pTab that use the collating sequence pColl.
3731** If pColl==0 then recompute all indices of pTab.
3732*/
3733#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003734static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003735 Index *pIndex; /* An index associated with pTab */
3736
3737 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003738 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003739 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3740 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003741 sqlite3RefillIndex(pParse, pIndex, -1);
3742 }
3743 }
3744}
3745#endif
3746
3747/*
3748** Recompute all indices of all tables in all databases where the
3749** indices use the collating sequence pColl. If pColl==0 then recompute
3750** all indices everywhere.
3751*/
3752#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003753static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003754 Db *pDb; /* A single database */
3755 int iDb; /* The database index number */
3756 sqlite3 *db = pParse->db; /* The database connection */
3757 HashElem *k; /* For looping over tables in pDb */
3758 Table *pTab; /* A table in the database */
3759
drh21206082011-04-04 18:22:02 +00003760 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00003761 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003762 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003763 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003764 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003765 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003766 }
3767 }
3768}
3769#endif
3770
3771/*
drheee46cf2004-11-06 00:02:48 +00003772** Generate code for the REINDEX command.
3773**
3774** REINDEX -- 1
3775** REINDEX <collation> -- 2
3776** REINDEX ?<database>.?<tablename> -- 3
3777** REINDEX ?<database>.?<indexname> -- 4
3778**
3779** Form 1 causes all indices in all attached databases to be rebuilt.
3780** Form 2 rebuilds all indices in all databases that use the named
3781** collating function. Forms 3 and 4 rebuild the named index or all
3782** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003783*/
3784#ifndef SQLITE_OMIT_REINDEX
3785void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3786 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3787 char *z; /* Name of a table or index */
3788 const char *zDb; /* Name of the database */
3789 Table *pTab; /* A table in the database */
3790 Index *pIndex; /* An index associated with pTab */
3791 int iDb; /* The database index number */
3792 sqlite3 *db = pParse->db; /* The database connection */
3793 Token *pObjName; /* Name of the table or index to be reindexed */
3794
danielk197733a5edc2005-01-27 00:22:02 +00003795 /* Read the database schema. If an error occurs, leave an error message
3796 ** and code in pParse and return NULL. */
3797 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003798 return;
danielk197733a5edc2005-01-27 00:22:02 +00003799 }
3800
drh8af73d42009-05-13 22:58:28 +00003801 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003802 reindexDatabases(pParse, 0);
3803 return;
drhd3001712009-05-12 17:46:53 +00003804 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003805 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003806 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003807 zColl = sqlite3NameFromToken(pParse->db, pName1);
3808 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003809 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003810 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003811 reindexDatabases(pParse, zColl);
3812 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003813 return;
3814 }
drh633e6d52008-07-28 19:34:53 +00003815 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003816 }
3817 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3818 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003819 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003820 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003821 zDb = db->aDb[iDb].zName;
3822 pTab = sqlite3FindTable(db, z, zDb);
3823 if( pTab ){
3824 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003825 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003826 return;
3827 }
3828 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003829 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003830 if( pIndex ){
3831 sqlite3BeginWriteOperation(pParse, 0, iDb);
3832 sqlite3RefillIndex(pParse, pIndex, -1);
3833 return;
3834 }
3835 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3836}
3837#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003838
3839/*
3840** Return a dynamicly allocated KeyInfo structure that can be used
3841** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3842**
3843** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003844** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003845** pointer. If an error occurs (out of memory or missing collation
3846** sequence), NULL is returned and the state of pParse updated to reflect
3847** the error.
3848*/
3849KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3850 int i;
3851 int nCol = pIdx->nColumn;
3852 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003853 sqlite3 *db = pParse->db;
3854 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003855
3856 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003857 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003858 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3859 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3860 for(i=0; i<nCol; i++){
3861 char *zColl = pIdx->azColl[i];
3862 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003863 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003864 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3865 }
drh1bd10f82008-12-10 21:19:56 +00003866 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003867 }
3868
3869 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003870 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003871 pKey = 0;
3872 }
3873 return pKey;
3874}