blob: 38bdad859f0544b977672a50638b7ad82b4a7709 [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
drh1fe05372013-07-31 18:12:26 +0000385 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000386 sqlite3DbFree(db, p->zColAff);
387 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000388}
389
390/*
drhc96d8532005-05-03 12:30:33 +0000391** For the index called zIdxName which is found in the database iDb,
392** unlike that index from its Table then remove the index from
393** the index hash table and free all memory structures associated
394** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000395*/
drh9bb575f2004-09-06 17:24:11 +0000396void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000397 Index *pIndex;
398 int len;
drh21206082011-04-04 18:22:02 +0000399 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000400
drh21206082011-04-04 18:22:02 +0000401 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
402 pHash = &db->aDb[iDb].pSchema->idxHash;
drhdee0e402009-05-03 20:23:53 +0000403 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000404 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh22645842011-03-24 01:34:03 +0000405 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000406 if( pIndex->pTable->pIndex==pIndex ){
407 pIndex->pTable->pIndex = pIndex->pNext;
408 }else{
409 Index *p;
drh04491712009-05-13 17:21:13 +0000410 /* Justification of ALWAYS(); The index must be on the list of
411 ** indices. */
412 p = pIndex->pTable->pIndex;
413 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
414 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000415 p->pNext = pIndex->pNext;
416 }
drh5e00f6c2001-09-13 13:46:56 +0000417 }
dan1feeaed2010-07-23 15:41:47 +0000418 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000419 }
drh956bc922004-07-24 17:38:29 +0000420 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000421}
422
423/*
drh81028a42012-05-15 18:28:27 +0000424** Look through the list of open database files in db->aDb[] and if
425** any have been closed, remove them from the list. Reallocate the
426** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000427**
drh81028a42012-05-15 18:28:27 +0000428** Entry 0 (the "main" database) and entry 1 (the "temp" database)
429** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000430*/
drh81028a42012-05-15 18:28:27 +0000431void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000432 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000433 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000434 struct Db *pDb = &db->aDb[i];
435 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000436 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000437 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000438 continue;
439 }
440 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000441 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000442 }
drh8bf8dc92003-05-17 17:35:10 +0000443 j++;
drh1c2d8412003-03-31 00:30:47 +0000444 }
445 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
446 db->nDb = j;
447 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
448 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000449 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000450 db->aDb = db->aDbStatic;
451 }
drhe0bc4042002-06-25 01:09:11 +0000452}
453
454/*
drh81028a42012-05-15 18:28:27 +0000455** Reset the schema for the database at index iDb. Also reset the
456** TEMP schema.
457*/
458void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000459 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000460 assert( iDb<db->nDb );
461
462 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000463 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000464 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
465 assert( pDb->pSchema!=0 );
466 sqlite3SchemaClear(pDb->pSchema);
467
468 /* If any database other than TEMP is reset, then also reset TEMP
469 ** since TEMP might be holding triggers that reference tables in the
470 ** other database.
471 */
472 if( iDb!=1 ){
473 pDb = &db->aDb[1];
474 assert( pDb->pSchema!=0 );
475 sqlite3SchemaClear(pDb->pSchema);
476 }
477 return;
478}
479
480/*
481** Erase all schema information from all attached databases (including
482** "main" and "temp") for a single database connection.
483*/
484void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
485 int i;
486 sqlite3BtreeEnterAll(db);
487 for(i=0; i<db->nDb; i++){
488 Db *pDb = &db->aDb[i];
489 if( pDb->pSchema ){
490 sqlite3SchemaClear(pDb->pSchema);
491 }
492 }
493 db->flags &= ~SQLITE_InternChanges;
494 sqlite3VtabUnlockList(db);
495 sqlite3BtreeLeaveAll(db);
496 sqlite3CollapseDatabaseArray(db);
497}
498
499/*
drhe0bc4042002-06-25 01:09:11 +0000500** This routine is called when a commit occurs.
501*/
drh9bb575f2004-09-06 17:24:11 +0000502void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000503 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000504}
505
506/*
dand46def72010-07-24 11:28:28 +0000507** Delete memory allocated for the column names of a table or view (the
508** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000509*/
dand46def72010-07-24 11:28:28 +0000510static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000511 int i;
512 Column *pCol;
513 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000514 if( (pCol = pTable->aCol)!=0 ){
515 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000516 sqlite3DbFree(db, pCol->zName);
517 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000518 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000519 sqlite3DbFree(db, pCol->zType);
520 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000521 }
drh633e6d52008-07-28 19:34:53 +0000522 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000523 }
drh956bc922004-07-24 17:38:29 +0000524}
525
526/*
drh75897232000-05-29 14:26:00 +0000527** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000528** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000529**
530** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000531** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000532** memory structures of the indices and foreign keys associated with
533** the table.
drh29ddd3a2012-05-15 12:49:32 +0000534**
535** The db parameter is optional. It is needed if the Table object
536** contains lookaside memory. (Table objects in the schema do not use
537** lookaside memory, but some ephemeral Table objects do.) Or the
538** db parameter can be used with db->pnBytesFreed to measure the memory
539** used by the Table object.
drh75897232000-05-29 14:26:00 +0000540*/
dan1feeaed2010-07-23 15:41:47 +0000541void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000542 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000543 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000544
dand46def72010-07-24 11:28:28 +0000545 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000546
drhed8a3bb2005-06-06 21:19:56 +0000547 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000548 if( !pTable ) return;
549 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000550
drh29ddd3a2012-05-15 12:49:32 +0000551 /* Record the number of outstanding lookaside allocations in schema Tables
552 ** prior to doing any free() operations. Since schema Tables do not use
553 ** lookaside, this number should not change. */
554 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
555 db->lookaside.nOut : 0 );
556
dand46def72010-07-24 11:28:28 +0000557 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000558 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
559 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000560 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000561 if( !db || db->pnBytesFreed==0 ){
562 char *zName = pIndex->zName;
563 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhf2f105d2012-08-20 15:53:54 +0000564 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
dand46def72010-07-24 11:28:28 +0000565 );
drh21206082011-04-04 18:22:02 +0000566 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000567 assert( pOld==pIndex || pOld==0 );
568 }
569 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000570 }
571
dan1da40a32009-09-19 17:00:31 +0000572 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000573 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000574
575 /* Delete the Table structure itself.
576 */
dand46def72010-07-24 11:28:28 +0000577 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000578 sqlite3DbFree(db, pTable->zName);
579 sqlite3DbFree(db, pTable->zColAff);
580 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000581#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000582 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000583#endif
drh078e4082010-07-28 19:17:51 +0000584#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000585 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000586#endif
drh633e6d52008-07-28 19:34:53 +0000587 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000588
589 /* Verify that no lookaside memory was used by schema tables */
590 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000591}
592
593/*
drh5edc3122001-09-13 21:53:09 +0000594** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000595** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000596*/
drh9bb575f2004-09-06 17:24:11 +0000597void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000598 Table *p;
drh956bc922004-07-24 17:38:29 +0000599 Db *pDb;
600
drhd229ca92002-01-09 13:30:41 +0000601 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000602 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000603 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000604 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000605 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000606 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000607 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000608 sqlite3Strlen30(zTabName),0);
dan1feeaed2010-07-23 15:41:47 +0000609 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000610 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000611}
612
613/*
drha99db3b2004-06-19 14:49:12 +0000614** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000615** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000616** is obtained from sqliteMalloc() and must be freed by the calling
617** function.
drh75897232000-05-29 14:26:00 +0000618**
drh24fb6272009-05-01 21:13:36 +0000619** Any quotation marks (ex: "name", 'name', [name], or `name`) that
620** surround the body of the token are removed.
621**
drhc96d8532005-05-03 12:30:33 +0000622** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000623** are not \000 terminated and are not persistent. The returned string
624** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000625*/
drh17435752007-08-16 04:30:38 +0000626char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000627 char *zName;
628 if( pName ){
drh17435752007-08-16 04:30:38 +0000629 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000630 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000631 }else{
632 zName = 0;
633 }
drh75897232000-05-29 14:26:00 +0000634 return zName;
635}
636
637/*
danielk1977cbb18d22004-05-28 11:37:27 +0000638** Open the sqlite_master table stored in database number iDb for
639** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000640*/
danielk1977c00da102006-01-07 13:21:04 +0000641void sqlite3OpenMasterTable(Parse *p, int iDb){
642 Vdbe *v = sqlite3GetVdbe(p);
643 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977207872a2008-01-03 07:54:23 +0000644 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
danielk1977d336e222009-02-20 10:58:41 +0000645 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
danielk19776ab3a2e2009-02-19 14:39:25 +0000646 if( p->nTab==0 ){
647 p->nTab = 1;
648 }
drhe0bc4042002-06-25 01:09:11 +0000649}
650
651/*
danielk197704103022009-02-03 16:51:24 +0000652** Parameter zName points to a nul-terminated buffer containing the name
653** of a database ("main", "temp" or the name of an attached db). This
654** function returns the index of the named database in db->aDb[], or
655** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000656*/
danielk197704103022009-02-03 16:51:24 +0000657int sqlite3FindDbName(sqlite3 *db, const char *zName){
658 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000659 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000660 Db *pDb;
661 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000662 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000663 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000664 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000665 break;
drh73c42a12004-11-20 18:13:10 +0000666 }
danielk1977cbb18d22004-05-28 11:37:27 +0000667 }
668 }
danielk1977576ec6b2005-01-21 11:55:25 +0000669 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000670}
671
danielk197704103022009-02-03 16:51:24 +0000672/*
673** The token *pName contains the name of a database (either "main" or
674** "temp" or the name of an attached db). This routine returns the
675** index of the named database in db->aDb[], or -1 if the named db
676** does not exist.
677*/
678int sqlite3FindDb(sqlite3 *db, Token *pName){
679 int i; /* Database number */
680 char *zName; /* Name we are searching for */
681 zName = sqlite3NameFromToken(db, pName);
682 i = sqlite3FindDbName(db, zName);
683 sqlite3DbFree(db, zName);
684 return i;
685}
686
drh0e3d7472004-06-19 17:33:07 +0000687/* The table or view or trigger name is passed to this routine via tokens
688** pName1 and pName2. If the table name was fully qualified, for example:
689**
690** CREATE TABLE xxx.yyy (...);
691**
692** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
693** the table name is not fully qualified, i.e.:
694**
695** CREATE TABLE yyy(...);
696**
697** Then pName1 is set to "yyy" and pName2 is "".
698**
699** This routine sets the *ppUnqual pointer to point at the token (pName1 or
700** pName2) that stores the unqualified table name. The index of the
701** database "xxx" is returned.
702*/
danielk1977ef2cb632004-05-29 02:37:19 +0000703int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000704 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000705 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000706 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
707 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000708){
drh0e3d7472004-06-19 17:33:07 +0000709 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000710 sqlite3 *db = pParse->db;
711
drhc4a64fa2009-05-11 20:53:28 +0000712 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000713 if( db->init.busy ) {
714 sqlite3ErrorMsg(pParse, "corrupt database");
715 pParse->nErr++;
716 return -1;
717 }
danielk1977cbb18d22004-05-28 11:37:27 +0000718 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000719 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000720 if( iDb<0 ){
721 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
722 pParse->nErr++;
723 return -1;
724 }
725 }else{
726 assert( db->init.iDb==0 || db->init.busy );
727 iDb = db->init.iDb;
728 *pUnqual = pName1;
729 }
730 return iDb;
731}
732
733/*
danielk1977d8123362004-06-12 09:25:12 +0000734** This routine is used to check if the UTF-8 string zName is a legal
735** unqualified name for a new schema object (table, index, view or
736** trigger). All names are legal except those that begin with the string
737** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
738** is reserved for internal use.
739*/
740int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000741 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000742 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000743 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000744 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
745 return SQLITE_ERROR;
746 }
747 return SQLITE_OK;
748}
749
750/*
drh75897232000-05-29 14:26:00 +0000751** Begin constructing a new table representation in memory. This is
752** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000753** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000754** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000755** flag is true if the table should be stored in the auxiliary database
756** file instead of in the main database file. This is normally the case
757** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000758** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000759**
drhf57b3392001-10-08 13:22:32 +0000760** The new table record is initialized and put in pParse->pNewTable.
761** As more of the CREATE TABLE statement is parsed, additional action
762** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000763** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000764** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000765*/
danielk19774adee202004-05-08 08:23:19 +0000766void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000767 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000768 Token *pName1, /* First part of the name of the table or view */
769 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000770 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000771 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000772 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000773 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000774){
drh75897232000-05-29 14:26:00 +0000775 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000776 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000777 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000778 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000779 int iDb; /* Database number to create the table in */
780 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000781
danielk1977cbb18d22004-05-28 11:37:27 +0000782 /* The table or view name to create is passed to this routine via tokens
783 ** pName1 and pName2. If the table name was fully qualified, for example:
784 **
785 ** CREATE TABLE xxx.yyy (...);
786 **
787 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
788 ** the table name is not fully qualified, i.e.:
789 **
790 ** CREATE TABLE yyy(...);
791 **
792 ** Then pName1 is set to "yyy" and pName2 is "".
793 **
794 ** The call below sets the pName pointer to point at the token (pName1 or
795 ** pName2) that stores the unqualified table name. The variable iDb is
796 ** set to the index of the database that the table or view is to be
797 ** created in.
798 */
danielk1977ef2cb632004-05-29 02:37:19 +0000799 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000800 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000801 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
802 /* If creating a temp table, the name may not be qualified. Unless
803 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000804 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000805 return;
806 }
danielk197753c0f742005-03-29 03:10:59 +0000807 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000808
809 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000810 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000811 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000812 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000813 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000814 }
drh1d85d932004-02-14 23:05:52 +0000815 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000816#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000817 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000818 {
819 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000820 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000821 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000822 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000823 }
drhe5f9c642003-01-13 23:27:31 +0000824 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000825 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000826 code = SQLITE_CREATE_TEMP_VIEW;
827 }else{
828 code = SQLITE_CREATE_VIEW;
829 }
830 }else{
danielk197753c0f742005-03-29 03:10:59 +0000831 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000832 code = SQLITE_CREATE_TEMP_TABLE;
833 }else{
834 code = SQLITE_CREATE_TABLE;
835 }
836 }
danielk1977f1a381e2006-06-16 08:01:02 +0000837 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000838 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000839 }
840 }
841#endif
drhf57b3392001-10-08 13:22:32 +0000842
drhf57b3392001-10-08 13:22:32 +0000843 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000844 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000845 ** it does. The exception is if the statement being parsed was passed
846 ** to an sqlite3_declare_vtab() call. In that case only the column names
847 ** and types will be used, so there is no need to test for namespace
848 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000849 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000850 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000851 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000852 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
853 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000854 }
dana16d1062010-09-28 17:37:28 +0000855 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000856 if( pTable ){
857 if( !noErr ){
858 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000859 }else{
860 assert( !db->init.busy );
861 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000862 }
863 goto begin_table_error;
864 }
drh8a8a0d12010-09-28 20:26:44 +0000865 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000866 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
867 goto begin_table_error;
868 }
drh75897232000-05-29 14:26:00 +0000869 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000870
danielk197726783a52007-08-29 14:06:22 +0000871 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000872 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000873 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000874 pParse->rc = SQLITE_NOMEM;
875 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000876 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000877 }
drh75897232000-05-29 14:26:00 +0000878 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000879 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000880 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000881 pTable->nRef = 1;
drh186ad8c2013-10-08 18:40:37 +0000882 pTable->nRowEst = 1048576;
drhc4a64fa2009-05-11 20:53:28 +0000883 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000884 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000885
drh4794f732004-11-05 17:17:50 +0000886 /* If this is the magic sqlite_sequence table used by autoincrement,
887 ** then record a pointer to this table in the main database structure
888 ** so that INSERT can find the table easily.
889 */
890#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000891 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000892 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000893 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000894 }
895#endif
896
drh17f71932002-02-21 12:01:27 +0000897 /* Begin generating the code that will insert the table record into
898 ** the SQLITE_MASTER table. Note in particular that we must go ahead
899 ** and allocate the record number for the table entry now. Before any
900 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
901 ** indices to be created and the table record must come before the
902 ** indices. Hence, the record number for the table must be allocated
903 ** now.
904 */
danielk19774adee202004-05-08 08:23:19 +0000905 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000906 int j1;
drhe321c292006-01-12 01:56:43 +0000907 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000908 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000909 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000910
danielk197720b1eaf2006-07-26 16:22:14 +0000911#ifndef SQLITE_OMIT_VIRTUALTABLE
912 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000913 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000914 }
915#endif
916
danielk197736963fd2005-02-19 08:18:05 +0000917 /* If the file format and encoding in the database have not been set,
918 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000919 */
drhb7654112008-01-12 12:48:07 +0000920 reg1 = pParse->regRowid = ++pParse->nMem;
921 reg2 = pParse->regRoot = ++pParse->nMem;
922 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000923 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000924 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000925 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000926 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000927 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000928 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000929 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000930 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000931 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000932 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000933
drh4794f732004-11-05 17:17:50 +0000934 /* This just creates a place-holder record in the sqlite_master table.
935 ** The record created does not contain anything yet. It will be replaced
936 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000937 **
drh0fa991b2009-03-21 16:19:26 +0000938 ** The rowid for the new entry is left in register pParse->regRowid.
939 ** The root page number of the new table is left in reg pParse->regRoot.
940 ** The rowid and root page number values are needed by the code that
941 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000942 */
danielk1977f1a381e2006-06-16 08:01:02 +0000943#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
944 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000945 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000946 }else
947#endif
948 {
drhb7654112008-01-12 12:48:07 +0000949 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000950 }
danielk1977c00da102006-01-07 13:21:04 +0000951 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000952 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
953 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
954 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
955 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000956 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000957 }
drh23bf66d2004-12-14 03:34:34 +0000958
959 /* Normal (non-error) return. */
960 return;
961
962 /* If an error occurs, we jump here */
963begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000964 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000965 return;
drh75897232000-05-29 14:26:00 +0000966}
967
968/*
danielk1977c60e9b82005-01-31 12:42:29 +0000969** This macro is used to compare two strings in a case-insensitive manner.
970** It is slightly faster than calling sqlite3StrICmp() directly, but
971** produces larger code.
972**
973** WARNING: This macro is not compatible with the strcmp() family. It
974** returns true if the two strings are equal, otherwise false.
975*/
976#define STRICMP(x, y) (\
977sqlite3UpperToLower[*(unsigned char *)(x)]== \
978sqlite3UpperToLower[*(unsigned char *)(y)] \
979&& sqlite3StrICmp((x)+1,(y)+1)==0 )
980
981/*
drh75897232000-05-29 14:26:00 +0000982** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000983**
984** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000985** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000986** first to get things going. Then this routine is called for each
987** column.
drh75897232000-05-29 14:26:00 +0000988*/
danielk19774adee202004-05-08 08:23:19 +0000989void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000990 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000991 int i;
drha99db3b2004-06-19 14:49:12 +0000992 char *z;
drhc9b84a12002-06-20 11:36:48 +0000993 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000994 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000995 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000996#if SQLITE_MAX_COLUMN
997 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000998 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
999 return;
1000 }
drhbb4957f2008-03-20 14:03:29 +00001001#endif
danielk1977ae74e032008-12-23 11:11:51 +00001002 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001003 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001004 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001005 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001006 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001007 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001008 return;
1009 }
1010 }
drh75897232000-05-29 14:26:00 +00001011 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001012 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001013 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001014 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001015 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001016 return;
1017 }
drh6d4abfb2001-10-22 02:58:08 +00001018 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001019 }
drhc9b84a12002-06-20 11:36:48 +00001020 pCol = &p->aCol[p->nCol];
1021 memset(pCol, 0, sizeof(p->aCol[0]));
1022 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001023
1024 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001025 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1026 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001027 */
danielk19774f057f92004-06-08 00:02:33 +00001028 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001029 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001030 p->nCol++;
drh75897232000-05-29 14:26:00 +00001031}
1032
1033/*
drh382c0242001-10-06 16:33:02 +00001034** This routine is called by the parser while in the middle of
1035** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1036** been seen on a column. This routine sets the notNull flag on
1037** the column currently under construction.
1038*/
danielk19774adee202004-05-08 08:23:19 +00001039void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001040 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001041 p = pParse->pNewTable;
1042 if( p==0 || NEVER(p->nCol<1) ) return;
1043 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001044}
1045
1046/*
danielk197752a83fb2005-01-31 12:56:44 +00001047** Scan the column type name zType (length nType) and return the
1048** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001049**
1050** This routine does a case-independent search of zType for the
1051** substrings in the following table. If one of the substrings is
1052** found, the corresponding affinity is returned. If zType contains
1053** more than one of the substrings, entries toward the top of
1054** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001055** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001056**
1057** Substring | Affinity
1058** --------------------------------
1059** 'INT' | SQLITE_AFF_INTEGER
1060** 'CHAR' | SQLITE_AFF_TEXT
1061** 'CLOB' | SQLITE_AFF_TEXT
1062** 'TEXT' | SQLITE_AFF_TEXT
1063** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001064** 'REAL' | SQLITE_AFF_REAL
1065** 'FLOA' | SQLITE_AFF_REAL
1066** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001067**
1068** If none of the substrings in the above table are found,
1069** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001070*/
drhfdaac672013-10-04 15:30:21 +00001071char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001072 u32 h = 0;
1073 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001074 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001075
drhfdaac672013-10-04 15:30:21 +00001076 if( zIn==0 ) return aff;
1077 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001078 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001079 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001080 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001081 aff = SQLITE_AFF_TEXT;
1082 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001083 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1084 aff = SQLITE_AFF_TEXT;
1085 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1086 aff = SQLITE_AFF_TEXT;
1087 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001088 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001089 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001090 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001091#ifndef SQLITE_OMIT_FLOATING_POINT
1092 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1093 && aff==SQLITE_AFF_NUMERIC ){
1094 aff = SQLITE_AFF_REAL;
1095 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1096 && aff==SQLITE_AFF_NUMERIC ){
1097 aff = SQLITE_AFF_REAL;
1098 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1099 && aff==SQLITE_AFF_NUMERIC ){
1100 aff = SQLITE_AFF_REAL;
1101#endif
danielk1977201f7162005-02-01 02:13:29 +00001102 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001103 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001104 break;
danielk197752a83fb2005-01-31 12:56:44 +00001105 }
1106 }
drhd3037a42013-10-04 18:29:25 +00001107
1108 /* If pszEst is not NULL, store an estimate of the field size. The
1109 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001110 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001111 *pszEst = 1; /* default size is approx 4 bytes */
1112 if( aff<=SQLITE_AFF_NONE ){
1113 if( zChar ){
1114 while( zChar[0] ){
1115 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001116 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001117 sqlite3GetInt32(zChar, &v);
1118 v = v/4 + 1;
1119 if( v>255 ) v = 255;
1120 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1121 break;
1122 }
1123 zChar++;
drhfdaac672013-10-04 15:30:21 +00001124 }
drhd3037a42013-10-04 18:29:25 +00001125 }else{
1126 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001127 }
drhfdaac672013-10-04 15:30:21 +00001128 }
1129 }
danielk1977b3dff962005-02-01 01:21:55 +00001130 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001131}
1132
1133/*
drh382c0242001-10-06 16:33:02 +00001134** This routine is called by the parser while in the middle of
1135** parsing a CREATE TABLE statement. The pFirst token is the first
1136** token in the sequence of tokens that describe the type of the
1137** column currently under construction. pLast is the last token
1138** in the sequence. Use this information to construct a string
1139** that contains the typename of the column and store that string
1140** in zType.
1141*/
drh487e2622005-06-25 18:42:14 +00001142void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001143 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001144 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001145
drhc4a64fa2009-05-11 20:53:28 +00001146 p = pParse->pNewTable;
1147 if( p==0 || NEVER(p->nCol<1) ) return;
1148 pCol = &p->aCol[p->nCol-1];
1149 assert( pCol->zType==0 );
1150 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001151 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001152}
1153
1154/*
danielk19777977a172004-11-09 12:44:37 +00001155** The expression is the default value for the most recently added column
1156** of the table currently under construction.
1157**
1158** Default value expressions must be constant. Raise an exception if this
1159** is not the case.
drhd9b02572001-04-15 00:37:09 +00001160**
1161** This routine is called by the parser while in the middle of
1162** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001163*/
drhb7916a72009-05-27 10:31:29 +00001164void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001165 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001166 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001167 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001168 p = pParse->pNewTable;
1169 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001170 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001171 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001172 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1173 pCol->zName);
1174 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001175 /* A copy of pExpr is used instead of the original, as pExpr contains
1176 ** tokens that point to volatile memory. The 'span' of the expression
1177 ** is required by pragma table_info.
1178 */
drh633e6d52008-07-28 19:34:53 +00001179 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001180 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1181 sqlite3DbFree(db, pCol->zDflt);
1182 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001183 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001184 }
danielk19777977a172004-11-09 12:44:37 +00001185 }
drhb7916a72009-05-27 10:31:29 +00001186 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001187}
1188
1189/*
drh4a324312001-12-21 14:30:42 +00001190** Designate the PRIMARY KEY for the table. pList is a list of names
1191** of columns that form the primary key. If pList is NULL, then the
1192** most recently added column of the table is the primary key.
1193**
1194** A table can have at most one primary key. If the table already has
1195** a primary key (and this is the second primary key) then create an
1196** error.
1197**
1198** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001199** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001200** field of the table under construction to be the index of the
1201** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1202** no INTEGER PRIMARY KEY.
1203**
1204** If the key is not an INTEGER PRIMARY KEY, then create a unique
1205** index for the key. No index is created for INTEGER PRIMARY KEYs.
1206*/
drh205f48e2004-11-05 00:43:11 +00001207void sqlite3AddPrimaryKey(
1208 Parse *pParse, /* Parsing context */
1209 ExprList *pList, /* List of field names to be indexed */
1210 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001211 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1212 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001213){
drh4a324312001-12-21 14:30:42 +00001214 Table *pTab = pParse->pNewTable;
1215 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001216 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001217 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001218 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001219 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001220 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001221 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001222 }
drh7d10d5a2008-08-20 16:35:10 +00001223 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001224 if( pList==0 ){
1225 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001226 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh78100cc2003-08-23 22:40:53 +00001227 }else{
danielk19770202b292004-06-09 09:55:16 +00001228 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001229 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001230 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1231 break;
1232 }
drh78100cc2003-08-23 22:40:53 +00001233 }
drh6e4fc2c2005-09-15 21:24:51 +00001234 if( iCol<pTab->nCol ){
drha371ace2012-09-13 14:22:47 +00001235 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh6e4fc2c2005-09-15 21:24:51 +00001236 }
drh4a324312001-12-21 14:30:42 +00001237 }
danielk19770202b292004-06-09 09:55:16 +00001238 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001239 }
1240 if( iCol>=0 && iCol<pTab->nCol ){
1241 zType = pTab->aCol[iCol].zType;
1242 }
drhfdd6e852005-12-16 01:06:16 +00001243 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1244 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001245 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001246 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001247 assert( autoInc==0 || autoInc==1 );
1248 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001249 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001250#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001251 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1252 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001253#endif
drh4a324312001-12-21 14:30:42 +00001254 }else{
dan1da40a32009-09-19 17:00:31 +00001255 Index *p;
drh8a9789b2013-08-01 03:36:59 +00001256 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001257 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001258 if( p ){
1259 p->autoIndex = 2;
1260 }
drhe0194f22003-02-26 13:52:51 +00001261 pList = 0;
drh4a324312001-12-21 14:30:42 +00001262 }
drhe0194f22003-02-26 13:52:51 +00001263
1264primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001265 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001266 return;
drh4a324312001-12-21 14:30:42 +00001267}
1268
1269/*
drhffe07b22005-11-03 00:41:17 +00001270** Add a new CHECK constraint to the table currently under construction.
1271*/
1272void sqlite3AddCheckConstraint(
1273 Parse *pParse, /* Parsing context */
1274 Expr *pCheckExpr /* The check expression */
1275){
1276#ifndef SQLITE_OMIT_CHECK
1277 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001278 if( pTab && !IN_DECLARE_VTAB ){
drh2938f922012-03-07 19:13:29 +00001279 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1280 if( pParse->constraintName.n ){
1281 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1282 }
drh33e619f2009-05-28 01:00:55 +00001283 }else
drhffe07b22005-11-03 00:41:17 +00001284#endif
drh33e619f2009-05-28 01:00:55 +00001285 {
drh2938f922012-03-07 19:13:29 +00001286 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001287 }
drhffe07b22005-11-03 00:41:17 +00001288}
1289
1290/*
drhd3d39e92004-05-20 22:16:29 +00001291** Set the collation function of the most recently parsed table column
1292** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001293*/
danielk197739002502007-11-12 09:50:26 +00001294void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001295 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001296 int i;
danielk197739002502007-11-12 09:50:26 +00001297 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001298 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001299
danielk1977b8cbb872006-06-19 05:33:45 +00001300 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001301 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001302 db = pParse->db;
1303 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001304 if( !zColl ) return;
1305
drhc4a64fa2009-05-11 20:53:28 +00001306 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001307 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001308 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001309 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001310
1311 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1312 ** then an index may have been created on this column before the
1313 ** collation type was added. Correct this if it is the case.
1314 */
1315 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1316 assert( pIdx->nColumn==1 );
1317 if( pIdx->aiColumn[0]==i ){
1318 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001319 }
1320 }
danielk197739002502007-11-12 09:50:26 +00001321 }else{
drh633e6d52008-07-28 19:34:53 +00001322 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001323 }
danielk19777cedc8d2004-06-10 10:50:08 +00001324}
1325
danielk1977466be562004-06-10 02:16:01 +00001326/*
1327** This function returns the collation sequence for database native text
1328** encoding identified by the string zName, length nName.
1329**
1330** If the requested collation sequence is not available, or not available
1331** in the database native encoding, the collation factory is invoked to
1332** request it. If the collation factory does not supply such a sequence,
1333** and the sequence is available in another text encoding, then that is
1334** returned instead.
1335**
1336** If no versions of the requested collations sequence are available, or
1337** another error occurs, NULL is returned and an error message written into
1338** pParse.
drha34001c2007-02-02 12:44:37 +00001339**
1340** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1341** invokes the collation factory if the named collation cannot be found
1342** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001343**
1344** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001345*/
drhc4a64fa2009-05-11 20:53:28 +00001346CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001347 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001348 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001349 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001350 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001351
drhc4a64fa2009-05-11 20:53:28 +00001352 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001353 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001354 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001355 }
1356
danielk19770202b292004-06-09 09:55:16 +00001357 return pColl;
1358}
1359
1360
drh8e2ca022002-06-17 17:07:19 +00001361/*
drh3f7d4e42004-07-24 14:35:58 +00001362** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001363**
1364** The schema cookie is used to determine when the schema for the
1365** database changes. After each schema change, the cookie value
1366** changes. When a process first reads the schema it records the
1367** cookie. Thereafter, whenever it goes to access the database,
1368** it checks the cookie to make sure the schema has not changed
1369** since it was last read.
1370**
1371** This plan is not completely bullet-proof. It is possible for
1372** the schema to change multiple times and for the cookie to be
1373** set back to prior value. But schema changes are infrequent
1374** and the probability of hitting the same cookie value is only
1375** 1 chance in 2^32. So we're safe enough.
1376*/
drh9cbf3422008-01-17 16:22:13 +00001377void sqlite3ChangeCookie(Parse *pParse, int iDb){
1378 int r1 = sqlite3GetTempReg(pParse);
1379 sqlite3 *db = pParse->db;
1380 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001381 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001382 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001383 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001384 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001385}
1386
1387/*
drh969fa7c2002-02-18 18:30:32 +00001388** Measure the number of characters needed to output the given
1389** identifier. The number returned includes any quotes used
1390** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001391**
1392** The estimate is conservative. It might be larger that what is
1393** really needed.
drh969fa7c2002-02-18 18:30:32 +00001394*/
1395static int identLength(const char *z){
1396 int n;
drh17f71932002-02-21 12:01:27 +00001397 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001398 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001399 }
drh234c39d2004-07-24 03:30:47 +00001400 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001401}
1402
1403/*
danielk19771b870de2009-03-14 08:37:23 +00001404** The first parameter is a pointer to an output buffer. The second
1405** parameter is a pointer to an integer that contains the offset at
1406** which to write into the output buffer. This function copies the
1407** nul-terminated string pointed to by the third parameter, zSignedIdent,
1408** to the specified offset in the buffer and updates *pIdx to refer
1409** to the first byte after the last byte written before returning.
1410**
1411** If the string zSignedIdent consists entirely of alpha-numeric
1412** characters, does not begin with a digit and is not an SQL keyword,
1413** then it is copied to the output buffer exactly as it is. Otherwise,
1414** it is quoted using double-quotes.
1415*/
drhc4a64fa2009-05-11 20:53:28 +00001416static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001417 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001418 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001419 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001420
drh17f71932002-02-21 12:01:27 +00001421 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001422 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001423 }
danielk19771b870de2009-03-14 08:37:23 +00001424 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1425 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001426 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001427 }
1428
drh234c39d2004-07-24 03:30:47 +00001429 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001430 for(j=0; zIdent[j]; j++){
1431 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001432 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001433 }
drh234c39d2004-07-24 03:30:47 +00001434 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001435 z[i] = 0;
1436 *pIdx = i;
1437}
1438
1439/*
1440** Generate a CREATE TABLE statement appropriate for the given
1441** table. Memory to hold the text of the statement is obtained
1442** from sqliteMalloc() and must be freed by the calling function.
1443*/
drh1d34fde2009-02-03 15:50:33 +00001444static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001445 int i, k, n;
1446 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001447 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001448 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001449 n = 0;
drh234c39d2004-07-24 03:30:47 +00001450 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001451 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001452 }
1453 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001454 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001455 zSep = "";
1456 zSep2 = ",";
1457 zEnd = ")";
1458 }else{
1459 zSep = "\n ";
1460 zSep2 = ",\n ";
1461 zEnd = "\n)";
1462 }
drhe0bc4042002-06-25 01:09:11 +00001463 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001464 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001465 if( zStmt==0 ){
1466 db->mallocFailed = 1;
1467 return 0;
1468 }
drhbdb339f2009-02-02 18:03:21 +00001469 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001470 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001471 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001472 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001473 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001474 static const char * const azType[] = {
1475 /* SQLITE_AFF_TEXT */ " TEXT",
1476 /* SQLITE_AFF_NONE */ "",
1477 /* SQLITE_AFF_NUMERIC */ " NUM",
1478 /* SQLITE_AFF_INTEGER */ " INT",
1479 /* SQLITE_AFF_REAL */ " REAL"
1480 };
1481 int len;
1482 const char *zType;
1483
drh5bb3eb92007-05-04 13:15:55 +00001484 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001485 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001486 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001487 identPut(zStmt, &k, pCol->zName);
1488 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001489 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001490 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1491 testcase( pCol->affinity==SQLITE_AFF_NONE );
1492 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1493 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1494 testcase( pCol->affinity==SQLITE_AFF_REAL );
1495
1496 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1497 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001498 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001499 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001500 memcpy(&zStmt[k], zType, len);
1501 k += len;
1502 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001503 }
drh5bb3eb92007-05-04 13:15:55 +00001504 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001505 return zStmt;
1506}
1507
1508/*
drhfdaac672013-10-04 15:30:21 +00001509** Estimate the total row width for a table.
1510*/
drhe13e9f52013-10-05 19:18:00 +00001511static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001512 unsigned wTable = 0;
1513 const Column *pTabCol;
1514 int i;
1515 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1516 wTable += pTabCol->szEst;
1517 }
1518 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001519 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001520}
1521
1522/*
drhe13e9f52013-10-05 19:18:00 +00001523** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001524*/
drhe13e9f52013-10-05 19:18:00 +00001525static void estimateIndexWidth(Index *pIdx){
drhfdaac672013-10-04 15:30:21 +00001526 unsigned wIndex = 1;
1527 int i;
1528 const Column *aCol = pIdx->pTable->aCol;
1529 for(i=0; i<pIdx->nColumn; i++){
1530 assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
1531 wIndex += aCol[pIdx->aiColumn[i]].szEst;
1532 }
drhe13e9f52013-10-05 19:18:00 +00001533 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001534}
1535
1536/*
drh75897232000-05-29 14:26:00 +00001537** This routine is called to report the final ")" that terminates
1538** a CREATE TABLE statement.
1539**
drhf57b3392001-10-08 13:22:32 +00001540** The table structure that other action routines have been building
1541** is added to the internal hash tables, assuming no errors have
1542** occurred.
drh75897232000-05-29 14:26:00 +00001543**
drh1d85d932004-02-14 23:05:52 +00001544** An entry for the table is made in the master table on disk, unless
1545** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001546** it means we are reading the sqlite_master table because we just
1547** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001548** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001549** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001550**
1551** If the pSelect argument is not NULL, it means that this routine
1552** was called to create a table generated from a
1553** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1554** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001555*/
danielk197719a8e7e2005-03-17 05:03:38 +00001556void sqlite3EndTable(
1557 Parse *pParse, /* Parse context */
1558 Token *pCons, /* The ',' token after the last column defn. */
1559 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1560 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1561){
drhfdaac672013-10-04 15:30:21 +00001562 Table *p; /* The new table */
1563 sqlite3 *db = pParse->db; /* The database connection */
1564 int iDb; /* Database in which the table lives */
1565 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001566
drh8af73d42009-05-13 22:58:28 +00001567 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001568 return;
1569 }
drh28037572000-08-02 13:47:41 +00001570 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001571 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001572
danielk1977517eb642004-06-07 10:00:31 +00001573 assert( !db->init.busy || !pSelect );
1574
drhb9bb7c12006-06-11 23:41:55 +00001575 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001576
drhffe07b22005-11-03 00:41:17 +00001577#ifndef SQLITE_OMIT_CHECK
1578 /* Resolve names in all CHECK constraint expressions.
1579 */
1580 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001581 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001582 }
1583#endif /* !defined(SQLITE_OMIT_CHECK) */
1584
drhe13e9f52013-10-05 19:18:00 +00001585 /* Estimate the average row size for the table and for all implied indices */
1586 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001587 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001588 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001589 }
1590
drh1d85d932004-02-14 23:05:52 +00001591 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001592 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1593 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001594 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001595 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001596 */
drh1d85d932004-02-14 23:05:52 +00001597 if( db->init.busy ){
1598 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001599 }
1600
drhe3c41372001-09-17 20:25:58 +00001601 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001602 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001603 **
drhe0bc4042002-06-25 01:09:11 +00001604 ** If this is a TEMPORARY table, write the entry into the auxiliary
1605 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001606 */
drh1d85d932004-02-14 23:05:52 +00001607 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001608 int n;
drhd8bc7082000-06-07 23:51:50 +00001609 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001610 char *zType; /* "view" or "table" */
1611 char *zType2; /* "VIEW" or "TABLE" */
1612 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001613
danielk19774adee202004-05-08 08:23:19 +00001614 v = sqlite3GetVdbe(pParse);
drh768578e2009-05-12 00:40:12 +00001615 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001616
drh66a51672008-01-03 00:01:23 +00001617 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001618
drh0fa991b2009-03-21 16:19:26 +00001619 /*
1620 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001621 */
drh4ff6dfa2002-03-03 23:06:00 +00001622 if( p->pSelect==0 ){
1623 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001624 zType = "table";
1625 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001626#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001627 }else{
1628 /* A view */
drh4794f732004-11-05 17:17:50 +00001629 zType = "view";
1630 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001631#endif
drh4ff6dfa2002-03-03 23:06:00 +00001632 }
danielk1977517eb642004-06-07 10:00:31 +00001633
danielk1977517eb642004-06-07 10:00:31 +00001634 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1635 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001636 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001637 **
1638 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1639 ** suitable state to query for the column names and types to be used
1640 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001641 **
1642 ** A shared-cache write-lock is not required to write to the new table,
1643 ** as a schema-lock must have already been obtained to create it. Since
1644 ** a schema-lock excludes all other database users, the write-lock would
1645 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001646 */
1647 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001648 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001649 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001650
danielk19776ab3a2e2009-02-19 14:39:25 +00001651 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001652 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001653 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001654 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001655 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001656 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001657 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001658 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001659 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001660 if( pSelTab==0 ) return;
1661 assert( p->aCol==0 );
1662 p->nCol = pSelTab->nCol;
1663 p->aCol = pSelTab->aCol;
1664 pSelTab->nCol = 0;
1665 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001666 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001667 }
1668 }
drh4794f732004-11-05 17:17:50 +00001669
drh4794f732004-11-05 17:17:50 +00001670 /* Compute the complete text of the CREATE statement */
1671 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001672 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001673 }else{
drh1bd10f82008-12-10 21:19:56 +00001674 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001675 zStmt = sqlite3MPrintf(db,
1676 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1677 );
drh4794f732004-11-05 17:17:50 +00001678 }
1679
1680 /* A slot for the record has already been allocated in the
1681 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001682 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001683 */
1684 sqlite3NestedParse(pParse,
1685 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001686 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1687 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001688 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001689 zType,
1690 p->zName,
1691 p->zName,
drhb7654112008-01-12 12:48:07 +00001692 pParse->regRoot,
1693 zStmt,
1694 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001695 );
drh633e6d52008-07-28 19:34:53 +00001696 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001697 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001698
1699#ifndef SQLITE_OMIT_AUTOINCREMENT
1700 /* Check to see if we need to create an sqlite_sequence table for
1701 ** keeping track of autoincrement keys.
1702 */
drh7d10d5a2008-08-20 16:35:10 +00001703 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001704 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001705 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001706 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001707 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001708 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1709 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001710 );
1711 }
1712 }
1713#endif
drh4794f732004-11-05 17:17:50 +00001714
1715 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001716 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001717 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001718 }
drh17e9e292003-02-01 13:53:28 +00001719
drh2958a4e2004-11-12 03:56:15 +00001720
drh17e9e292003-02-01 13:53:28 +00001721 /* Add the table to the in-memory representation of the database.
1722 */
drh8af73d42009-05-13 22:58:28 +00001723 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001724 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001725 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001726 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001727 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001728 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001729 if( pOld ){
1730 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001731 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001732 return;
1733 }
drh17e9e292003-02-01 13:53:28 +00001734 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001735 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001736
1737#ifndef SQLITE_OMIT_ALTERTABLE
1738 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001739 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001740 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001741 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001742 if( pCons->z==0 ){
1743 pCons = pEnd;
1744 }
drh1bd10f82008-12-10 21:19:56 +00001745 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001746 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001747 }
1748#endif
drh17e9e292003-02-01 13:53:28 +00001749 }
drh75897232000-05-29 14:26:00 +00001750}
1751
drhb7f91642004-10-31 02:22:47 +00001752#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001753/*
drha76b5df2002-02-23 02:32:10 +00001754** The parser calls this routine in order to create a new VIEW
1755*/
danielk19774adee202004-05-08 08:23:19 +00001756void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001757 Parse *pParse, /* The parsing context */
1758 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001759 Token *pName1, /* The token that holds the name of the view */
1760 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001761 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001762 int isTemp, /* TRUE for a TEMPORARY view */
1763 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001764){
drha76b5df2002-02-23 02:32:10 +00001765 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001766 int n;
drhb7916a72009-05-27 10:31:29 +00001767 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001768 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001769 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00001770 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00001771 int iDb;
drh17435752007-08-16 04:30:38 +00001772 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001773
drh7c3d64f2005-06-06 15:32:08 +00001774 if( pParse->nVar>0 ){
1775 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001776 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001777 return;
1778 }
drhfdd48a72006-09-11 23:45:48 +00001779 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001780 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001781 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001782 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001783 return;
1784 }
danielk1977ef2cb632004-05-29 02:37:19 +00001785 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001786 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00001787 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
1788 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00001789 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001790 return;
1791 }
drh174b6192002-12-03 02:22:52 +00001792
drh4b59ab52002-08-24 18:24:51 +00001793 /* Make a copy of the entire SELECT statement that defines the view.
1794 ** This will force all the Expr.token.z values to be dynamically
1795 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001796 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001797 */
danielk19776ab3a2e2009-02-19 14:39:25 +00001798 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00001799 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001800 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001801 return;
1802 }
drh17435752007-08-16 04:30:38 +00001803 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001804 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001805 }
drh4b59ab52002-08-24 18:24:51 +00001806
1807 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1808 ** the end.
1809 */
drha76b5df2002-02-23 02:32:10 +00001810 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00001811 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00001812 sEnd.z += sEnd.n;
1813 }
1814 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001815 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00001816 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00001817 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001818 sEnd.z = &z[n-1];
1819 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001820
danielk19774adee202004-05-08 08:23:19 +00001821 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001822 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001823 return;
drh417be792002-03-03 18:59:40 +00001824}
drhb7f91642004-10-31 02:22:47 +00001825#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001826
danielk1977fe3fcbe22006-06-12 12:08:45 +00001827#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001828/*
1829** The Table structure pTable is really a VIEW. Fill in the names of
1830** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001831** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001832*/
danielk19774adee202004-05-08 08:23:19 +00001833int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001834 Table *pSelTab; /* A fake table from which we get the result set */
1835 Select *pSel; /* Copy of the SELECT that implements the view */
1836 int nErr = 0; /* Number of errors encountered */
1837 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001838 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001839 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001840
1841 assert( pTable );
1842
danielk1977fe3fcbe22006-06-12 12:08:45 +00001843#ifndef SQLITE_OMIT_VIRTUALTABLE
1844 if( sqlite3VtabCallConnect(pParse, pTable) ){
1845 return SQLITE_ERROR;
1846 }
drh4cbdda92006-06-14 19:00:20 +00001847 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001848#endif
1849
1850#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001851 /* A positive nCol means the columns names for this view are
1852 ** already known.
1853 */
1854 if( pTable->nCol>0 ) return 0;
1855
1856 /* A negative nCol is a special marker meaning that we are currently
1857 ** trying to compute the column names. If we enter this routine with
1858 ** a negative nCol, it means two or more views form a loop, like this:
1859 **
1860 ** CREATE VIEW one AS SELECT * FROM two;
1861 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001862 **
drh768578e2009-05-12 00:40:12 +00001863 ** Actually, the error above is now caught prior to reaching this point.
1864 ** But the following test is still important as it does come up
1865 ** in the following:
1866 **
1867 ** CREATE TABLE main.ex1(a);
1868 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1869 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00001870 */
1871 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001872 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001873 return 1;
1874 }
drh85c23c62005-08-20 03:03:04 +00001875 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001876
1877 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001878 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1879 ** "*" elements in the results set of the view and will assign cursors
1880 ** to the elements of the FROM clause. But we do not want these changes
1881 ** to be permanent. So the computation is done on a copy of the SELECT
1882 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001883 */
drh9b3187e2005-01-18 14:45:47 +00001884 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00001885 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00001886 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00001887 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00001888 n = pParse->nTab;
1889 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1890 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00001891 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00001892#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001893 xAuth = db->xAuth;
1894 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001895 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001896 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001897#else
drh7d10d5a2008-08-20 16:35:10 +00001898 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001899#endif
drhd9da78a2009-03-24 15:08:09 +00001900 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00001901 pParse->nTab = n;
1902 if( pSelTab ){
1903 assert( pTable->aCol==0 );
1904 pTable->nCol = pSelTab->nCol;
1905 pTable->aCol = pSelTab->aCol;
1906 pSelTab->nCol = 0;
1907 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001908 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00001909 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00001910 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001911 }else{
1912 pTable->nCol = 0;
1913 nErr++;
1914 }
drh633e6d52008-07-28 19:34:53 +00001915 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001916 } else {
drh417be792002-03-03 18:59:40 +00001917 nErr++;
1918 }
drhb7f91642004-10-31 02:22:47 +00001919#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001920 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001921}
1922#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001923
drhb7f91642004-10-31 02:22:47 +00001924#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001925/*
drh8bf8dc92003-05-17 17:35:10 +00001926** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001927*/
drh9bb575f2004-09-06 17:24:11 +00001928static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001929 HashElem *i;
drh21206082011-04-04 18:22:02 +00001930 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00001931 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001932 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001933 Table *pTab = sqliteHashData(i);
1934 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00001935 sqliteDeleteColumnNames(db, pTab);
1936 pTab->aCol = 0;
1937 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00001938 }
1939 }
drh8bf8dc92003-05-17 17:35:10 +00001940 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001941}
drhb7f91642004-10-31 02:22:47 +00001942#else
1943# define sqliteViewResetAll(A,B)
1944#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001945
drh75897232000-05-29 14:26:00 +00001946/*
danielk1977a0bf2652004-11-04 14:30:04 +00001947** This function is called by the VDBE to adjust the internal schema
1948** used by SQLite when the btree layer moves a table root page. The
1949** root-page of a table or index in database iDb has changed from iFrom
1950** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001951**
1952** Ticket #1728: The symbol table might still contain information
1953** on tables and/or indices that are the process of being deleted.
1954** If you are unlucky, one of those deleted indices or tables might
1955** have the same rootpage number as the real table or index that is
1956** being moved. So we cannot stop searching after the first match
1957** because the first match might be for one of the deleted indices
1958** or tables and not the table/index that is actually being moved.
1959** We must continue looping until all tables and indices with
1960** rootpage==iFrom have been converted to have a rootpage of iTo
1961** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001962*/
1963#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00001964void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00001965 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001966 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00001967 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00001968
drhcdf011d2011-04-04 21:25:28 +00001969 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1970 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00001971 pHash = &pDb->pSchema->tblHash;
1972 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001973 Table *pTab = sqliteHashData(pElem);
1974 if( pTab->tnum==iFrom ){
1975 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001976 }
1977 }
danielk1977da184232006-01-05 11:34:32 +00001978 pHash = &pDb->pSchema->idxHash;
1979 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001980 Index *pIdx = sqliteHashData(pElem);
1981 if( pIdx->tnum==iFrom ){
1982 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001983 }
1984 }
danielk1977a0bf2652004-11-04 14:30:04 +00001985}
1986#endif
1987
1988/*
1989** Write code to erase the table with root-page iTable from database iDb.
1990** Also write code to modify the sqlite_master table and internal schema
1991** if a root-page of another table is moved by the btree-layer whilst
1992** erasing iTable (this can happen with an auto-vacuum database).
1993*/
drh4e0cff62004-11-05 05:10:28 +00001994static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1995 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001996 int r1 = sqlite3GetTempReg(pParse);
1997 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00001998 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00001999#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002000 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002001 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002002 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002003 ** reflect this.
2004 **
drh0fa991b2009-03-21 16:19:26 +00002005 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002006 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2007 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002008 */
danielk197763e3e9f2004-11-05 09:19:27 +00002009 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002010 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2011 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002012#endif
drhb7654112008-01-12 12:48:07 +00002013 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002014}
2015
2016/*
2017** Write VDBE code to erase table pTab and all associated indices on disk.
2018** Code to update the sqlite_master tables and internal schema definitions
2019** in case a root-page belonging to another table is moved by the btree layer
2020** is also added (this can happen with an auto-vacuum database).
2021*/
drh4e0cff62004-11-05 05:10:28 +00002022static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002023#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002024 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002025 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2026 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002027 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002028 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002029 }
2030#else
2031 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2032 ** is not defined), then it is important to call OP_Destroy on the
2033 ** table and index root-pages in order, starting with the numerically
2034 ** largest root-page number. This guarantees that none of the root-pages
2035 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2036 ** following were coded:
2037 **
2038 ** OP_Destroy 4 0
2039 ** ...
2040 ** OP_Destroy 5 0
2041 **
2042 ** and root page 5 happened to be the largest root-page number in the
2043 ** database, then root page 5 would be moved to page 4 by the
2044 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2045 ** a free-list page.
2046 */
2047 int iTab = pTab->tnum;
2048 int iDestroyed = 0;
2049
2050 while( 1 ){
2051 Index *pIdx;
2052 int iLargest = 0;
2053
2054 if( iDestroyed==0 || iTab<iDestroyed ){
2055 iLargest = iTab;
2056 }
2057 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2058 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002059 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002060 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2061 iLargest = iIdx;
2062 }
2063 }
danielk1977da184232006-01-05 11:34:32 +00002064 if( iLargest==0 ){
2065 return;
2066 }else{
2067 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002068 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002069 destroyRootPage(pParse, iLargest, iDb);
2070 iDestroyed = iLargest;
2071 }
danielk1977a0bf2652004-11-04 14:30:04 +00002072 }
2073#endif
2074}
2075
2076/*
drh74e7c8f2011-10-21 19:06:32 +00002077** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002078** after a DROP INDEX or DROP TABLE command.
2079*/
2080static void sqlite3ClearStatTables(
2081 Parse *pParse, /* The parsing context */
2082 int iDb, /* The database number */
2083 const char *zType, /* "idx" or "tbl" */
2084 const char *zName /* Name of index or table */
2085){
drha5ae4c32011-08-07 01:31:52 +00002086 int i;
2087 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002088 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002089 char zTab[24];
2090 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2091 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002092 sqlite3NestedParse(pParse,
2093 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002094 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002095 );
2096 }
2097 }
2098}
2099
2100/*
drhfaacf172011-08-12 01:51:45 +00002101** Generate code to drop a table.
2102*/
2103void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2104 Vdbe *v;
2105 sqlite3 *db = pParse->db;
2106 Trigger *pTrigger;
2107 Db *pDb = &db->aDb[iDb];
2108
2109 v = sqlite3GetVdbe(pParse);
2110 assert( v!=0 );
2111 sqlite3BeginWriteOperation(pParse, 1, iDb);
2112
2113#ifndef SQLITE_OMIT_VIRTUALTABLE
2114 if( IsVirtual(pTab) ){
2115 sqlite3VdbeAddOp0(v, OP_VBegin);
2116 }
2117#endif
2118
2119 /* Drop all triggers associated with the table being dropped. Code
2120 ** is generated to remove entries from sqlite_master and/or
2121 ** sqlite_temp_master if required.
2122 */
2123 pTrigger = sqlite3TriggerList(pParse, pTab);
2124 while( pTrigger ){
2125 assert( pTrigger->pSchema==pTab->pSchema ||
2126 pTrigger->pSchema==db->aDb[1].pSchema );
2127 sqlite3DropTriggerPtr(pParse, pTrigger);
2128 pTrigger = pTrigger->pNext;
2129 }
2130
2131#ifndef SQLITE_OMIT_AUTOINCREMENT
2132 /* Remove any entries of the sqlite_sequence table associated with
2133 ** the table being dropped. This is done before the table is dropped
2134 ** at the btree level, in case the sqlite_sequence table needs to
2135 ** move as a result of the drop (can happen in auto-vacuum mode).
2136 */
2137 if( pTab->tabFlags & TF_Autoincrement ){
2138 sqlite3NestedParse(pParse,
2139 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2140 pDb->zName, pTab->zName
2141 );
2142 }
2143#endif
2144
2145 /* Drop all SQLITE_MASTER table and index entries that refer to the
2146 ** table. The program name loops through the master table and deletes
2147 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002148 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002149 ** created in the temp database that refers to a table in another
2150 ** database.
2151 */
2152 sqlite3NestedParse(pParse,
2153 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2154 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002155 if( !isView && !IsVirtual(pTab) ){
2156 destroyTable(pParse, pTab);
2157 }
2158
2159 /* Remove the table entry from SQLite's internal schema and modify
2160 ** the schema cookie.
2161 */
2162 if( IsVirtual(pTab) ){
2163 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2164 }
2165 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2166 sqlite3ChangeCookie(pParse, iDb);
2167 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002168}
2169
2170/*
drh75897232000-05-29 14:26:00 +00002171** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002172** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002173*/
drha0733842005-12-29 01:11:36 +00002174void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002175 Table *pTab;
drh75897232000-05-29 14:26:00 +00002176 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002177 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002178 int iDb;
drh75897232000-05-29 14:26:00 +00002179
drh8af73d42009-05-13 22:58:28 +00002180 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002181 goto exit_drop_table;
2182 }
drh8af73d42009-05-13 22:58:28 +00002183 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002184 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002185 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002186 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002187 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002188
drha0733842005-12-29 01:11:36 +00002189 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002190 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002191 goto exit_drop_table;
2192 }
danielk1977da184232006-01-05 11:34:32 +00002193 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002194 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002195
2196 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2197 ** it is initialized.
2198 */
2199 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2200 goto exit_drop_table;
2201 }
drhe5f9c642003-01-13 23:27:31 +00002202#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002203 {
2204 int code;
danielk1977da184232006-01-05 11:34:32 +00002205 const char *zTab = SCHEMA_TABLE(iDb);
2206 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002207 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002208 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002209 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002210 }
drhe5f9c642003-01-13 23:27:31 +00002211 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002212 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002213 code = SQLITE_DROP_TEMP_VIEW;
2214 }else{
2215 code = SQLITE_DROP_VIEW;
2216 }
danielk19774b2688a2006-06-20 11:01:07 +00002217#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002218 }else if( IsVirtual(pTab) ){
2219 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002220 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002221#endif
drhe5f9c642003-01-13 23:27:31 +00002222 }else{
danielk197753c0f742005-03-29 03:10:59 +00002223 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002224 code = SQLITE_DROP_TEMP_TABLE;
2225 }else{
2226 code = SQLITE_DROP_TABLE;
2227 }
2228 }
danielk1977f1a381e2006-06-16 08:01:02 +00002229 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002230 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002231 }
danielk1977a8858102004-05-28 12:11:21 +00002232 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2233 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002234 }
drhe5f9c642003-01-13 23:27:31 +00002235 }
2236#endif
drh08ccfaa2011-10-07 23:52:25 +00002237 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2238 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002239 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002240 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002241 }
danielk1977576ec6b2005-01-21 11:55:25 +00002242
2243#ifndef SQLITE_OMIT_VIEW
2244 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2245 ** on a table.
2246 */
danielk1977a8858102004-05-28 12:11:21 +00002247 if( isView && pTab->pSelect==0 ){
2248 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2249 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002250 }
danielk1977a8858102004-05-28 12:11:21 +00002251 if( !isView && pTab->pSelect ){
2252 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2253 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002254 }
danielk1977576ec6b2005-01-21 11:55:25 +00002255#endif
drh75897232000-05-29 14:26:00 +00002256
drh1ccde152000-06-17 13:12:39 +00002257 /* Generate code to remove the table from the master table
2258 ** on disk.
2259 */
danielk19774adee202004-05-08 08:23:19 +00002260 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002261 if( v ){
drh77658e22007-12-04 16:54:52 +00002262 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002263 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002264 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002265 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002266 }
danielk1977a8858102004-05-28 12:11:21 +00002267
2268exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002269 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002270}
2271
2272/*
drhc2eef3b2002-08-31 18:53:06 +00002273** This routine is called to create a new foreign key on the table
2274** currently under construction. pFromCol determines which columns
2275** in the current table point to the foreign key. If pFromCol==0 then
2276** connect the key to the last column inserted. pTo is the name of
2277** the table referred to. pToCol is a list of tables in the other
2278** pTo table that the foreign key points to. flags contains all
2279** information about the conflict resolution algorithms specified
2280** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2281**
2282** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002283** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002284**
2285** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002286** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002287*/
danielk19774adee202004-05-08 08:23:19 +00002288void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002289 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002290 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002291 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002292 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002293 int flags /* Conflict resolution algorithms. */
2294){
danielk197718576932008-08-06 13:47:40 +00002295 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002296#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002297 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002298 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002299 Table *p = pParse->pNewTable;
2300 int nByte;
2301 int i;
2302 int nCol;
2303 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002304
2305 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002306 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002307 if( pFromCol==0 ){
2308 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002309 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002310 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002311 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002312 " should reference only one column of table %T",
2313 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002314 goto fk_end;
2315 }
2316 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002317 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002318 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002319 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002320 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002321 goto fk_end;
2322 }else{
danielk19770202b292004-06-09 09:55:16 +00002323 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002324 }
drhe61922a2009-05-02 13:29:37 +00002325 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002326 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002327 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002328 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002329 }
2330 }
drh633e6d52008-07-28 19:34:53 +00002331 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002332 if( pFKey==0 ){
2333 goto fk_end;
2334 }
drhc2eef3b2002-08-31 18:53:06 +00002335 pFKey->pFrom = p;
2336 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002337 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002338 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002339 memcpy(z, pTo->z, pTo->n);
2340 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002341 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002342 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002343 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002344 if( pFromCol==0 ){
2345 pFKey->aCol[0].iFrom = p->nCol-1;
2346 }else{
2347 for(i=0; i<nCol; i++){
2348 int j;
2349 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002350 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002351 pFKey->aCol[i].iFrom = j;
2352 break;
2353 }
2354 }
2355 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002356 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002357 "unknown column \"%s\" in foreign key definition",
2358 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002359 goto fk_end;
2360 }
2361 }
2362 }
2363 if( pToCol ){
2364 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002365 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002366 pFKey->aCol[i].zCol = z;
2367 memcpy(z, pToCol->a[i].zName, n);
2368 z[n] = 0;
2369 z += n+1;
2370 }
2371 }
2372 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002373 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2374 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002375
drh21206082011-04-04 18:22:02 +00002376 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002377 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2378 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2379 );
danf59c5ca2009-09-22 16:55:38 +00002380 if( pNextTo==pFKey ){
2381 db->mallocFailed = 1;
2382 goto fk_end;
2383 }
dan1da40a32009-09-19 17:00:31 +00002384 if( pNextTo ){
2385 assert( pNextTo->pPrevTo==0 );
2386 pFKey->pNextTo = pNextTo;
2387 pNextTo->pPrevTo = pFKey;
2388 }
2389
drhc2eef3b2002-08-31 18:53:06 +00002390 /* Link the foreign key to the table as the last step.
2391 */
2392 p->pFKey = pFKey;
2393 pFKey = 0;
2394
2395fk_end:
drh633e6d52008-07-28 19:34:53 +00002396 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002397#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002398 sqlite3ExprListDelete(db, pFromCol);
2399 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002400}
2401
2402/*
2403** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2404** clause is seen as part of a foreign key definition. The isDeferred
2405** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2406** The behavior of the most recently created foreign key is adjusted
2407** accordingly.
2408*/
danielk19774adee202004-05-08 08:23:19 +00002409void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002410#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002411 Table *pTab;
2412 FKey *pFKey;
2413 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002414 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002415 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002416#endif
drhc2eef3b2002-08-31 18:53:06 +00002417}
2418
2419/*
drh063336a2004-11-05 20:58:39 +00002420** Generate code that will erase and refill index *pIdx. This is
2421** used to initialize a newly created index or to recompute the
2422** content of an index in response to a REINDEX command.
2423**
2424** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002425** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002426** root page number of the index. If memRootPage is negative, then
2427** the index already exists and must be cleared before being refilled and
2428** the root page number of the index is taken from pIndex->tnum.
2429*/
2430static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2431 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002432 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2433 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002434 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002435 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002436 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002437 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002438 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002439 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002440 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002441 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002442 sqlite3 *db = pParse->db; /* The database connection */
2443 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002444
danielk19771d54df82004-11-23 15:41:16 +00002445#ifndef SQLITE_OMIT_AUTHORIZATION
2446 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002447 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002448 return;
2449 }
2450#endif
2451
danielk1977c00da102006-01-07 13:21:04 +00002452 /* Require a write-lock on the table to perform this operation */
2453 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2454
drh063336a2004-11-05 20:58:39 +00002455 v = sqlite3GetVdbe(pParse);
2456 if( v==0 ) return;
2457 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002458 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002459 }else{
2460 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002461 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002462 }
danielk1977b3bf5562006-01-10 17:58:23 +00002463 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002464 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002465 (char *)pKey, P4_KEYINFO_HANDOFF);
dan428c2182012-08-06 18:50:11 +00002466 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
dana20fde62011-07-12 14:28:05 +00002467
dan689ab892011-08-12 15:02:00 +00002468 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002469 iSorter = pParse->nTab++;
2470 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002471
2472 /* Open the table. Loop through all rows of the table, inserting index
2473 ** records into the sorter. */
danielk1977c00da102006-01-07 13:21:04 +00002474 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002475 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002476 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002477
drhb2b9d3d2013-08-01 01:14:43 +00002478 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
drhca892a72011-09-03 00:17:51 +00002479 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drhb2b9d3d2013-08-01 01:14:43 +00002480 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
drhca892a72011-09-03 00:17:51 +00002481 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2482 sqlite3VdbeJumpHere(v, addr1);
2483 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
2484 if( pIndex->onError!=OE_None ){
2485 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2486 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2487 addr2 = sqlite3VdbeCurrentAddr(v);
2488 sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
drhd91c1a12013-02-09 13:58:25 +00002489 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
2490 OE_Abort, "indexed columns are not unique", P4_STATIC
drhca892a72011-09-03 00:17:51 +00002491 );
2492 }else{
2493 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002494 }
drhca892a72011-09-03 00:17:51 +00002495 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2496 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2497 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002498 sqlite3ReleaseTempReg(pParse, regRecord);
drhca892a72011-09-03 00:17:51 +00002499 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
drhd654be82005-09-20 17:42:23 +00002500 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002501
drh66a51672008-01-03 00:01:23 +00002502 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2503 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002504 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002505}
2506
2507/*
drh23bf66d2004-12-14 03:34:34 +00002508** Create a new index for an SQL table. pName1.pName2 is the name of the index
2509** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002510** be NULL for a primary key or an index that is created to satisfy a
2511** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002512** as the table to be indexed. pParse->pNewTable is a table that is
2513** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002514**
drh382c0242001-10-06 16:33:02 +00002515** pList is a list of columns to be indexed. pList will be NULL if this
2516** is a primary key or unique-constraint on the most recent column added
2517** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002518**
2519** If the index is created successfully, return a pointer to the new Index
2520** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2521** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002522*/
dan1da40a32009-09-19 17:00:31 +00002523Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002524 Parse *pParse, /* All information about this parse */
2525 Token *pName1, /* First part of index name. May be NULL */
2526 Token *pName2, /* Second part of index name. May be NULL */
2527 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002528 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002529 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002530 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002531 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002532 int sortOrder, /* Sort order of primary key when pList==NULL */
2533 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002534){
dan1da40a32009-09-19 17:00:31 +00002535 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002536 Table *pTab = 0; /* Table to be indexed */
2537 Index *pIndex = 0; /* The index to be created */
2538 char *zName = 0; /* Name of the index */
2539 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002540 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002541 Token nullId; /* Fake token for an empty ID list */
2542 DbFixer sFix; /* For assigning database names to pTable */
2543 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002544 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002545 Db *pDb; /* The specific table containing the indexed database */
2546 int iDb; /* Index of the database that is being written */
2547 Token *pName = 0; /* Unqualified name of the index to create */
2548 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002549 const Column *pTabCol; /* A column in the table */
2550 int nCol; /* Number of columns */
2551 int nExtra = 0; /* Space allocated for zExtra[] */
2552 char *zExtra; /* Extra space after the Index object */
danielk1977cbb18d22004-05-28 11:37:27 +00002553
drh8af73d42009-05-13 22:58:28 +00002554 assert( pParse->nErr==0 ); /* Never called with prior errors */
2555 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002556 goto exit_create_index;
2557 }
2558 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002559 goto exit_create_index;
2560 }
drhdaffd0e2001-04-11 14:28:42 +00002561
drh75897232000-05-29 14:26:00 +00002562 /*
2563 ** Find the table that is to be indexed. Return early if not found.
2564 */
danielk1977cbb18d22004-05-28 11:37:27 +00002565 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002566
2567 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002568 ** to search for the table. 'Fix' the table name to this db
2569 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002570 */
2571 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002572 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002573 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002574 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002575
danielk197753c0f742005-03-29 03:10:59 +00002576#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002577 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002578 ** is a temp table. If so, set the database to 1. Do not do this
2579 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002580 */
danielk1977fe910332007-12-02 11:46:34 +00002581 if( !db->init.busy ){
2582 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002583 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002584 iDb = 1;
2585 }
danielk1977ef2cb632004-05-29 02:37:19 +00002586 }
danielk197753c0f742005-03-29 03:10:59 +00002587#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002588
drhd100f692013-10-03 15:39:44 +00002589 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2590 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002591 /* Because the parser constructs pTblName from a single identifier,
2592 ** sqlite3FixSrcList can never fail. */
2593 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002594 }
dan41fb5cd2012-10-04 19:33:00 +00002595 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002596 assert( db->mallocFailed==0 || pTab==0 );
2597 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002598 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2599 sqlite3ErrorMsg(pParse,
2600 "cannot create a TEMP index on non-TEMP table \"%s\"",
2601 pTab->zName);
2602 goto exit_create_index;
2603 }
drh75897232000-05-29 14:26:00 +00002604 }else{
drhe3c41372001-09-17 20:25:58 +00002605 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002606 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002607 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002608 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002609 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002610 }
drhfdd6e852005-12-16 01:06:16 +00002611 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002612
drhd3001712009-05-12 17:46:53 +00002613 assert( pTab!=0 );
2614 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002615 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh503a6862013-03-01 01:07:17 +00002616 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002617 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002618 goto exit_create_index;
2619 }
danielk1977576ec6b2005-01-21 11:55:25 +00002620#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002621 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002622 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002623 goto exit_create_index;
2624 }
danielk1977576ec6b2005-01-21 11:55:25 +00002625#endif
danielk19775ee9d692006-06-21 12:36:25 +00002626#ifndef SQLITE_OMIT_VIRTUALTABLE
2627 if( IsVirtual(pTab) ){
2628 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2629 goto exit_create_index;
2630 }
2631#endif
drh75897232000-05-29 14:26:00 +00002632
2633 /*
2634 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002635 ** index or table with the same name.
2636 **
2637 ** Exception: If we are reading the names of permanent indices from the
2638 ** sqlite_master table (because some other process changed the schema) and
2639 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002640 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002641 **
2642 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002643 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2644 ** own name.
drh75897232000-05-29 14:26:00 +00002645 */
danielk1977d8123362004-06-12 09:25:12 +00002646 if( pName ){
drh17435752007-08-16 04:30:38 +00002647 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002648 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002649 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002650 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002651 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002652 }
danielk1977d8123362004-06-12 09:25:12 +00002653 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002654 if( sqlite3FindTable(db, zName, 0)!=0 ){
2655 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2656 goto exit_create_index;
2657 }
2658 }
danielk197759a33f92007-03-17 10:26:59 +00002659 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2660 if( !ifNotExist ){
2661 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002662 }else{
2663 assert( !db->init.busy );
2664 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002665 }
danielk197759a33f92007-03-17 10:26:59 +00002666 goto exit_create_index;
2667 }
danielk1977a21c6b62005-01-24 10:25:59 +00002668 }else{
drhadbca9c2001-09-27 15:11:53 +00002669 int n;
2670 Index *pLoop;
2671 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002672 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002673 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002674 goto exit_create_index;
2675 }
drh75897232000-05-29 14:26:00 +00002676 }
2677
drhe5f9c642003-01-13 23:27:31 +00002678 /* Check for authorization to create an index.
2679 */
2680#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002681 {
drhfdd6e852005-12-16 01:06:16 +00002682 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002683 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002684 goto exit_create_index;
2685 }
2686 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002687 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002688 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002689 goto exit_create_index;
2690 }
drhe5f9c642003-01-13 23:27:31 +00002691 }
2692#endif
2693
drh75897232000-05-29 14:26:00 +00002694 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002695 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002696 ** So create a fake list to simulate this.
2697 */
2698 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002699 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002700 nullId.n = sqlite3Strlen30((char*)nullId.z);
drhb7916a72009-05-27 10:31:29 +00002701 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002702 if( pList==0 ) goto exit_create_index;
drhb7916a72009-05-27 10:31:29 +00002703 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
drh1bd10f82008-12-10 21:19:56 +00002704 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002705 }
2706
danielk1977b3bf5562006-01-10 17:58:23 +00002707 /* Figure out how many bytes of space are required to store explicitly
2708 ** specified collation sequence names.
2709 */
2710 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002711 Expr *pExpr = pList->a[i].pExpr;
2712 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00002713 assert( pExpr->op==TK_COLLATE );
2714 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00002715 }
2716 }
2717
drh75897232000-05-29 14:26:00 +00002718 /*
2719 ** Allocate the index structure.
2720 */
drhea678832008-12-10 19:26:22 +00002721 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002722 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002723 pIndex = sqlite3DbMallocZero(db,
drhe0711b42012-01-05 12:38:02 +00002724 ROUND8(sizeof(Index)) + /* Index structure */
drhe09b84c2011-11-14 02:53:54 +00002725 ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
2726 sizeof(char *)*nCol + /* Index.azColl */
2727 sizeof(int)*nCol + /* Index.aiColumn */
2728 sizeof(u8)*nCol + /* Index.aSortOrder */
2729 nName + 1 + /* Index.zName */
2730 nExtra /* Collation sequence names */
danielk1977b3bf5562006-01-10 17:58:23 +00002731 );
drh17435752007-08-16 04:30:38 +00002732 if( db->mallocFailed ){
2733 goto exit_create_index;
2734 }
drhe0711b42012-01-05 12:38:02 +00002735 zExtra = (char*)pIndex;
2736 pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
drhe09b84c2011-11-14 02:53:54 +00002737 pIndex->azColl = (char**)
2738 ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
2739 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
2740 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh78aecb72006-02-10 18:08:09 +00002741 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
drhfaacf172011-08-12 01:51:45 +00002742 pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
danielk1977b3bf5562006-01-10 17:58:23 +00002743 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2744 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002745 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002746 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002747 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002748 pIndex->onError = (u8)onError;
drh7699d1c2013-06-04 12:42:29 +00002749 pIndex->uniqNotNull = onError==OE_Abort;
drh1bd10f82008-12-10 21:19:56 +00002750 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002751 pIndex->pSchema = db->aDb[iDb].pSchema;
drh3780be12013-07-31 19:05:22 +00002752 if( pPIWhere ){
2753 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
2754 pIndex->pPartIdxWhere = pPIWhere;
2755 pPIWhere = 0;
2756 }
drh21206082011-04-04 18:22:02 +00002757 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002758
drhfdd6e852005-12-16 01:06:16 +00002759 /* Check to see if we should honor DESC requests on index columns
2760 */
danielk1977da184232006-01-05 11:34:32 +00002761 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002762 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002763 }else{
2764 sortOrderMask = 0; /* Ignore DESC */
2765 }
2766
drh1ccde152000-06-17 13:12:39 +00002767 /* Scan the names of the columns of the table to be indexed and
2768 ** load the column indices into the Index structure. Report an error
2769 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002770 **
2771 ** TODO: Add a test to make sure that the same column is not named
2772 ** more than once within the same index. Only the first instance of
2773 ** the column will ever be used by the optimizer. Note that using the
2774 ** same column more than once cannot be an error because that would
2775 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00002776 */
drhfdd6e852005-12-16 01:06:16 +00002777 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2778 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00002779 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002780 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002781
drhfdd6e852005-12-16 01:06:16 +00002782 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2783 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002784 }
2785 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002786 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002787 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00002788 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00002789 goto exit_create_index;
2790 }
drh967e8b72000-06-21 13:59:10 +00002791 pIndex->aiColumn[i] = j;
dan911ce412013-05-15 15:16:50 +00002792 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00002793 int nColl;
dan911ce412013-05-15 15:16:50 +00002794 assert( pListItem->pExpr->op==TK_COLLATE );
2795 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00002796 nColl = sqlite3Strlen30(zColl) + 1;
2797 assert( nExtra>=nColl );
2798 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00002799 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00002800 zExtra += nColl;
2801 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00002802 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002803 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00002804 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00002805 }
drhb7f24de2009-05-13 17:35:23 +00002806 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002807 goto exit_create_index;
2808 }
danielk1977b3bf5562006-01-10 17:58:23 +00002809 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002810 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002811 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00002812 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00002813 }
drh51147ba2005-07-23 22:59:55 +00002814 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00002815 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00002816
danielk1977d8123362004-06-12 09:25:12 +00002817 if( pTab==pParse->pNewTable ){
2818 /* This routine has been called to create an automatic index as a
2819 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2820 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2821 ** i.e. one of:
2822 **
2823 ** CREATE TABLE t(x PRIMARY KEY, y);
2824 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2825 **
2826 ** Either way, check to see if the table already has such an index. If
2827 ** so, don't bother creating this one. This only applies to
2828 ** automatically created indices. Users can do as they wish with
2829 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00002830 **
2831 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2832 ** (and thus suppressing the second one) even if they have different
2833 ** sort orders.
2834 **
2835 ** If there are different collating sequences or if the columns of
2836 ** the constraint occur in different orders, then the constraints are
2837 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00002838 */
2839 Index *pIdx;
2840 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2841 int k;
2842 assert( pIdx->onError!=OE_None );
2843 assert( pIdx->autoIndex );
2844 assert( pIndex->onError!=OE_None );
2845
2846 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2847 for(k=0; k<pIdx->nColumn; k++){
drhd3001712009-05-12 17:46:53 +00002848 const char *z1;
2849 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00002850 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00002851 z1 = pIdx->azColl[k];
2852 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00002853 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002854 }
2855 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002856 if( pIdx->onError!=pIndex->onError ){
2857 /* This constraint creates the same index as a previous
2858 ** constraint specified somewhere in the CREATE TABLE statement.
2859 ** However the ON CONFLICT clauses are different. If both this
2860 ** constraint and the previous equivalent constraint have explicit
2861 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00002862 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00002863 */
2864 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2865 sqlite3ErrorMsg(pParse,
2866 "conflicting ON CONFLICT clauses specified", 0);
2867 }
2868 if( pIdx->onError==OE_Default ){
2869 pIdx->onError = pIndex->onError;
2870 }
2871 }
danielk1977d8123362004-06-12 09:25:12 +00002872 goto exit_create_index;
2873 }
2874 }
2875 }
2876
drh75897232000-05-29 14:26:00 +00002877 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002878 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002879 */
drh234c39d2004-07-24 03:30:47 +00002880 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002881 Index *p;
drh21206082011-04-04 18:22:02 +00002882 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002883 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00002884 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00002885 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002886 if( p ){
2887 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002888 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002889 goto exit_create_index;
2890 }
drh5e00f6c2001-09-13 13:46:56 +00002891 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002892 if( pTblName!=0 ){
2893 pIndex->tnum = db->init.newTnum;
2894 }
drhd78eeee2001-09-13 16:18:53 +00002895 }
2896
drh1d85d932004-02-14 23:05:52 +00002897 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002898 ** involves writing the index into the master table and filling in the
2899 ** index with the current table contents.
2900 **
drh1d85d932004-02-14 23:05:52 +00002901 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2902 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002903 ** CREATE INDEX statements are read out of the master table. In
2904 ** the latter case the index already exists on disk, which is why
2905 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002906 **
danielk1977cbb18d22004-05-28 11:37:27 +00002907 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002908 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2909 ** has just been created, it contains no data and the index initialization
2910 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002911 */
drhb2b9d3d2013-08-01 01:14:43 +00002912 else if( pParse->nErr==0 ){
drhadbca9c2001-09-27 15:11:53 +00002913 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002914 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002915 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002916
danielk19774adee202004-05-08 08:23:19 +00002917 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002918 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002919
drhfdd6e852005-12-16 01:06:16 +00002920
drh063336a2004-11-05 20:58:39 +00002921 /* Create the rootpage for the index
2922 */
drhaee128d2005-02-14 20:48:18 +00002923 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002924 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002925
2926 /* Gather the complete text of the CREATE INDEX statement into
2927 ** the zStmt variable
2928 */
drhd3001712009-05-12 17:46:53 +00002929 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00002930 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00002931 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00002932 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002933 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00002934 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00002935 }else{
2936 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002937 /* zStmt = sqlite3MPrintf(""); */
2938 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002939 }
drh063336a2004-11-05 20:58:39 +00002940
2941 /* Add an entry in sqlite_master for this index
2942 */
2943 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002944 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002945 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2946 pIndex->zName,
2947 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002948 iMem,
drh063336a2004-11-05 20:58:39 +00002949 zStmt
2950 );
drh633e6d52008-07-28 19:34:53 +00002951 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002952
danielk1977a21c6b62005-01-24 10:25:59 +00002953 /* Fill the index with data and reparse the schema. Code an OP_Expire
2954 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002955 */
danielk1977cbb18d22004-05-28 11:37:27 +00002956 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002957 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002958 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00002959 sqlite3VdbeAddParseSchemaOp(v, iDb,
2960 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00002961 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002962 }
drh75897232000-05-29 14:26:00 +00002963 }
2964
danielk1977d8123362004-06-12 09:25:12 +00002965 /* When adding an index to the list of indices for a table, make
2966 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00002967 ** OE_Ignore. This is necessary for the correct constraint check
2968 ** processing (in sqlite3GenerateConstraintChecks()) as part of
2969 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00002970 */
drh234c39d2004-07-24 03:30:47 +00002971 if( db->init.busy || pTblName==0 ){
2972 if( onError!=OE_Replace || pTab->pIndex==0
2973 || pTab->pIndex->onError==OE_Replace){
2974 pIndex->pNext = pTab->pIndex;
2975 pTab->pIndex = pIndex;
2976 }else{
2977 Index *pOther = pTab->pIndex;
2978 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2979 pOther = pOther->pNext;
2980 }
2981 pIndex->pNext = pOther->pNext;
2982 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002983 }
dan1da40a32009-09-19 17:00:31 +00002984 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00002985 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002986 }
danielk1977d8123362004-06-12 09:25:12 +00002987
drh75897232000-05-29 14:26:00 +00002988 /* Clean up before exiting */
2989exit_create_index:
drh1fe05372013-07-31 18:12:26 +00002990 if( pIndex ) freeIndex(db, pIndex);
2991 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00002992 sqlite3ExprListDelete(db, pList);
2993 sqlite3SrcListDelete(db, pTblName);
2994 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00002995 return pRet;
drh75897232000-05-29 14:26:00 +00002996}
2997
2998/*
drh51147ba2005-07-23 22:59:55 +00002999** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003000** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003001**
3002** aiRowEst[0] is suppose to contain the number of elements in the index.
3003** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3004** number of rows in the table that match any particular value of the
3005** first column of the index. aiRowEst[2] is an estimate of the number
3006** of rows that match any particular combiniation of the first 2 columns
3007** of the index. And so forth. It must always be the case that
3008*
3009** aiRowEst[N]<=aiRowEst[N-1]
3010** aiRowEst[N]>=1
3011**
3012** Apart from that, we have little to go on besides intuition as to
3013** how aiRowEst[] should be initialized. The numbers generated here
3014** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003015*/
3016void sqlite3DefaultRowEst(Index *pIdx){
drhfaacf172011-08-12 01:51:45 +00003017 tRowcnt *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00003018 int i;
drhfaacf172011-08-12 01:51:45 +00003019 tRowcnt n;
drh28c4cf42005-07-27 20:41:43 +00003020 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00003021 a[0] = pIdx->pTable->nRowEst;
3022 if( a[0]<10 ) a[0] = 10;
3023 n = 10;
3024 for(i=1; i<=pIdx->nColumn; i++){
3025 a[i] = n;
3026 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00003027 }
3028 if( pIdx->onError!=OE_None ){
3029 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00003030 }
3031}
3032
3033/*
drh74e24cd2002-01-09 03:19:59 +00003034** This routine will drop an existing named index. This routine
3035** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003036*/
drh4d91a702006-01-04 15:54:36 +00003037void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003038 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003039 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003040 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003041 int iDb;
drh75897232000-05-29 14:26:00 +00003042
drh8af73d42009-05-13 22:58:28 +00003043 assert( pParse->nErr==0 ); /* Never called with prior errors */
3044 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003045 goto exit_drop_index;
3046 }
drhd24cc422003-03-27 12:51:24 +00003047 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003048 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3049 goto exit_drop_index;
3050 }
danielk19774adee202004-05-08 08:23:19 +00003051 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003052 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003053 if( !ifExists ){
3054 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003055 }else{
3056 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003057 }
drha6ecd332004-06-10 00:29:09 +00003058 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003059 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003060 }
drh485b39b2002-07-13 03:11:52 +00003061 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00003062 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003063 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003064 goto exit_drop_index;
3065 }
danielk1977da184232006-01-05 11:34:32 +00003066 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003067#ifndef SQLITE_OMIT_AUTHORIZATION
3068 {
3069 int code = SQLITE_DROP_INDEX;
3070 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003071 const char *zDb = db->aDb[iDb].zName;
3072 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003073 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003074 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003075 }
danielk1977da184232006-01-05 11:34:32 +00003076 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003077 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003078 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003079 }
drhed6c8672003-01-12 18:02:16 +00003080 }
drhe5f9c642003-01-13 23:27:31 +00003081#endif
drh75897232000-05-29 14:26:00 +00003082
3083 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003084 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003085 if( v ){
drh77658e22007-12-04 16:54:52 +00003086 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003087 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003088 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003089 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003090 );
drha5ae4c32011-08-07 01:31:52 +00003091 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003092 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003093 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003094 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003095 }
3096
drhd24cc422003-03-27 12:51:24 +00003097exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003098 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003099}
3100
3101/*
dan9ace1122012-03-29 07:51:45 +00003102** pArray is a pointer to an array of objects. Each object in the
3103** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3104** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003105**
dan9ace1122012-03-29 07:51:45 +00003106** When this function is called, *pnEntry contains the current size of
3107** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3108** in total).
drh13449892005-09-07 21:22:45 +00003109**
dan9ace1122012-03-29 07:51:45 +00003110** If the realloc() is successful (i.e. if no OOM condition occurs), the
3111** space allocated for the new object is zeroed, *pnEntry updated to
3112** reflect the new size of the array and a pointer to the new allocation
3113** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003114**
dan9ace1122012-03-29 07:51:45 +00003115** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3116** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003117*/
drhcf643722007-03-27 13:36:37 +00003118void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003119 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003120 void *pArray, /* Array of objects. Might be reallocated */
3121 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003122 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003123 int *pIdx /* Write the index of a new slot here */
3124){
3125 char *z;
drh6c535152012-02-02 03:38:30 +00003126 int n = *pnEntry;
3127 if( (n & (n-1))==0 ){
3128 int sz = (n==0) ? 1 : 2*n;
3129 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003130 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003131 *pIdx = -1;
3132 return pArray;
drh13449892005-09-07 21:22:45 +00003133 }
drhcf643722007-03-27 13:36:37 +00003134 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003135 }
drhcf643722007-03-27 13:36:37 +00003136 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003137 memset(&z[n * szEntry], 0, szEntry);
3138 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003139 ++*pnEntry;
3140 return pArray;
drh13449892005-09-07 21:22:45 +00003141}
3142
3143/*
drh75897232000-05-29 14:26:00 +00003144** Append a new element to the given IdList. Create a new IdList if
3145** need be.
drhdaffd0e2001-04-11 14:28:42 +00003146**
3147** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003148*/
drh17435752007-08-16 04:30:38 +00003149IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003150 int i;
drh75897232000-05-29 14:26:00 +00003151 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003152 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003153 if( pList==0 ) return 0;
3154 }
drhcf643722007-03-27 13:36:37 +00003155 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003156 db,
drhcf643722007-03-27 13:36:37 +00003157 pList->a,
3158 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003159 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003160 &i
3161 );
drh13449892005-09-07 21:22:45 +00003162 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003163 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003164 return 0;
drh75897232000-05-29 14:26:00 +00003165 }
drh17435752007-08-16 04:30:38 +00003166 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003167 return pList;
3168}
3169
3170/*
drhfe05af82005-07-21 03:14:59 +00003171** Delete an IdList.
3172*/
drh633e6d52008-07-28 19:34:53 +00003173void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003174 int i;
3175 if( pList==0 ) return;
3176 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003177 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003178 }
drh633e6d52008-07-28 19:34:53 +00003179 sqlite3DbFree(db, pList->a);
3180 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003181}
3182
3183/*
3184** Return the index in pList of the identifier named zId. Return -1
3185** if not found.
3186*/
3187int sqlite3IdListIndex(IdList *pList, const char *zName){
3188 int i;
3189 if( pList==0 ) return -1;
3190 for(i=0; i<pList->nId; i++){
3191 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3192 }
3193 return -1;
3194}
3195
3196/*
drha78c22c2008-11-11 18:28:58 +00003197** Expand the space allocated for the given SrcList object by
3198** creating nExtra new slots beginning at iStart. iStart is zero based.
3199** New slots are zeroed.
3200**
3201** For example, suppose a SrcList initially contains two entries: A,B.
3202** To append 3 new entries onto the end, do this:
3203**
3204** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3205**
3206** After the call above it would contain: A, B, nil, nil, nil.
3207** If the iStart argument had been 1 instead of 2, then the result
3208** would have been: A, nil, nil, nil, B. To prepend the new slots,
3209** the iStart value would be 0. The result then would
3210** be: nil, nil, nil, A, B.
3211**
3212** If a memory allocation fails the SrcList is unchanged. The
3213** db->mallocFailed flag will be set to true.
3214*/
3215SrcList *sqlite3SrcListEnlarge(
3216 sqlite3 *db, /* Database connection to notify of OOM errors */
3217 SrcList *pSrc, /* The SrcList to be enlarged */
3218 int nExtra, /* Number of new slots to add to pSrc->a[] */
3219 int iStart /* Index in pSrc->a[] of first new slot */
3220){
3221 int i;
3222
3223 /* Sanity checking on calling parameters */
3224 assert( iStart>=0 );
3225 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003226 assert( pSrc!=0 );
3227 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003228
3229 /* Allocate additional space if needed */
3230 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3231 SrcList *pNew;
3232 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003233 int nGot;
drha78c22c2008-11-11 18:28:58 +00003234 pNew = sqlite3DbRealloc(db, pSrc,
3235 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3236 if( pNew==0 ){
3237 assert( db->mallocFailed );
3238 return pSrc;
3239 }
3240 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003241 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drhad01d892013-06-19 13:59:49 +00003242 pSrc->nAlloc = (u8)nGot;
drha78c22c2008-11-11 18:28:58 +00003243 }
3244
3245 /* Move existing slots that come after the newly inserted slots
3246 ** out of the way */
3247 for(i=pSrc->nSrc-1; i>=iStart; i--){
3248 pSrc->a[i+nExtra] = pSrc->a[i];
3249 }
drhad01d892013-06-19 13:59:49 +00003250 pSrc->nSrc += (i8)nExtra;
drha78c22c2008-11-11 18:28:58 +00003251
3252 /* Zero the newly allocated slots */
3253 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3254 for(i=iStart; i<iStart+nExtra; i++){
3255 pSrc->a[i].iCursor = -1;
3256 }
3257
3258 /* Return a pointer to the enlarged SrcList */
3259 return pSrc;
3260}
3261
3262
3263/*
drhad3cab52002-05-24 02:04:32 +00003264** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003265** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003266**
drha78c22c2008-11-11 18:28:58 +00003267** A SrcList is returned, or NULL if there is an OOM error. The returned
3268** SrcList might be the same as the SrcList that was input or it might be
3269** a new one. If an OOM error does occurs, then the prior value of pList
3270** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003271**
3272** If pDatabase is not null, it means that the table has an optional
3273** database name prefix. Like this: "database.table". The pDatabase
3274** points to the table name and the pTable points to the database name.
3275** The SrcList.a[].zName field is filled with the table name which might
3276** come from pTable (if pDatabase is NULL) or from pDatabase.
3277** SrcList.a[].zDatabase is filled with the database name from pTable,
3278** or with NULL if no database is specified.
3279**
3280** In other words, if call like this:
3281**
drh17435752007-08-16 04:30:38 +00003282** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003283**
3284** Then B is a table name and the database name is unspecified. If called
3285** like this:
3286**
drh17435752007-08-16 04:30:38 +00003287** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003288**
drhd3001712009-05-12 17:46:53 +00003289** Then C is the table name and B is the database name. If C is defined
3290** then so is B. In other words, we never have a case where:
3291**
3292** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003293**
3294** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3295** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003296*/
drh17435752007-08-16 04:30:38 +00003297SrcList *sqlite3SrcListAppend(
3298 sqlite3 *db, /* Connection to notify of malloc failures */
3299 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3300 Token *pTable, /* Table to append */
3301 Token *pDatabase /* Database of the table */
3302){
drha99db3b2004-06-19 14:49:12 +00003303 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003304 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003305 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003306 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003307 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003308 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003309 }
drha78c22c2008-11-11 18:28:58 +00003310 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3311 if( db->mallocFailed ){
3312 sqlite3SrcListDelete(db, pList);
3313 return 0;
drhad3cab52002-05-24 02:04:32 +00003314 }
drha78c22c2008-11-11 18:28:58 +00003315 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003316 if( pDatabase && pDatabase->z==0 ){
3317 pDatabase = 0;
3318 }
drhd3001712009-05-12 17:46:53 +00003319 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003320 Token *pTemp = pDatabase;
3321 pDatabase = pTable;
3322 pTable = pTemp;
3323 }
drh17435752007-08-16 04:30:38 +00003324 pItem->zName = sqlite3NameFromToken(db, pTable);
3325 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003326 return pList;
3327}
3328
3329/*
drhdfe88ec2008-11-03 20:55:06 +00003330** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003331*/
danielk19774adee202004-05-08 08:23:19 +00003332void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003333 int i;
drh9b3187e2005-01-18 14:45:47 +00003334 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003335 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003336 if( pList ){
3337 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3338 if( pItem->iCursor>=0 ) break;
3339 pItem->iCursor = pParse->nTab++;
3340 if( pItem->pSelect ){
3341 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3342 }
drh63eb5f22003-04-29 16:20:44 +00003343 }
3344 }
3345}
3346
3347/*
drhad3cab52002-05-24 02:04:32 +00003348** Delete an entire SrcList including all its substructure.
3349*/
drh633e6d52008-07-28 19:34:53 +00003350void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003351 int i;
drhbe5c89a2004-07-26 00:31:09 +00003352 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003353 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003354 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003355 sqlite3DbFree(db, pItem->zDatabase);
3356 sqlite3DbFree(db, pItem->zName);
3357 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003358 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003359 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003360 sqlite3SelectDelete(db, pItem->pSelect);
3361 sqlite3ExprDelete(db, pItem->pOn);
3362 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003363 }
drh633e6d52008-07-28 19:34:53 +00003364 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003365}
3366
drh982cef72000-05-30 16:27:03 +00003367/*
drh61dfc312006-12-16 16:25:15 +00003368** This routine is called by the parser to add a new term to the
3369** end of a growing FROM clause. The "p" parameter is the part of
3370** the FROM clause that has already been constructed. "p" is NULL
3371** if this is the first term of the FROM clause. pTable and pDatabase
3372** are the name of the table and database named in the FROM clause term.
3373** pDatabase is NULL if the database name qualifier is missing - the
3374** usual case. If the term has a alias, then pAlias points to the
3375** alias token. If the term is a subquery, then pSubquery is the
3376** SELECT statement that the subquery encodes. The pTable and
3377** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3378** parameters are the content of the ON and USING clauses.
3379**
3380** Return a new SrcList which encodes is the FROM with the new
3381** term added.
3382*/
3383SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003384 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003385 SrcList *p, /* The left part of the FROM clause already seen */
3386 Token *pTable, /* Name of the table to add to the FROM clause */
3387 Token *pDatabase, /* Name of the database containing pTable */
3388 Token *pAlias, /* The right-hand side of the AS subexpression */
3389 Select *pSubquery, /* A subquery used in place of a table name */
3390 Expr *pOn, /* The ON clause of a join */
3391 IdList *pUsing /* The USING clause of a join */
3392){
3393 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003394 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003395 if( !p && (pOn || pUsing) ){
3396 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3397 (pOn ? "ON" : "USING")
3398 );
3399 goto append_from_error;
3400 }
drh17435752007-08-16 04:30:38 +00003401 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003402 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003403 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003404 }
3405 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003406 assert( pAlias!=0 );
3407 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003408 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003409 }
3410 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003411 pItem->pOn = pOn;
3412 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003413 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003414
3415 append_from_error:
3416 assert( p==0 );
3417 sqlite3ExprDelete(db, pOn);
3418 sqlite3IdListDelete(db, pUsing);
3419 sqlite3SelectDelete(db, pSubquery);
3420 return 0;
drh61dfc312006-12-16 16:25:15 +00003421}
3422
3423/*
danielk1977b1c685b2008-10-06 16:18:39 +00003424** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3425** element of the source-list passed as the second argument.
3426*/
3427void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003428 assert( pIndexedBy!=0 );
3429 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003430 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3431 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3432 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3433 /* A "NOT INDEXED" clause was supplied. See parse.y
3434 ** construct "indexed_opt" for details. */
3435 pItem->notIndexed = 1;
3436 }else{
3437 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3438 }
3439 }
3440}
3441
3442/*
drh61dfc312006-12-16 16:25:15 +00003443** When building up a FROM clause in the parser, the join operator
3444** is initially attached to the left operand. But the code generator
3445** expects the join operator to be on the right operand. This routine
3446** Shifts all join operators from left to right for an entire FROM
3447** clause.
3448**
3449** Example: Suppose the join is like this:
3450**
3451** A natural cross join B
3452**
3453** The operator is "natural cross join". The A and B operands are stored
3454** in p->a[0] and p->a[1], respectively. The parser initially stores the
3455** operator with A. This routine shifts that operator over to B.
3456*/
3457void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003458 if( p ){
drh61dfc312006-12-16 16:25:15 +00003459 int i;
drhd017ab92011-08-23 00:01:58 +00003460 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003461 for(i=p->nSrc-1; i>0; i--){
3462 p->a[i].jointype = p->a[i-1].jointype;
3463 }
3464 p->a[0].jointype = 0;
3465 }
3466}
3467
3468/*
drhc4a3c772001-04-04 11:48:57 +00003469** Begin a transaction
3470*/
drh684917c2004-10-05 02:41:42 +00003471void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003472 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003473 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003474 int i;
drh5e00f6c2001-09-13 13:46:56 +00003475
drhd3001712009-05-12 17:46:53 +00003476 assert( pParse!=0 );
3477 db = pParse->db;
3478 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003479/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003480 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3481 return;
3482 }
danielk19771d850a72004-05-31 08:26:49 +00003483 v = sqlite3GetVdbe(pParse);
3484 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003485 if( type!=TK_DEFERRED ){
3486 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003487 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003488 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003489 }
3490 }
drh66a51672008-01-03 00:01:23 +00003491 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003492}
3493
3494/*
3495** Commit a transaction
3496*/
danielk19774adee202004-05-08 08:23:19 +00003497void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003498 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003499
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, "COMMIT", 0, 0) ){
3503 return;
3504 }
danielk19771d850a72004-05-31 08:26:49 +00003505 v = sqlite3GetVdbe(pParse);
3506 if( v ){
drh66a51672008-01-03 00:01:23 +00003507 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003508 }
drhc4a3c772001-04-04 11:48:57 +00003509}
3510
3511/*
3512** Rollback a transaction
3513*/
danielk19774adee202004-05-08 08:23:19 +00003514void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003515 Vdbe *v;
3516
drhd3001712009-05-12 17:46:53 +00003517 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003518 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003519 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3520 return;
3521 }
danielk19774adee202004-05-08 08:23:19 +00003522 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003523 if( v ){
drh66a51672008-01-03 00:01:23 +00003524 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003525 }
drhc4a3c772001-04-04 11:48:57 +00003526}
drhf57b14a2001-09-14 18:54:08 +00003527
3528/*
danielk1977fd7f0452008-12-17 17:30:26 +00003529** This function is called by the parser when it parses a command to create,
3530** release or rollback an SQL savepoint.
3531*/
3532void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003533 char *zName = sqlite3NameFromToken(pParse->db, pName);
3534 if( zName ){
3535 Vdbe *v = sqlite3GetVdbe(pParse);
3536#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003537 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003538 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3539#endif
3540 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3541 sqlite3DbFree(pParse->db, zName);
3542 return;
3543 }
3544 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003545 }
3546}
3547
3548/*
drhdc3ff9c2004-08-18 02:10:15 +00003549** Make sure the TEMP database is open and available for use. Return
3550** the number of errors. Leave any error messages in the pParse structure.
3551*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003552int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003553 sqlite3 *db = pParse->db;
3554 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003555 int rc;
drh10a76c92010-01-26 01:25:26 +00003556 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003557 static const int flags =
3558 SQLITE_OPEN_READWRITE |
3559 SQLITE_OPEN_CREATE |
3560 SQLITE_OPEN_EXCLUSIVE |
3561 SQLITE_OPEN_DELETEONCLOSE |
3562 SQLITE_OPEN_TEMP_DB;
3563
dan3a6d8ae2011-04-23 15:54:54 +00003564 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003565 if( rc!=SQLITE_OK ){
3566 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3567 "file for storing temporary tables");
3568 pParse->rc = rc;
3569 return 1;
3570 }
drh10a76c92010-01-26 01:25:26 +00003571 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003572 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003573 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3574 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003575 return 1;
drh10a76c92010-01-26 01:25:26 +00003576 }
drhdc3ff9c2004-08-18 02:10:15 +00003577 }
3578 return 0;
3579}
3580
3581/*
drh80242052004-06-09 00:48:12 +00003582** Generate VDBE code that will verify the schema cookie and start
3583** a read-transaction for all named database files.
3584**
3585** It is important that all schema cookies be verified and all
3586** read transactions be started before anything else happens in
3587** the VDBE program. But this routine can be called after much other
3588** code has been generated. So here is what we do:
3589**
drhc275b4e2004-07-19 17:25:24 +00003590** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003591** will jump to a subroutine at the end of the program. Then we
3592** record every database that needs its schema verified in the
3593** pParse->cookieMask field. Later, after all other code has been
3594** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003595** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003596** will be made to point to that subroutine. The generation of the
3597** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003598**
3599** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3600** schema on any databases. This can be used to position the OP_Goto
3601** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003602*/
danielk19774adee202004-05-08 08:23:19 +00003603void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003604 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003605
danf78baaf2012-12-06 19:37:22 +00003606#ifndef SQLITE_OMIT_TRIGGER
3607 if( pToplevel!=pParse ){
3608 /* This branch is taken if a trigger is currently being coded. In this
3609 ** case, set cookieGoto to a non-zero value to show that this function
3610 ** has been called. This is used by the sqlite3ExprCodeConstants()
3611 ** function. */
3612 pParse->cookieGoto = -1;
3613 }
3614#endif
dan65a7cd12009-09-01 12:16:01 +00003615 if( pToplevel->cookieGoto==0 ){
3616 Vdbe *v = sqlite3GetVdbe(pToplevel);
3617 if( v==0 ) return; /* This only happens if there was a prior error */
3618 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003619 }
drhc275b4e2004-07-19 17:25:24 +00003620 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003621 sqlite3 *db = pToplevel->db;
drh64123582011-04-02 20:01:02 +00003622 yDbMask mask;
dan65a7cd12009-09-01 12:16:01 +00003623
drhc275b4e2004-07-19 17:25:24 +00003624 assert( iDb<db->nDb );
3625 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003626 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drh21206082011-04-04 18:22:02 +00003627 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh64123582011-04-02 20:01:02 +00003628 mask = ((yDbMask)1)<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003629 if( (pToplevel->cookieMask & mask)==0 ){
3630 pToplevel->cookieMask |= mask;
3631 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003632 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003633 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003634 }
drhc275b4e2004-07-19 17:25:24 +00003635 }
drh001bbcb2003-03-19 03:14:00 +00003636 }
drh001bbcb2003-03-19 03:14:00 +00003637}
3638
3639/*
dan57966752011-04-09 17:32:58 +00003640** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3641** attached database. Otherwise, invoke it for the database named zDb only.
3642*/
3643void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3644 sqlite3 *db = pParse->db;
3645 int i;
3646 for(i=0; i<db->nDb; i++){
3647 Db *pDb = &db->aDb[i];
3648 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3649 sqlite3CodeVerifySchema(pParse, i);
3650 }
3651 }
3652}
3653
3654/*
drh1c928532002-01-31 15:54:21 +00003655** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003656** might change the database.
3657**
3658** This routine starts a new transaction if we are not already within
3659** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003660** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003661** be set for operations that might fail (due to a constraint) part of
3662** the way through and which will need to undo some writes without having to
3663** rollback the whole transaction. For operations where all constraints
3664** can be checked before any changes are made to the database, it is never
3665** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003666*/
drh7f0f12e2004-05-21 13:39:50 +00003667void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003668 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003669 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003670 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003671 pToplevel->isMultiWrite |= setStatement;
3672}
3673
drhff738bc2009-09-24 00:09:58 +00003674/*
3675** Indicate that the statement currently under construction might write
3676** more than one entry (example: deleting one row then inserting another,
3677** inserting multiple rows in a table, or inserting a row and index entries.)
3678** If an abort occurs after some of these writes have completed, then it will
3679** be necessary to undo the completed writes.
3680*/
3681void sqlite3MultiWrite(Parse *pParse){
3682 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3683 pToplevel->isMultiWrite = 1;
3684}
3685
dane0af83a2009-09-08 19:15:01 +00003686/*
drhff738bc2009-09-24 00:09:58 +00003687** The code generator calls this routine if is discovers that it is
3688** possible to abort a statement prior to completion. In order to
3689** perform this abort without corrupting the database, we need to make
3690** sure that the statement is protected by a statement transaction.
3691**
3692** Technically, we only need to set the mayAbort flag if the
3693** isMultiWrite flag was previously set. There is a time dependency
3694** such that the abort must occur after the multiwrite. This makes
3695** some statements involving the REPLACE conflict resolution algorithm
3696** go a little faster. But taking advantage of this time dependency
3697** makes it more difficult to prove that the code is correct (in
3698** particular, it prevents us from writing an effective
3699** implementation of sqlite3AssertMayAbort()) and so we have chosen
3700** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003701*/
3702void sqlite3MayAbort(Parse *pParse){
3703 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3704 pToplevel->mayAbort = 1;
3705}
3706
3707/*
3708** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3709** error. The onError parameter determines which (if any) of the statement
3710** and/or current transaction is rolled back.
3711*/
drhd91c1a12013-02-09 13:58:25 +00003712void sqlite3HaltConstraint(
3713 Parse *pParse, /* Parsing context */
3714 int errCode, /* extended error code */
3715 int onError, /* Constraint type */
3716 char *p4, /* Error message */
3717 int p4type /* P4_STATIC or P4_TRANSIENT */
3718){
dane0af83a2009-09-08 19:15:01 +00003719 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003720 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003721 if( onError==OE_Abort ){
3722 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003723 }
drhd91c1a12013-02-09 13:58:25 +00003724 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drh663fc632002-02-02 18:49:19 +00003725}
3726
drh4343fea2004-11-05 23:46:15 +00003727/*
3728** Check to see if pIndex uses the collating sequence pColl. Return
3729** true if it does and false if it does not.
3730*/
3731#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003732static int collationMatch(const char *zColl, Index *pIndex){
3733 int i;
drh04491712009-05-13 17:21:13 +00003734 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00003735 for(i=0; i<pIndex->nColumn; i++){
3736 const char *z = pIndex->azColl[i];
drh04491712009-05-13 17:21:13 +00003737 assert( z!=0 );
3738 if( 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00003739 return 1;
3740 }
drh4343fea2004-11-05 23:46:15 +00003741 }
3742 return 0;
3743}
3744#endif
3745
3746/*
3747** Recompute all indices of pTab that use the collating sequence pColl.
3748** If pColl==0 then recompute all indices of pTab.
3749*/
3750#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003751static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003752 Index *pIndex; /* An index associated with pTab */
3753
3754 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003755 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003756 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3757 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003758 sqlite3RefillIndex(pParse, pIndex, -1);
3759 }
3760 }
3761}
3762#endif
3763
3764/*
3765** Recompute all indices of all tables in all databases where the
3766** indices use the collating sequence pColl. If pColl==0 then recompute
3767** all indices everywhere.
3768*/
3769#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003770static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003771 Db *pDb; /* A single database */
3772 int iDb; /* The database index number */
3773 sqlite3 *db = pParse->db; /* The database connection */
3774 HashElem *k; /* For looping over tables in pDb */
3775 Table *pTab; /* A table in the database */
3776
drh21206082011-04-04 18:22:02 +00003777 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00003778 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003779 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003780 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003781 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003782 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003783 }
3784 }
3785}
3786#endif
3787
3788/*
drheee46cf2004-11-06 00:02:48 +00003789** Generate code for the REINDEX command.
3790**
3791** REINDEX -- 1
3792** REINDEX <collation> -- 2
3793** REINDEX ?<database>.?<tablename> -- 3
3794** REINDEX ?<database>.?<indexname> -- 4
3795**
3796** Form 1 causes all indices in all attached databases to be rebuilt.
3797** Form 2 rebuilds all indices in all databases that use the named
3798** collating function. Forms 3 and 4 rebuild the named index or all
3799** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003800*/
3801#ifndef SQLITE_OMIT_REINDEX
3802void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3803 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3804 char *z; /* Name of a table or index */
3805 const char *zDb; /* Name of the database */
3806 Table *pTab; /* A table in the database */
3807 Index *pIndex; /* An index associated with pTab */
3808 int iDb; /* The database index number */
3809 sqlite3 *db = pParse->db; /* The database connection */
3810 Token *pObjName; /* Name of the table or index to be reindexed */
3811
danielk197733a5edc2005-01-27 00:22:02 +00003812 /* Read the database schema. If an error occurs, leave an error message
3813 ** and code in pParse and return NULL. */
3814 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003815 return;
danielk197733a5edc2005-01-27 00:22:02 +00003816 }
3817
drh8af73d42009-05-13 22:58:28 +00003818 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00003819 reindexDatabases(pParse, 0);
3820 return;
drhd3001712009-05-12 17:46:53 +00003821 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003822 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003823 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003824 zColl = sqlite3NameFromToken(pParse->db, pName1);
3825 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00003826 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00003827 if( pColl ){
drhd3001712009-05-12 17:46:53 +00003828 reindexDatabases(pParse, zColl);
3829 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003830 return;
3831 }
drh633e6d52008-07-28 19:34:53 +00003832 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003833 }
3834 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3835 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003836 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003837 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003838 zDb = db->aDb[iDb].zName;
3839 pTab = sqlite3FindTable(db, z, zDb);
3840 if( pTab ){
3841 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003842 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003843 return;
3844 }
3845 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003846 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003847 if( pIndex ){
3848 sqlite3BeginWriteOperation(pParse, 0, iDb);
3849 sqlite3RefillIndex(pParse, pIndex, -1);
3850 return;
3851 }
3852 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3853}
3854#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003855
3856/*
3857** Return a dynamicly allocated KeyInfo structure that can be used
3858** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3859**
3860** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003861** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003862** pointer. If an error occurs (out of memory or missing collation
3863** sequence), NULL is returned and the state of pParse updated to reflect
3864** the error.
3865*/
3866KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3867 int i;
3868 int nCol = pIdx->nColumn;
drh323df792013-08-05 19:11:29 +00003869 KeyInfo *pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00003870
drh323df792013-08-05 19:11:29 +00003871 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
danielk1977b3bf5562006-01-10 17:58:23 +00003872 if( pKey ){
danielk1977b3bf5562006-01-10 17:58:23 +00003873 for(i=0; i<nCol; i++){
3874 char *zColl = pIdx->azColl[i];
3875 assert( zColl );
drhc4a64fa2009-05-11 20:53:28 +00003876 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003877 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3878 }
danielk1977b3bf5562006-01-10 17:58:23 +00003879 }
3880
3881 if( pParse->nErr ){
drh323df792013-08-05 19:11:29 +00003882 sqlite3DbFree(pParse->db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003883 pKey = 0;
3884 }
3885 return pKey;
3886}