blob: 27f026c8dd7221dadf15cae76d6c8c246d7eb903 [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;
drhf30a9692013-11-15 01:10:18 +0000153 int iDb, i, addr;
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
drhf30a9692013-11-15 01:10:18 +0000167 for(i=0; i<pParse->nVtabLock; i++){
168 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
169 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000170 }
drhf30a9692013-11-15 01:10:18 +0000171 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000172#endif
danielk1977c00da102006-01-07 13:21:04 +0000173
174 /* Once all the cookies have been verified and transactions opened,
175 ** obtain the required table-locks. This is a no-op unless the
176 ** shared-cache feature is enabled.
177 */
178 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000179
180 /* Initialize any AUTOINCREMENT data structures required.
181 */
182 sqlite3AutoincrementBegin(pParse);
183
drhf30a9692013-11-15 01:10:18 +0000184 /* Code constant expressions that where factored out of inner loops */
185 addr = pParse->cookieGoto;
186 if( pParse->pConstExpr ){
187 ExprList *pEL = pParse->pConstExpr;
188 pParse->cookieGoto = 0;
189 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000190 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000191 }
192 }
193
drh0b9f50d2009-06-23 20:28:53 +0000194 /* Finally, jump back to the beginning of the executable code. */
drhf30a9692013-11-15 01:10:18 +0000195 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
drh80242052004-06-09 00:48:12 +0000196 }
drh71c697e2004-08-08 23:39:19 +0000197 }
198
drh3f7d4e42004-07-24 14:35:58 +0000199
drh80242052004-06-09 00:48:12 +0000200 /* Get the VDBE program ready for execution
201 */
drh04491712009-05-13 17:21:13 +0000202 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000203 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000204 /* A minimum of one cursor is required if autoincrement is used
205 * See ticket [a696379c1f08866] */
206 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000207 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000208 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000209 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000210 }else{
drh483750b2003-01-29 18:46:51 +0000211 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000212 }
drha226d052002-09-25 19:04:07 +0000213 pParse->nTab = 0;
214 pParse->nMem = 0;
215 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000216 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000217 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000218 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000219}
220
221/*
drh205f48e2004-11-05 00:43:11 +0000222** Run the parser and code generator recursively in order to generate
223** code for the SQL statement given onto the end of the pParse context
224** currently under construction. When the parser is run recursively
225** this way, the final OP_Halt is not appended and other initialization
226** and finalization steps are omitted because those are handling by the
227** outermost parser.
228**
229** Not everything is nestable. This facility is designed to permit
230** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000231** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000232*/
233void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
234 va_list ap;
235 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000236 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000237 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000238# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
239 char saveBuf[SAVE_SZ];
240
drh205f48e2004-11-05 00:43:11 +0000241 if( pParse->nErr ) return;
242 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
243 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000244 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000245 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000246 if( zSql==0 ){
247 return; /* A malloc must have failed */
248 }
drh205f48e2004-11-05 00:43:11 +0000249 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000250 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
251 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000252 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000253 sqlite3DbFree(db, zErrMsg);
254 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000255 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000256 pParse->nested--;
257}
258
259/*
danielk19778a414492004-06-29 08:59:35 +0000260** Locate the in-memory structure that describes a particular database
261** table given the name of that table and (optionally) the name of the
262** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000263**
danielk19778a414492004-06-29 08:59:35 +0000264** If zDatabase is 0, all databases are searched for the table and the
265** first matching table is returned. (No checking for duplicate table
266** names is done.) The search order is TEMP first, then MAIN, then any
267** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000268**
danielk19774adee202004-05-08 08:23:19 +0000269** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000270*/
drh9bb575f2004-09-06 17:24:11 +0000271Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000272 Table *p = 0;
273 int i;
drh0a687d12008-07-08 14:52:07 +0000274 int nName;
drh645f63e2004-06-22 13:22:40 +0000275 assert( zName!=0 );
drhdee0e402009-05-03 20:23:53 +0000276 nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000277 /* All mutexes are required for schema access. Make sure we hold them. */
278 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000279 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000280 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000281 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000282 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh0a687d12008-07-08 14:52:07 +0000283 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000284 if( p ) break;
285 }
drh74e24cd2002-01-09 03:19:59 +0000286 return p;
drh75897232000-05-29 14:26:00 +0000287}
288
289/*
danielk19778a414492004-06-29 08:59:35 +0000290** Locate the in-memory structure that describes a particular database
291** table given the name of that table and (optionally) the name of the
292** database containing the table. Return NULL if not found. Also leave an
293** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000294**
danielk19778a414492004-06-29 08:59:35 +0000295** The difference between this routine and sqlite3FindTable() is that this
296** routine leaves an error message in pParse->zErrMsg where
297** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000298*/
drhca424112008-01-25 15:04:48 +0000299Table *sqlite3LocateTable(
300 Parse *pParse, /* context in which to report errors */
301 int isView, /* True if looking for a VIEW rather than a TABLE */
302 const char *zName, /* Name of the table we are looking for */
303 const char *zDbase /* Name of the database. Might be NULL */
304){
drha69d9162003-04-17 22:57:53 +0000305 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000306
danielk19778a414492004-06-29 08:59:35 +0000307 /* Read the database schema. If an error occurs, leave an error message
308 ** and code in pParse and return NULL. */
309 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
310 return 0;
311 }
312
danielk19774adee202004-05-08 08:23:19 +0000313 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000314 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000315 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000316 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000317 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000318 }else{
drhca424112008-01-25 15:04:48 +0000319 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000320 }
drha6ecd332004-06-10 00:29:09 +0000321 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000322 }
323 return p;
324}
325
326/*
dan41fb5cd2012-10-04 19:33:00 +0000327** Locate the table identified by *p.
328**
329** This is a wrapper around sqlite3LocateTable(). The difference between
330** sqlite3LocateTable() and this function is that this function restricts
331** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
332** non-NULL if it is part of a view or trigger program definition. See
333** sqlite3FixSrcList() for details.
334*/
335Table *sqlite3LocateTableItem(
336 Parse *pParse,
337 int isView,
338 struct SrcList_item *p
339){
340 const char *zDb;
341 assert( p->pSchema==0 || p->zDatabase==0 );
342 if( p->pSchema ){
343 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
344 zDb = pParse->db->aDb[iDb].zName;
345 }else{
346 zDb = p->zDatabase;
347 }
348 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
349}
350
351/*
drha69d9162003-04-17 22:57:53 +0000352** Locate the in-memory structure that describes
353** a particular index given the name of that index
354** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000355** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000356**
357** If zDatabase is 0, all databases are searched for the
358** table and the first matching index is returned. (No checking
359** for duplicate index names is done.) The search order is
360** TEMP first, then MAIN, then any auxiliary databases added
361** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000362*/
drh9bb575f2004-09-06 17:24:11 +0000363Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000364 Index *p = 0;
365 int i;
drhdee0e402009-05-03 20:23:53 +0000366 int nName = sqlite3Strlen30(zName);
drh21206082011-04-04 18:22:02 +0000367 /* All mutexes are required for schema access. Make sure we hold them. */
368 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000369 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000370 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000371 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000372 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000373 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000374 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drh04491712009-05-13 17:21:13 +0000375 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000376 if( p ) break;
377 }
drh74e24cd2002-01-09 03:19:59 +0000378 return p;
drh75897232000-05-29 14:26:00 +0000379}
380
381/*
drh956bc922004-07-24 17:38:29 +0000382** Reclaim the memory used by an index
383*/
dan1feeaed2010-07-23 15:41:47 +0000384static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000385#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000386 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000387#endif
drh2ec2fb22013-11-06 19:59:23 +0000388 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
drh1fe05372013-07-31 18:12:26 +0000389 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000390 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000391 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh633e6d52008-07-28 19:34:53 +0000392 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000393}
394
395/*
drhc96d8532005-05-03 12:30:33 +0000396** For the index called zIdxName which is found in the database iDb,
397** unlike that index from its Table then remove the index from
398** the index hash table and free all memory structures associated
399** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000400*/
drh9bb575f2004-09-06 17:24:11 +0000401void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000402 Index *pIndex;
403 int len;
drh21206082011-04-04 18:22:02 +0000404 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000405
drh21206082011-04-04 18:22:02 +0000406 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
407 pHash = &db->aDb[iDb].pSchema->idxHash;
drhdee0e402009-05-03 20:23:53 +0000408 len = sqlite3Strlen30(zIdxName);
drha83ccca2009-04-28 13:01:09 +0000409 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
drh22645842011-03-24 01:34:03 +0000410 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000411 if( pIndex->pTable->pIndex==pIndex ){
412 pIndex->pTable->pIndex = pIndex->pNext;
413 }else{
414 Index *p;
drh04491712009-05-13 17:21:13 +0000415 /* Justification of ALWAYS(); The index must be on the list of
416 ** indices. */
417 p = pIndex->pTable->pIndex;
418 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
419 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000420 p->pNext = pIndex->pNext;
421 }
drh5e00f6c2001-09-13 13:46:56 +0000422 }
dan1feeaed2010-07-23 15:41:47 +0000423 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000424 }
drh956bc922004-07-24 17:38:29 +0000425 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000426}
427
428/*
drh81028a42012-05-15 18:28:27 +0000429** Look through the list of open database files in db->aDb[] and if
430** any have been closed, remove them from the list. Reallocate the
431** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000432**
drh81028a42012-05-15 18:28:27 +0000433** Entry 0 (the "main" database) and entry 1 (the "temp" database)
434** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000435*/
drh81028a42012-05-15 18:28:27 +0000436void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000437 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000438 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000439 struct Db *pDb = &db->aDb[i];
440 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000441 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000442 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000443 continue;
444 }
445 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000446 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000447 }
drh8bf8dc92003-05-17 17:35:10 +0000448 j++;
drh1c2d8412003-03-31 00:30:47 +0000449 }
450 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
451 db->nDb = j;
452 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
453 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000454 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000455 db->aDb = db->aDbStatic;
456 }
drhe0bc4042002-06-25 01:09:11 +0000457}
458
459/*
drh81028a42012-05-15 18:28:27 +0000460** Reset the schema for the database at index iDb. Also reset the
461** TEMP schema.
462*/
463void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000464 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000465 assert( iDb<db->nDb );
466
467 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000468 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000469 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
470 assert( pDb->pSchema!=0 );
471 sqlite3SchemaClear(pDb->pSchema);
472
473 /* If any database other than TEMP is reset, then also reset TEMP
474 ** since TEMP might be holding triggers that reference tables in the
475 ** other database.
476 */
477 if( iDb!=1 ){
478 pDb = &db->aDb[1];
479 assert( pDb->pSchema!=0 );
480 sqlite3SchemaClear(pDb->pSchema);
481 }
482 return;
483}
484
485/*
486** Erase all schema information from all attached databases (including
487** "main" and "temp") for a single database connection.
488*/
489void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
490 int i;
491 sqlite3BtreeEnterAll(db);
492 for(i=0; i<db->nDb; i++){
493 Db *pDb = &db->aDb[i];
494 if( pDb->pSchema ){
495 sqlite3SchemaClear(pDb->pSchema);
496 }
497 }
498 db->flags &= ~SQLITE_InternChanges;
499 sqlite3VtabUnlockList(db);
500 sqlite3BtreeLeaveAll(db);
501 sqlite3CollapseDatabaseArray(db);
502}
503
504/*
drhe0bc4042002-06-25 01:09:11 +0000505** This routine is called when a commit occurs.
506*/
drh9bb575f2004-09-06 17:24:11 +0000507void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000508 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000509}
510
511/*
dand46def72010-07-24 11:28:28 +0000512** Delete memory allocated for the column names of a table or view (the
513** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000514*/
dand46def72010-07-24 11:28:28 +0000515static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000516 int i;
517 Column *pCol;
518 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000519 if( (pCol = pTable->aCol)!=0 ){
520 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000521 sqlite3DbFree(db, pCol->zName);
522 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000523 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000524 sqlite3DbFree(db, pCol->zType);
525 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000526 }
drh633e6d52008-07-28 19:34:53 +0000527 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000528 }
drh956bc922004-07-24 17:38:29 +0000529}
530
531/*
drh75897232000-05-29 14:26:00 +0000532** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000533** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000534**
535** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000536** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000537** memory structures of the indices and foreign keys associated with
538** the table.
drh29ddd3a2012-05-15 12:49:32 +0000539**
540** The db parameter is optional. It is needed if the Table object
541** contains lookaside memory. (Table objects in the schema do not use
542** lookaside memory, but some ephemeral Table objects do.) Or the
543** db parameter can be used with db->pnBytesFreed to measure the memory
544** used by the Table object.
drh75897232000-05-29 14:26:00 +0000545*/
dan1feeaed2010-07-23 15:41:47 +0000546void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000547 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000548 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000549
dand46def72010-07-24 11:28:28 +0000550 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000551
drhed8a3bb2005-06-06 21:19:56 +0000552 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000553 if( !pTable ) return;
554 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000555
drh29ddd3a2012-05-15 12:49:32 +0000556 /* Record the number of outstanding lookaside allocations in schema Tables
557 ** prior to doing any free() operations. Since schema Tables do not use
558 ** lookaside, this number should not change. */
559 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
560 db->lookaside.nOut : 0 );
561
dand46def72010-07-24 11:28:28 +0000562 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000563 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
564 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000565 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000566 if( !db || db->pnBytesFreed==0 ){
567 char *zName = pIndex->zName;
568 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhf2f105d2012-08-20 15:53:54 +0000569 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
dand46def72010-07-24 11:28:28 +0000570 );
drh21206082011-04-04 18:22:02 +0000571 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000572 assert( pOld==pIndex || pOld==0 );
573 }
574 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000575 }
576
dan1da40a32009-09-19 17:00:31 +0000577 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000578 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000579
580 /* Delete the Table structure itself.
581 */
dand46def72010-07-24 11:28:28 +0000582 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000583 sqlite3DbFree(db, pTable->zName);
584 sqlite3DbFree(db, pTable->zColAff);
585 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000586#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000587 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000588#endif
drh078e4082010-07-28 19:17:51 +0000589#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000590 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000591#endif
drh633e6d52008-07-28 19:34:53 +0000592 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000593
594 /* Verify that no lookaside memory was used by schema tables */
595 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000596}
597
598/*
drh5edc3122001-09-13 21:53:09 +0000599** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000600** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000601*/
drh9bb575f2004-09-06 17:24:11 +0000602void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000603 Table *p;
drh956bc922004-07-24 17:38:29 +0000604 Db *pDb;
605
drhd229ca92002-01-09 13:30:41 +0000606 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000607 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000608 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000609 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000610 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000611 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000612 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
drha83ccca2009-04-28 13:01:09 +0000613 sqlite3Strlen30(zTabName),0);
dan1feeaed2010-07-23 15:41:47 +0000614 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000615 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000616}
617
618/*
drha99db3b2004-06-19 14:49:12 +0000619** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000620** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000621** is obtained from sqliteMalloc() and must be freed by the calling
622** function.
drh75897232000-05-29 14:26:00 +0000623**
drh24fb6272009-05-01 21:13:36 +0000624** Any quotation marks (ex: "name", 'name', [name], or `name`) that
625** surround the body of the token are removed.
626**
drhc96d8532005-05-03 12:30:33 +0000627** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000628** are not \000 terminated and are not persistent. The returned string
629** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000630*/
drh17435752007-08-16 04:30:38 +0000631char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000632 char *zName;
633 if( pName ){
drh17435752007-08-16 04:30:38 +0000634 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000635 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000636 }else{
637 zName = 0;
638 }
drh75897232000-05-29 14:26:00 +0000639 return zName;
640}
641
642/*
danielk1977cbb18d22004-05-28 11:37:27 +0000643** Open the sqlite_master table stored in database number iDb for
644** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000645*/
danielk1977c00da102006-01-07 13:21:04 +0000646void sqlite3OpenMasterTable(Parse *p, int iDb){
647 Vdbe *v = sqlite3GetVdbe(p);
648 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000649 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000650 if( p->nTab==0 ){
651 p->nTab = 1;
652 }
drhe0bc4042002-06-25 01:09:11 +0000653}
654
655/*
danielk197704103022009-02-03 16:51:24 +0000656** Parameter zName points to a nul-terminated buffer containing the name
657** of a database ("main", "temp" or the name of an attached db). This
658** function returns the index of the named database in db->aDb[], or
659** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000660*/
danielk197704103022009-02-03 16:51:24 +0000661int sqlite3FindDbName(sqlite3 *db, const char *zName){
662 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000663 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000664 Db *pDb;
665 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000666 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000667 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000668 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000669 break;
drh73c42a12004-11-20 18:13:10 +0000670 }
danielk1977cbb18d22004-05-28 11:37:27 +0000671 }
672 }
danielk1977576ec6b2005-01-21 11:55:25 +0000673 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000674}
675
danielk197704103022009-02-03 16:51:24 +0000676/*
677** The token *pName contains the name of a database (either "main" or
678** "temp" or the name of an attached db). This routine returns the
679** index of the named database in db->aDb[], or -1 if the named db
680** does not exist.
681*/
682int sqlite3FindDb(sqlite3 *db, Token *pName){
683 int i; /* Database number */
684 char *zName; /* Name we are searching for */
685 zName = sqlite3NameFromToken(db, pName);
686 i = sqlite3FindDbName(db, zName);
687 sqlite3DbFree(db, zName);
688 return i;
689}
690
drh0e3d7472004-06-19 17:33:07 +0000691/* The table or view or trigger name is passed to this routine via tokens
692** pName1 and pName2. If the table name was fully qualified, for example:
693**
694** CREATE TABLE xxx.yyy (...);
695**
696** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
697** the table name is not fully qualified, i.e.:
698**
699** CREATE TABLE yyy(...);
700**
701** Then pName1 is set to "yyy" and pName2 is "".
702**
703** This routine sets the *ppUnqual pointer to point at the token (pName1 or
704** pName2) that stores the unqualified table name. The index of the
705** database "xxx" is returned.
706*/
danielk1977ef2cb632004-05-29 02:37:19 +0000707int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000708 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000709 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000710 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
711 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000712){
drh0e3d7472004-06-19 17:33:07 +0000713 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000714 sqlite3 *db = pParse->db;
715
drhc4a64fa2009-05-11 20:53:28 +0000716 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000717 if( db->init.busy ) {
718 sqlite3ErrorMsg(pParse, "corrupt database");
719 pParse->nErr++;
720 return -1;
721 }
danielk1977cbb18d22004-05-28 11:37:27 +0000722 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000723 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000724 if( iDb<0 ){
725 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
726 pParse->nErr++;
727 return -1;
728 }
729 }else{
730 assert( db->init.iDb==0 || db->init.busy );
731 iDb = db->init.iDb;
732 *pUnqual = pName1;
733 }
734 return iDb;
735}
736
737/*
danielk1977d8123362004-06-12 09:25:12 +0000738** This routine is used to check if the UTF-8 string zName is a legal
739** unqualified name for a new schema object (table, index, view or
740** trigger). All names are legal except those that begin with the string
741** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
742** is reserved for internal use.
743*/
744int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000745 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000746 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000747 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000748 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
749 return SQLITE_ERROR;
750 }
751 return SQLITE_OK;
752}
753
754/*
drh44156282013-10-23 22:23:03 +0000755** Return the PRIMARY KEY index of a table
756*/
757Index *sqlite3PrimaryKeyIndex(Table *pTab){
758 Index *p;
759 for(p=pTab->pIndex; p && p->autoIndex!=2; p=p->pNext){}
760 return p;
761}
762
763/*
764** Return the column of index pIdx that corresponds to table
765** column iCol. Return -1 if not found.
766*/
767i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
768 int i;
769 for(i=0; i<pIdx->nColumn; i++){
770 if( iCol==pIdx->aiColumn[i] ) return i;
771 }
772 return -1;
773}
774
775/*
drh75897232000-05-29 14:26:00 +0000776** Begin constructing a new table representation in memory. This is
777** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000778** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000779** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000780** flag is true if the table should be stored in the auxiliary database
781** file instead of in the main database file. This is normally the case
782** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000783** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000784**
drhf57b3392001-10-08 13:22:32 +0000785** The new table record is initialized and put in pParse->pNewTable.
786** As more of the CREATE TABLE statement is parsed, additional action
787** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000788** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000789** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000790*/
danielk19774adee202004-05-08 08:23:19 +0000791void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000792 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000793 Token *pName1, /* First part of the name of the table or view */
794 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000795 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000796 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000797 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000798 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000799){
drh75897232000-05-29 14:26:00 +0000800 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000801 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000802 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000803 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000804 int iDb; /* Database number to create the table in */
805 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000806
danielk1977cbb18d22004-05-28 11:37:27 +0000807 /* The table or view name to create is passed to this routine via tokens
808 ** pName1 and pName2. If the table name was fully qualified, for example:
809 **
810 ** CREATE TABLE xxx.yyy (...);
811 **
812 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
813 ** the table name is not fully qualified, i.e.:
814 **
815 ** CREATE TABLE yyy(...);
816 **
817 ** Then pName1 is set to "yyy" and pName2 is "".
818 **
819 ** The call below sets the pName pointer to point at the token (pName1 or
820 ** pName2) that stores the unqualified table name. The variable iDb is
821 ** set to the index of the database that the table or view is to be
822 ** created in.
823 */
danielk1977ef2cb632004-05-29 02:37:19 +0000824 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000825 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000826 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
827 /* If creating a temp table, the name may not be qualified. Unless
828 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000829 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000830 return;
831 }
danielk197753c0f742005-03-29 03:10:59 +0000832 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000833
834 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000835 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000836 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000837 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000838 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000839 }
drh1d85d932004-02-14 23:05:52 +0000840 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000841#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000842 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000843 {
844 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000845 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000846 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000847 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000848 }
drhe5f9c642003-01-13 23:27:31 +0000849 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000850 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000851 code = SQLITE_CREATE_TEMP_VIEW;
852 }else{
853 code = SQLITE_CREATE_VIEW;
854 }
855 }else{
danielk197753c0f742005-03-29 03:10:59 +0000856 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000857 code = SQLITE_CREATE_TEMP_TABLE;
858 }else{
859 code = SQLITE_CREATE_TABLE;
860 }
861 }
danielk1977f1a381e2006-06-16 08:01:02 +0000862 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000863 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000864 }
865 }
866#endif
drhf57b3392001-10-08 13:22:32 +0000867
drhf57b3392001-10-08 13:22:32 +0000868 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000869 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000870 ** it does. The exception is if the statement being parsed was passed
871 ** to an sqlite3_declare_vtab() call. In that case only the column names
872 ** and types will be used, so there is no need to test for namespace
873 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000874 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000875 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000876 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000877 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
878 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000879 }
dana16d1062010-09-28 17:37:28 +0000880 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000881 if( pTable ){
882 if( !noErr ){
883 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000884 }else{
885 assert( !db->init.busy );
886 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000887 }
888 goto begin_table_error;
889 }
drh8a8a0d12010-09-28 20:26:44 +0000890 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000891 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
892 goto begin_table_error;
893 }
drh75897232000-05-29 14:26:00 +0000894 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000895
danielk197726783a52007-08-29 14:06:22 +0000896 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000897 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000898 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000899 pParse->rc = SQLITE_NOMEM;
900 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000901 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000902 }
drh75897232000-05-29 14:26:00 +0000903 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000904 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000905 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000906 pTable->nRef = 1;
drh186ad8c2013-10-08 18:40:37 +0000907 pTable->nRowEst = 1048576;
drhc4a64fa2009-05-11 20:53:28 +0000908 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000909 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000910
drh4794f732004-11-05 17:17:50 +0000911 /* If this is the magic sqlite_sequence table used by autoincrement,
912 ** then record a pointer to this table in the main database structure
913 ** so that INSERT can find the table easily.
914 */
915#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000916 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000917 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000918 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000919 }
920#endif
921
drh17f71932002-02-21 12:01:27 +0000922 /* Begin generating the code that will insert the table record into
923 ** the SQLITE_MASTER table. Note in particular that we must go ahead
924 ** and allocate the record number for the table entry now. Before any
925 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
926 ** indices to be created and the table record must come before the
927 ** indices. Hence, the record number for the table must be allocated
928 ** now.
929 */
danielk19774adee202004-05-08 08:23:19 +0000930 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000931 int j1;
drhe321c292006-01-12 01:56:43 +0000932 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000933 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000934 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000935
danielk197720b1eaf2006-07-26 16:22:14 +0000936#ifndef SQLITE_OMIT_VIRTUALTABLE
937 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000938 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000939 }
940#endif
941
danielk197736963fd2005-02-19 08:18:05 +0000942 /* If the file format and encoding in the database have not been set,
943 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000944 */
drhb7654112008-01-12 12:48:07 +0000945 reg1 = pParse->regRowid = ++pParse->nMem;
946 reg2 = pParse->regRoot = ++pParse->nMem;
947 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000948 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000949 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000950 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000951 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000952 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000953 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000954 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000955 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000956 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000957 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000958
drh4794f732004-11-05 17:17:50 +0000959 /* This just creates a place-holder record in the sqlite_master table.
960 ** The record created does not contain anything yet. It will be replaced
961 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000962 **
drh0fa991b2009-03-21 16:19:26 +0000963 ** The rowid for the new entry is left in register pParse->regRowid.
964 ** The root page number of the new table is left in reg pParse->regRoot.
965 ** The rowid and root page number values are needed by the code that
966 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000967 */
danielk1977f1a381e2006-06-16 08:01:02 +0000968#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
969 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000970 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000971 }else
972#endif
973 {
drh8a120f82013-11-01 17:59:53 +0000974 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000975 }
danielk1977c00da102006-01-07 13:21:04 +0000976 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000977 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
978 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
979 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
980 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000981 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000982 }
drh23bf66d2004-12-14 03:34:34 +0000983
984 /* Normal (non-error) return. */
985 return;
986
987 /* If an error occurs, we jump here */
988begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000989 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000990 return;
drh75897232000-05-29 14:26:00 +0000991}
992
993/*
danielk1977c60e9b82005-01-31 12:42:29 +0000994** This macro is used to compare two strings in a case-insensitive manner.
995** It is slightly faster than calling sqlite3StrICmp() directly, but
996** produces larger code.
997**
998** WARNING: This macro is not compatible with the strcmp() family. It
999** returns true if the two strings are equal, otherwise false.
1000*/
1001#define STRICMP(x, y) (\
1002sqlite3UpperToLower[*(unsigned char *)(x)]== \
1003sqlite3UpperToLower[*(unsigned char *)(y)] \
1004&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1005
1006/*
drh75897232000-05-29 14:26:00 +00001007** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001008**
1009** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001010** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001011** first to get things going. Then this routine is called for each
1012** column.
drh75897232000-05-29 14:26:00 +00001013*/
danielk19774adee202004-05-08 08:23:19 +00001014void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001015 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001016 int i;
drha99db3b2004-06-19 14:49:12 +00001017 char *z;
drhc9b84a12002-06-20 11:36:48 +00001018 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001019 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001020 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001021#if SQLITE_MAX_COLUMN
1022 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001023 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1024 return;
1025 }
drhbb4957f2008-03-20 14:03:29 +00001026#endif
danielk1977ae74e032008-12-23 11:11:51 +00001027 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001028 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001029 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001030 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001031 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001032 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001033 return;
1034 }
1035 }
drh75897232000-05-29 14:26:00 +00001036 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001037 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001038 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001039 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001040 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001041 return;
1042 }
drh6d4abfb2001-10-22 02:58:08 +00001043 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001044 }
drhc9b84a12002-06-20 11:36:48 +00001045 pCol = &p->aCol[p->nCol];
1046 memset(pCol, 0, sizeof(p->aCol[0]));
1047 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001048
1049 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001050 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1051 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001052 */
danielk19774f057f92004-06-08 00:02:33 +00001053 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001054 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001055 p->nCol++;
drh75897232000-05-29 14:26:00 +00001056}
1057
1058/*
drh382c0242001-10-06 16:33:02 +00001059** This routine is called by the parser while in the middle of
1060** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1061** been seen on a column. This routine sets the notNull flag on
1062** the column currently under construction.
1063*/
danielk19774adee202004-05-08 08:23:19 +00001064void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001065 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001066 p = pParse->pNewTable;
1067 if( p==0 || NEVER(p->nCol<1) ) return;
1068 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001069}
1070
1071/*
danielk197752a83fb2005-01-31 12:56:44 +00001072** Scan the column type name zType (length nType) and return the
1073** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001074**
1075** This routine does a case-independent search of zType for the
1076** substrings in the following table. If one of the substrings is
1077** found, the corresponding affinity is returned. If zType contains
1078** more than one of the substrings, entries toward the top of
1079** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001080** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001081**
1082** Substring | Affinity
1083** --------------------------------
1084** 'INT' | SQLITE_AFF_INTEGER
1085** 'CHAR' | SQLITE_AFF_TEXT
1086** 'CLOB' | SQLITE_AFF_TEXT
1087** 'TEXT' | SQLITE_AFF_TEXT
1088** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001089** 'REAL' | SQLITE_AFF_REAL
1090** 'FLOA' | SQLITE_AFF_REAL
1091** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001092**
1093** If none of the substrings in the above table are found,
1094** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001095*/
drhfdaac672013-10-04 15:30:21 +00001096char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001097 u32 h = 0;
1098 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001099 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001100
drhfdaac672013-10-04 15:30:21 +00001101 if( zIn==0 ) return aff;
1102 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001103 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001104 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001105 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001106 aff = SQLITE_AFF_TEXT;
1107 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001108 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1109 aff = SQLITE_AFF_TEXT;
1110 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1111 aff = SQLITE_AFF_TEXT;
1112 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001113 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001114 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001115 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001116#ifndef SQLITE_OMIT_FLOATING_POINT
1117 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1118 && aff==SQLITE_AFF_NUMERIC ){
1119 aff = SQLITE_AFF_REAL;
1120 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1121 && aff==SQLITE_AFF_NUMERIC ){
1122 aff = SQLITE_AFF_REAL;
1123 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1124 && aff==SQLITE_AFF_NUMERIC ){
1125 aff = SQLITE_AFF_REAL;
1126#endif
danielk1977201f7162005-02-01 02:13:29 +00001127 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001128 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001129 break;
danielk197752a83fb2005-01-31 12:56:44 +00001130 }
1131 }
drhd3037a42013-10-04 18:29:25 +00001132
1133 /* If pszEst is not NULL, store an estimate of the field size. The
1134 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001135 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001136 *pszEst = 1; /* default size is approx 4 bytes */
1137 if( aff<=SQLITE_AFF_NONE ){
1138 if( zChar ){
1139 while( zChar[0] ){
1140 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001141 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001142 sqlite3GetInt32(zChar, &v);
1143 v = v/4 + 1;
1144 if( v>255 ) v = 255;
1145 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1146 break;
1147 }
1148 zChar++;
drhfdaac672013-10-04 15:30:21 +00001149 }
drhd3037a42013-10-04 18:29:25 +00001150 }else{
1151 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001152 }
drhfdaac672013-10-04 15:30:21 +00001153 }
1154 }
danielk1977b3dff962005-02-01 01:21:55 +00001155 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001156}
1157
1158/*
drh382c0242001-10-06 16:33:02 +00001159** This routine is called by the parser while in the middle of
1160** parsing a CREATE TABLE statement. The pFirst token is the first
1161** token in the sequence of tokens that describe the type of the
1162** column currently under construction. pLast is the last token
1163** in the sequence. Use this information to construct a string
1164** that contains the typename of the column and store that string
1165** in zType.
1166*/
drh487e2622005-06-25 18:42:14 +00001167void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001168 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001169 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001170
drhc4a64fa2009-05-11 20:53:28 +00001171 p = pParse->pNewTable;
1172 if( p==0 || NEVER(p->nCol<1) ) return;
1173 pCol = &p->aCol[p->nCol-1];
1174 assert( pCol->zType==0 );
1175 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001176 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001177}
1178
1179/*
danielk19777977a172004-11-09 12:44:37 +00001180** The expression is the default value for the most recently added column
1181** of the table currently under construction.
1182**
1183** Default value expressions must be constant. Raise an exception if this
1184** is not the case.
drhd9b02572001-04-15 00:37:09 +00001185**
1186** This routine is called by the parser while in the middle of
1187** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001188*/
drhb7916a72009-05-27 10:31:29 +00001189void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001190 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001191 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001192 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001193 p = pParse->pNewTable;
1194 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001195 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001196 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001197 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1198 pCol->zName);
1199 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001200 /* A copy of pExpr is used instead of the original, as pExpr contains
1201 ** tokens that point to volatile memory. The 'span' of the expression
1202 ** is required by pragma table_info.
1203 */
drh633e6d52008-07-28 19:34:53 +00001204 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001205 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1206 sqlite3DbFree(db, pCol->zDflt);
1207 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001208 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001209 }
danielk19777977a172004-11-09 12:44:37 +00001210 }
drhb7916a72009-05-27 10:31:29 +00001211 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001212}
1213
1214/*
drh4a324312001-12-21 14:30:42 +00001215** Designate the PRIMARY KEY for the table. pList is a list of names
1216** of columns that form the primary key. If pList is NULL, then the
1217** most recently added column of the table is the primary key.
1218**
1219** A table can have at most one primary key. If the table already has
1220** a primary key (and this is the second primary key) then create an
1221** error.
1222**
1223** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001224** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001225** field of the table under construction to be the index of the
1226** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1227** no INTEGER PRIMARY KEY.
1228**
1229** If the key is not an INTEGER PRIMARY KEY, then create a unique
1230** index for the key. No index is created for INTEGER PRIMARY KEYs.
1231*/
drh205f48e2004-11-05 00:43:11 +00001232void sqlite3AddPrimaryKey(
1233 Parse *pParse, /* Parsing context */
1234 ExprList *pList, /* List of field names to be indexed */
1235 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001236 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1237 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001238){
drh4a324312001-12-21 14:30:42 +00001239 Table *pTab = pParse->pNewTable;
1240 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001241 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001242 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001243 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001244 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001245 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001246 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001247 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001248 }
drh7d10d5a2008-08-20 16:35:10 +00001249 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001250 if( pList==0 ){
1251 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001252 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001253 zType = pTab->aCol[iCol].zType;
1254 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001255 }else{
drh8ea30bf2013-10-22 01:18:17 +00001256 nTerm = pList->nExpr;
1257 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001258 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001259 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001260 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1261 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001262 break;
1263 }
drh78100cc2003-08-23 22:40:53 +00001264 }
drh4a324312001-12-21 14:30:42 +00001265 }
1266 }
drh8ea30bf2013-10-22 01:18:17 +00001267 if( nTerm==1
1268 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1269 && sortOrder==SQLITE_SO_ASC
1270 ){
drh4a324312001-12-21 14:30:42 +00001271 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001272 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001273 assert( autoInc==0 || autoInc==1 );
1274 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001275 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001276 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001277#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001278 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1279 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001280#endif
drh4a324312001-12-21 14:30:42 +00001281 }else{
drhc6bd4e42013-11-02 14:37:18 +00001282 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001283 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001284 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001285 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001286 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001287 if( p ){
1288 p->autoIndex = 2;
drhc6bd4e42013-11-02 14:37:18 +00001289 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001290 }
drhe0194f22003-02-26 13:52:51 +00001291 pList = 0;
drh4a324312001-12-21 14:30:42 +00001292 }
drhe0194f22003-02-26 13:52:51 +00001293
1294primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001295 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001296 return;
drh4a324312001-12-21 14:30:42 +00001297}
1298
1299/*
drhffe07b22005-11-03 00:41:17 +00001300** Add a new CHECK constraint to the table currently under construction.
1301*/
1302void sqlite3AddCheckConstraint(
1303 Parse *pParse, /* Parsing context */
1304 Expr *pCheckExpr /* The check expression */
1305){
1306#ifndef SQLITE_OMIT_CHECK
1307 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001308 if( pTab && !IN_DECLARE_VTAB ){
drh2938f922012-03-07 19:13:29 +00001309 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1310 if( pParse->constraintName.n ){
1311 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1312 }
drh33e619f2009-05-28 01:00:55 +00001313 }else
drhffe07b22005-11-03 00:41:17 +00001314#endif
drh33e619f2009-05-28 01:00:55 +00001315 {
drh2938f922012-03-07 19:13:29 +00001316 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001317 }
drhffe07b22005-11-03 00:41:17 +00001318}
1319
1320/*
drhd3d39e92004-05-20 22:16:29 +00001321** Set the collation function of the most recently parsed table column
1322** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001323*/
danielk197739002502007-11-12 09:50:26 +00001324void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001325 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001326 int i;
danielk197739002502007-11-12 09:50:26 +00001327 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001328 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001329
danielk1977b8cbb872006-06-19 05:33:45 +00001330 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001331 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001332 db = pParse->db;
1333 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001334 if( !zColl ) return;
1335
drhc4a64fa2009-05-11 20:53:28 +00001336 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001337 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001338 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001339 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001340
1341 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1342 ** then an index may have been created on this column before the
1343 ** collation type was added. Correct this if it is the case.
1344 */
1345 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001346 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001347 if( pIdx->aiColumn[0]==i ){
1348 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001349 }
1350 }
danielk197739002502007-11-12 09:50:26 +00001351 }else{
drh633e6d52008-07-28 19:34:53 +00001352 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001353 }
danielk19777cedc8d2004-06-10 10:50:08 +00001354}
1355
danielk1977466be562004-06-10 02:16:01 +00001356/*
1357** This function returns the collation sequence for database native text
1358** encoding identified by the string zName, length nName.
1359**
1360** If the requested collation sequence is not available, or not available
1361** in the database native encoding, the collation factory is invoked to
1362** request it. If the collation factory does not supply such a sequence,
1363** and the sequence is available in another text encoding, then that is
1364** returned instead.
1365**
1366** If no versions of the requested collations sequence are available, or
1367** another error occurs, NULL is returned and an error message written into
1368** pParse.
drha34001c2007-02-02 12:44:37 +00001369**
1370** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1371** invokes the collation factory if the named collation cannot be found
1372** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001373**
1374** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001375*/
drhc4a64fa2009-05-11 20:53:28 +00001376CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001377 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001378 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001379 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001380 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001381
drhc4a64fa2009-05-11 20:53:28 +00001382 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001383 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001384 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001385 }
1386
danielk19770202b292004-06-09 09:55:16 +00001387 return pColl;
1388}
1389
1390
drh8e2ca022002-06-17 17:07:19 +00001391/*
drh3f7d4e42004-07-24 14:35:58 +00001392** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001393**
1394** The schema cookie is used to determine when the schema for the
1395** database changes. After each schema change, the cookie value
1396** changes. When a process first reads the schema it records the
1397** cookie. Thereafter, whenever it goes to access the database,
1398** it checks the cookie to make sure the schema has not changed
1399** since it was last read.
1400**
1401** This plan is not completely bullet-proof. It is possible for
1402** the schema to change multiple times and for the cookie to be
1403** set back to prior value. But schema changes are infrequent
1404** and the probability of hitting the same cookie value is only
1405** 1 chance in 2^32. So we're safe enough.
1406*/
drh9cbf3422008-01-17 16:22:13 +00001407void sqlite3ChangeCookie(Parse *pParse, int iDb){
1408 int r1 = sqlite3GetTempReg(pParse);
1409 sqlite3 *db = pParse->db;
1410 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001411 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001412 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001413 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001414 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001415}
1416
1417/*
drh969fa7c2002-02-18 18:30:32 +00001418** Measure the number of characters needed to output the given
1419** identifier. The number returned includes any quotes used
1420** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001421**
1422** The estimate is conservative. It might be larger that what is
1423** really needed.
drh969fa7c2002-02-18 18:30:32 +00001424*/
1425static int identLength(const char *z){
1426 int n;
drh17f71932002-02-21 12:01:27 +00001427 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001428 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001429 }
drh234c39d2004-07-24 03:30:47 +00001430 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001431}
1432
1433/*
danielk19771b870de2009-03-14 08:37:23 +00001434** The first parameter is a pointer to an output buffer. The second
1435** parameter is a pointer to an integer that contains the offset at
1436** which to write into the output buffer. This function copies the
1437** nul-terminated string pointed to by the third parameter, zSignedIdent,
1438** to the specified offset in the buffer and updates *pIdx to refer
1439** to the first byte after the last byte written before returning.
1440**
1441** If the string zSignedIdent consists entirely of alpha-numeric
1442** characters, does not begin with a digit and is not an SQL keyword,
1443** then it is copied to the output buffer exactly as it is. Otherwise,
1444** it is quoted using double-quotes.
1445*/
drhc4a64fa2009-05-11 20:53:28 +00001446static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001447 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001448 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001449 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001450
drh17f71932002-02-21 12:01:27 +00001451 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001452 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001453 }
danielk19771b870de2009-03-14 08:37:23 +00001454 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1455 if( !needQuote ){
drhc4a64fa2009-05-11 20:53:28 +00001456 needQuote = zIdent[j];
danielk19771b870de2009-03-14 08:37:23 +00001457 }
1458
drh234c39d2004-07-24 03:30:47 +00001459 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001460 for(j=0; zIdent[j]; j++){
1461 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001462 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001463 }
drh234c39d2004-07-24 03:30:47 +00001464 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001465 z[i] = 0;
1466 *pIdx = i;
1467}
1468
1469/*
1470** Generate a CREATE TABLE statement appropriate for the given
1471** table. Memory to hold the text of the statement is obtained
1472** from sqliteMalloc() and must be freed by the calling function.
1473*/
drh1d34fde2009-02-03 15:50:33 +00001474static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001475 int i, k, n;
1476 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001477 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001478 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001479 n = 0;
drh234c39d2004-07-24 03:30:47 +00001480 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001481 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001482 }
1483 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001484 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001485 zSep = "";
1486 zSep2 = ",";
1487 zEnd = ")";
1488 }else{
1489 zSep = "\n ";
1490 zSep2 = ",\n ";
1491 zEnd = "\n)";
1492 }
drhe0bc4042002-06-25 01:09:11 +00001493 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001494 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001495 if( zStmt==0 ){
1496 db->mallocFailed = 1;
1497 return 0;
1498 }
drhbdb339f2009-02-02 18:03:21 +00001499 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001500 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001501 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001502 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001503 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001504 static const char * const azType[] = {
1505 /* SQLITE_AFF_TEXT */ " TEXT",
1506 /* SQLITE_AFF_NONE */ "",
1507 /* SQLITE_AFF_NUMERIC */ " NUM",
1508 /* SQLITE_AFF_INTEGER */ " INT",
1509 /* SQLITE_AFF_REAL */ " REAL"
1510 };
1511 int len;
1512 const char *zType;
1513
drh5bb3eb92007-05-04 13:15:55 +00001514 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001515 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001516 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001517 identPut(zStmt, &k, pCol->zName);
1518 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001519 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001520 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1521 testcase( pCol->affinity==SQLITE_AFF_NONE );
1522 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1523 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1524 testcase( pCol->affinity==SQLITE_AFF_REAL );
1525
1526 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1527 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001528 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001529 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001530 memcpy(&zStmt[k], zType, len);
1531 k += len;
1532 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001533 }
drh5bb3eb92007-05-04 13:15:55 +00001534 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001535 return zStmt;
1536}
1537
1538/*
drh7f9c5db2013-10-23 00:32:58 +00001539** Resize an Index object to hold N columns total. Return SQLITE_OK
1540** on success and SQLITE_NOMEM on an OOM error.
1541*/
1542static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1543 char *zExtra;
1544 int nByte;
1545 if( pIdx->nColumn>=N ) return SQLITE_OK;
1546 assert( pIdx->isResized==0 );
1547 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1548 zExtra = sqlite3DbMallocZero(db, nByte);
1549 if( zExtra==0 ) return SQLITE_NOMEM;
1550 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1551 pIdx->azColl = (char**)zExtra;
1552 zExtra += sizeof(char*)*N;
1553 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1554 pIdx->aiColumn = (i16*)zExtra;
1555 zExtra += sizeof(i16)*N;
1556 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1557 pIdx->aSortOrder = (u8*)zExtra;
1558 pIdx->nColumn = N;
1559 pIdx->isResized = 1;
1560 return SQLITE_OK;
1561}
1562
1563/*
drhfdaac672013-10-04 15:30:21 +00001564** Estimate the total row width for a table.
1565*/
drhe13e9f52013-10-05 19:18:00 +00001566static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001567 unsigned wTable = 0;
1568 const Column *pTabCol;
1569 int i;
1570 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1571 wTable += pTabCol->szEst;
1572 }
1573 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001574 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001575}
1576
1577/*
drhe13e9f52013-10-05 19:18:00 +00001578** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001579*/
drhe13e9f52013-10-05 19:18:00 +00001580static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001581 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001582 int i;
1583 const Column *aCol = pIdx->pTable->aCol;
1584 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001585 i16 x = pIdx->aiColumn[i];
1586 assert( x<pIdx->pTable->nCol );
1587 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001588 }
drhe13e9f52013-10-05 19:18:00 +00001589 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001590}
1591
drh7f9c5db2013-10-23 00:32:58 +00001592/* Return true if value x is found any of the first nCol entries of aiCol[]
1593*/
1594static int hasColumn(const i16 *aiCol, int nCol, int x){
1595 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1596 return 0;
1597}
1598
1599/*
drhc6bd4e42013-11-02 14:37:18 +00001600** This routine runs at the end of parsing a CREATE TABLE statement that
1601** has a WITHOUT ROWID clause. The job of this routine is to convert both
1602** internal schema data structures and the generated VDBE code so that they
1603** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1604** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001605**
drhc6bd4e42013-11-02 14:37:18 +00001606** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1607** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1608** data storage is a covering index btree.
1609** (2) Bypass the creation of the sqlite_master table entry
1610** for the PRIMARY KEY as the the primary key index is now
1611** identified by the sqlite_master table entry of the table itself.
1612** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1613** schema to the rootpage from the main table.
1614** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1615** (5) Add all table columns to the PRIMARY KEY Index object
1616** so that the PRIMARY KEY is a covering index. The surplus
1617** columns are part of KeyInfo.nXField and are not used for
1618** sorting or lookup or uniqueness checks.
1619** (6) Replace the rowid tail on all automatically generated UNIQUE
1620** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001621*/
1622static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1623 Index *pIdx;
1624 Index *pPk;
1625 int nPk;
1626 int i, j;
1627 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001628 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001629
1630 /* Convert the OP_CreateTable opcode that would normally create the
drhc6bd4e42013-11-02 14:37:18 +00001631 ** root-page for the table into a OP_CreateIndex opcode. The index
1632 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001633 */
1634 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001635 assert( v );
1636 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1637 }
1638
1639 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1640 ** table entry.
1641 */
1642 if( pParse->addrSkipPK ){
1643 assert( v );
1644 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001645 }
1646
1647 /* Locate the PRIMARY KEY index. Or, if this table was originally
1648 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1649 */
1650 if( pTab->iPKey>=0 ){
1651 ExprList *pList;
1652 pList = sqlite3ExprListAppend(pParse, 0, 0);
1653 if( pList==0 ) return;
1654 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1655 pTab->aCol[pTab->iPKey].zName);
1656 pList->a[0].sortOrder = pParse->iPkSortOrder;
1657 assert( pParse->pNewTable==pTab );
1658 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1659 if( pPk==0 ) return;
drh63f0eed2013-11-02 22:09:48 +00001660 pPk->autoIndex = 2;
drh7f9c5db2013-10-23 00:32:58 +00001661 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001662 }else{
1663 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001664 }
drh12826092013-11-05 22:39:17 +00001665 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001666 assert( pPk!=0 );
1667 nPk = pPk->nKeyCol;
1668
drhec95c442013-10-23 01:57:32 +00001669 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1670 for(i=0; i<nPk; i++){
1671 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1672 }
drh9eade082013-10-24 14:16:10 +00001673 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001674
drhc6bd4e42013-11-02 14:37:18 +00001675 /* The root page of the PRIMARY KEY is the table root page */
1676 pPk->tnum = pTab->tnum;
1677
drh7f9c5db2013-10-23 00:32:58 +00001678 /* Update the in-memory representation of all UNIQUE indices by converting
1679 ** the final rowid column into one or more columns of the PRIMARY KEY.
1680 */
1681 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1682 int n;
1683 if( pIdx->autoIndex==2 ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001684 for(i=n=0; i<nPk; i++){
1685 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1686 }
drh5a9a37b2013-11-05 17:30:04 +00001687 if( n==0 ){
1688 /* This index is a superset of the primary key */
1689 pIdx->nColumn = pIdx->nKeyCol;
1690 continue;
1691 }
drh7f9c5db2013-10-23 00:32:58 +00001692 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1693 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001694 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001695 pIdx->aiColumn[j] = pPk->aiColumn[i];
1696 pIdx->azColl[j] = pPk->azColl[i];
1697 j++;
1698 }
1699 }
drh00012df2013-11-05 01:59:07 +00001700 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1701 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001702 }
1703
1704 /* Add all table columns to the PRIMARY KEY index
1705 */
1706 if( nPk<pTab->nCol ){
1707 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1708 for(i=0, j=nPk; i<pTab->nCol; i++){
1709 if( !hasColumn(pPk->aiColumn, j, i) ){
1710 assert( j<pPk->nColumn );
1711 pPk->aiColumn[j] = i;
1712 pPk->azColl[j] = "BINARY";
1713 j++;
1714 }
1715 }
1716 assert( pPk->nColumn==j );
1717 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001718 }else{
1719 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001720 }
1721}
1722
drhfdaac672013-10-04 15:30:21 +00001723/*
drh75897232000-05-29 14:26:00 +00001724** This routine is called to report the final ")" that terminates
1725** a CREATE TABLE statement.
1726**
drhf57b3392001-10-08 13:22:32 +00001727** The table structure that other action routines have been building
1728** is added to the internal hash tables, assuming no errors have
1729** occurred.
drh75897232000-05-29 14:26:00 +00001730**
drh1d85d932004-02-14 23:05:52 +00001731** An entry for the table is made in the master table on disk, unless
1732** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001733** it means we are reading the sqlite_master table because we just
1734** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001735** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001736** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001737**
1738** If the pSelect argument is not NULL, it means that this routine
1739** was called to create a table generated from a
1740** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1741** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001742*/
danielk197719a8e7e2005-03-17 05:03:38 +00001743void sqlite3EndTable(
1744 Parse *pParse, /* Parse context */
1745 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001746 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1747 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001748 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1749){
drhfdaac672013-10-04 15:30:21 +00001750 Table *p; /* The new table */
1751 sqlite3 *db = pParse->db; /* The database connection */
1752 int iDb; /* Database in which the table lives */
1753 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001754
drh5969da42013-10-21 02:14:45 +00001755 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1756 return;
danielk1977261919c2005-12-06 12:52:59 +00001757 }
drh28037572000-08-02 13:47:41 +00001758 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001759 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001760
danielk1977517eb642004-06-07 10:00:31 +00001761 assert( !db->init.busy || !pSelect );
1762
drhc6bd4e42013-11-02 14:37:18 +00001763 /* If the db->init.busy is 1 it means we are reading the SQL off the
1764 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1765 ** So do not write to the disk again. Extract the root page number
1766 ** for the table from the db->init.newTnum field. (The page number
1767 ** should have been put there by the sqliteOpenCb routine.)
1768 */
1769 if( db->init.busy ){
1770 p->tnum = db->init.newTnum;
1771 }
1772
1773 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001774 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001775 if( (p->tabFlags & TF_Autoincrement) ){
1776 sqlite3ErrorMsg(pParse,
1777 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1778 return;
1779 }
drh5969da42013-10-21 02:14:45 +00001780 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001781 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001782 }else{
1783 p->tabFlags |= TF_WithoutRowid;
1784 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001785 }
1786 }
1787
drhb9bb7c12006-06-11 23:41:55 +00001788 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001789
drhffe07b22005-11-03 00:41:17 +00001790#ifndef SQLITE_OMIT_CHECK
1791 /* Resolve names in all CHECK constraint expressions.
1792 */
1793 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001794 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001795 }
1796#endif /* !defined(SQLITE_OMIT_CHECK) */
1797
drhe13e9f52013-10-05 19:18:00 +00001798 /* Estimate the average row size for the table and for all implied indices */
1799 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001800 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001801 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001802 }
1803
drhe3c41372001-09-17 20:25:58 +00001804 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001805 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001806 **
drhe0bc4042002-06-25 01:09:11 +00001807 ** If this is a TEMPORARY table, write the entry into the auxiliary
1808 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001809 */
drh1d85d932004-02-14 23:05:52 +00001810 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001811 int n;
drhd8bc7082000-06-07 23:51:50 +00001812 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001813 char *zType; /* "view" or "table" */
1814 char *zType2; /* "VIEW" or "TABLE" */
1815 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001816
danielk19774adee202004-05-08 08:23:19 +00001817 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001818 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001819
drh66a51672008-01-03 00:01:23 +00001820 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001821
drh0fa991b2009-03-21 16:19:26 +00001822 /*
1823 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001824 */
drh4ff6dfa2002-03-03 23:06:00 +00001825 if( p->pSelect==0 ){
1826 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001827 zType = "table";
1828 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001829#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001830 }else{
1831 /* A view */
drh4794f732004-11-05 17:17:50 +00001832 zType = "view";
1833 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001834#endif
drh4ff6dfa2002-03-03 23:06:00 +00001835 }
danielk1977517eb642004-06-07 10:00:31 +00001836
danielk1977517eb642004-06-07 10:00:31 +00001837 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1838 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001839 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001840 **
1841 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1842 ** suitable state to query for the column names and types to be used
1843 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001844 **
1845 ** A shared-cache write-lock is not required to write to the new table,
1846 ** as a schema-lock must have already been obtained to create it. Since
1847 ** a schema-lock excludes all other database users, the write-lock would
1848 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001849 */
1850 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001851 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001852 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001853
danielk19776ab3a2e2009-02-19 14:39:25 +00001854 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001855 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001856 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001857 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001858 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001859 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001860 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001861 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001862 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001863 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001864 assert( p->aCol==0 );
1865 p->nCol = pSelTab->nCol;
1866 p->aCol = pSelTab->aCol;
1867 pSelTab->nCol = 0;
1868 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001869 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001870 }
1871 }
drh4794f732004-11-05 17:17:50 +00001872
drh4794f732004-11-05 17:17:50 +00001873 /* Compute the complete text of the CREATE statement */
1874 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001875 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001876 }else{
drh8ea30bf2013-10-22 01:18:17 +00001877 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1878 n = (int)(pEnd2->z - pParse->sNameToken.z);
1879 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001880 zStmt = sqlite3MPrintf(db,
1881 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1882 );
drh4794f732004-11-05 17:17:50 +00001883 }
1884
1885 /* A slot for the record has already been allocated in the
1886 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001887 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001888 */
1889 sqlite3NestedParse(pParse,
1890 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001891 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1892 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001893 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001894 zType,
1895 p->zName,
1896 p->zName,
drhb7654112008-01-12 12:48:07 +00001897 pParse->regRoot,
1898 zStmt,
1899 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001900 );
drh633e6d52008-07-28 19:34:53 +00001901 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001902 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001903
1904#ifndef SQLITE_OMIT_AUTOINCREMENT
1905 /* Check to see if we need to create an sqlite_sequence table for
1906 ** keeping track of autoincrement keys.
1907 */
drh7d10d5a2008-08-20 16:35:10 +00001908 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001909 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001910 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001911 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001912 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001913 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1914 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001915 );
1916 }
1917 }
1918#endif
drh4794f732004-11-05 17:17:50 +00001919
1920 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001921 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001922 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001923 }
drh17e9e292003-02-01 13:53:28 +00001924
drh2958a4e2004-11-12 03:56:15 +00001925
drh17e9e292003-02-01 13:53:28 +00001926 /* Add the table to the in-memory representation of the database.
1927 */
drh8af73d42009-05-13 22:58:28 +00001928 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001929 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001930 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001931 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhea678832008-12-10 19:26:22 +00001932 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
drha83ccca2009-04-28 13:01:09 +00001933 sqlite3Strlen30(p->zName),p);
drh17e9e292003-02-01 13:53:28 +00001934 if( pOld ){
1935 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001936 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001937 return;
drh17e9e292003-02-01 13:53:28 +00001938 }
drh17e9e292003-02-01 13:53:28 +00001939 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001940 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001941
1942#ifndef SQLITE_OMIT_ALTERTABLE
1943 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001944 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001945 int nName;
drh5969da42013-10-21 02:14:45 +00001946 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001947 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00001948 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00001949 }
drh1bd10f82008-12-10 21:19:56 +00001950 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001951 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001952 }
1953#endif
drh17e9e292003-02-01 13:53:28 +00001954 }
drh75897232000-05-29 14:26:00 +00001955}
1956
drhb7f91642004-10-31 02:22:47 +00001957#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001958/*
drha76b5df2002-02-23 02:32:10 +00001959** The parser calls this routine in order to create a new VIEW
1960*/
danielk19774adee202004-05-08 08:23:19 +00001961void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001962 Parse *pParse, /* The parsing context */
1963 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001964 Token *pName1, /* The token that holds the name of the view */
1965 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001966 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001967 int isTemp, /* TRUE for a TEMPORARY view */
1968 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001969){
drha76b5df2002-02-23 02:32:10 +00001970 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001971 int n;
drhb7916a72009-05-27 10:31:29 +00001972 const char *z;
drh4b59ab52002-08-24 18:24:51 +00001973 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001974 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00001975 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00001976 int iDb;
drh17435752007-08-16 04:30:38 +00001977 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001978
drh7c3d64f2005-06-06 15:32:08 +00001979 if( pParse->nVar>0 ){
1980 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001981 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001982 return;
1983 }
drhfdd48a72006-09-11 23:45:48 +00001984 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001985 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00001986 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001987 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001988 return;
1989 }
danielk1977ef2cb632004-05-29 02:37:19 +00001990 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001991 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00001992 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
1993 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00001994 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001995 return;
1996 }
drh174b6192002-12-03 02:22:52 +00001997
drh4b59ab52002-08-24 18:24:51 +00001998 /* Make a copy of the entire SELECT statement that defines the view.
1999 ** This will force all the Expr.token.z values to be dynamically
2000 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002001 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002002 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002003 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002004 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002005 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002006 return;
2007 }
drh17435752007-08-16 04:30:38 +00002008 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002009 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002010 }
drh4b59ab52002-08-24 18:24:51 +00002011
2012 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2013 ** the end.
2014 */
drha76b5df2002-02-23 02:32:10 +00002015 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002016 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002017 sEnd.z += sEnd.n;
2018 }
2019 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002020 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002021 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002022 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002023 sEnd.z = &z[n-1];
2024 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002025
danielk19774adee202004-05-08 08:23:19 +00002026 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002027 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002028 return;
drh417be792002-03-03 18:59:40 +00002029}
drhb7f91642004-10-31 02:22:47 +00002030#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002031
danielk1977fe3fcbe22006-06-12 12:08:45 +00002032#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002033/*
2034** The Table structure pTable is really a VIEW. Fill in the names of
2035** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002036** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002037*/
danielk19774adee202004-05-08 08:23:19 +00002038int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002039 Table *pSelTab; /* A fake table from which we get the result set */
2040 Select *pSel; /* Copy of the SELECT that implements the view */
2041 int nErr = 0; /* Number of errors encountered */
2042 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002043 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00002044 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00002045
2046 assert( pTable );
2047
danielk1977fe3fcbe22006-06-12 12:08:45 +00002048#ifndef SQLITE_OMIT_VIRTUALTABLE
2049 if( sqlite3VtabCallConnect(pParse, pTable) ){
2050 return SQLITE_ERROR;
2051 }
drh4cbdda92006-06-14 19:00:20 +00002052 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002053#endif
2054
2055#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002056 /* A positive nCol means the columns names for this view are
2057 ** already known.
2058 */
2059 if( pTable->nCol>0 ) return 0;
2060
2061 /* A negative nCol is a special marker meaning that we are currently
2062 ** trying to compute the column names. If we enter this routine with
2063 ** a negative nCol, it means two or more views form a loop, like this:
2064 **
2065 ** CREATE VIEW one AS SELECT * FROM two;
2066 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002067 **
drh768578e2009-05-12 00:40:12 +00002068 ** Actually, the error above is now caught prior to reaching this point.
2069 ** But the following test is still important as it does come up
2070 ** in the following:
2071 **
2072 ** CREATE TABLE main.ex1(a);
2073 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2074 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002075 */
2076 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002077 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002078 return 1;
2079 }
drh85c23c62005-08-20 03:03:04 +00002080 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002081
2082 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002083 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2084 ** "*" elements in the results set of the view and will assign cursors
2085 ** to the elements of the FROM clause. But we do not want these changes
2086 ** to be permanent. So the computation is done on a copy of the SELECT
2087 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002088 */
drh9b3187e2005-01-18 14:45:47 +00002089 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002090 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002091 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002092 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002093 n = pParse->nTab;
2094 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2095 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002096 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002097#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002098 xAuth = db->xAuth;
2099 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002100 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002101 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002102#else
drh7d10d5a2008-08-20 16:35:10 +00002103 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002104#endif
drhd9da78a2009-03-24 15:08:09 +00002105 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002106 pParse->nTab = n;
2107 if( pSelTab ){
2108 assert( pTable->aCol==0 );
2109 pTable->nCol = pSelTab->nCol;
2110 pTable->aCol = pSelTab->aCol;
2111 pSelTab->nCol = 0;
2112 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002113 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002114 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00002115 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002116 }else{
2117 pTable->nCol = 0;
2118 nErr++;
2119 }
drh633e6d52008-07-28 19:34:53 +00002120 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002121 } else {
drh417be792002-03-03 18:59:40 +00002122 nErr++;
2123 }
drhb7f91642004-10-31 02:22:47 +00002124#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002125 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002126}
2127#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002128
drhb7f91642004-10-31 02:22:47 +00002129#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002130/*
drh8bf8dc92003-05-17 17:35:10 +00002131** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002132*/
drh9bb575f2004-09-06 17:24:11 +00002133static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002134 HashElem *i;
drh21206082011-04-04 18:22:02 +00002135 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002136 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002137 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002138 Table *pTab = sqliteHashData(i);
2139 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002140 sqliteDeleteColumnNames(db, pTab);
2141 pTab->aCol = 0;
2142 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002143 }
2144 }
drh8bf8dc92003-05-17 17:35:10 +00002145 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002146}
drhb7f91642004-10-31 02:22:47 +00002147#else
2148# define sqliteViewResetAll(A,B)
2149#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002150
drh75897232000-05-29 14:26:00 +00002151/*
danielk1977a0bf2652004-11-04 14:30:04 +00002152** This function is called by the VDBE to adjust the internal schema
2153** used by SQLite when the btree layer moves a table root page. The
2154** root-page of a table or index in database iDb has changed from iFrom
2155** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002156**
2157** Ticket #1728: The symbol table might still contain information
2158** on tables and/or indices that are the process of being deleted.
2159** If you are unlucky, one of those deleted indices or tables might
2160** have the same rootpage number as the real table or index that is
2161** being moved. So we cannot stop searching after the first match
2162** because the first match might be for one of the deleted indices
2163** or tables and not the table/index that is actually being moved.
2164** We must continue looping until all tables and indices with
2165** rootpage==iFrom have been converted to have a rootpage of iTo
2166** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002167*/
2168#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002169void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002170 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002171 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002172 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002173
drhcdf011d2011-04-04 21:25:28 +00002174 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2175 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002176 pHash = &pDb->pSchema->tblHash;
2177 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002178 Table *pTab = sqliteHashData(pElem);
2179 if( pTab->tnum==iFrom ){
2180 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002181 }
2182 }
danielk1977da184232006-01-05 11:34:32 +00002183 pHash = &pDb->pSchema->idxHash;
2184 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002185 Index *pIdx = sqliteHashData(pElem);
2186 if( pIdx->tnum==iFrom ){
2187 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002188 }
2189 }
danielk1977a0bf2652004-11-04 14:30:04 +00002190}
2191#endif
2192
2193/*
2194** Write code to erase the table with root-page iTable from database iDb.
2195** Also write code to modify the sqlite_master table and internal schema
2196** if a root-page of another table is moved by the btree-layer whilst
2197** erasing iTable (this can happen with an auto-vacuum database).
2198*/
drh4e0cff62004-11-05 05:10:28 +00002199static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2200 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002201 int r1 = sqlite3GetTempReg(pParse);
2202 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002203 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002204#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002205 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002206 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002207 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002208 ** reflect this.
2209 **
drh0fa991b2009-03-21 16:19:26 +00002210 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002211 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2212 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002213 */
danielk197763e3e9f2004-11-05 09:19:27 +00002214 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002215 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2216 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002217#endif
drhb7654112008-01-12 12:48:07 +00002218 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002219}
2220
2221/*
2222** Write VDBE code to erase table pTab and all associated indices on disk.
2223** Code to update the sqlite_master tables and internal schema definitions
2224** in case a root-page belonging to another table is moved by the btree layer
2225** is also added (this can happen with an auto-vacuum database).
2226*/
drh4e0cff62004-11-05 05:10:28 +00002227static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002228#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002229 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002230 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2231 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002232 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002233 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002234 }
2235#else
2236 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2237 ** is not defined), then it is important to call OP_Destroy on the
2238 ** table and index root-pages in order, starting with the numerically
2239 ** largest root-page number. This guarantees that none of the root-pages
2240 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2241 ** following were coded:
2242 **
2243 ** OP_Destroy 4 0
2244 ** ...
2245 ** OP_Destroy 5 0
2246 **
2247 ** and root page 5 happened to be the largest root-page number in the
2248 ** database, then root page 5 would be moved to page 4 by the
2249 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2250 ** a free-list page.
2251 */
2252 int iTab = pTab->tnum;
2253 int iDestroyed = 0;
2254
2255 while( 1 ){
2256 Index *pIdx;
2257 int iLargest = 0;
2258
2259 if( iDestroyed==0 || iTab<iDestroyed ){
2260 iLargest = iTab;
2261 }
2262 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2263 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002264 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002265 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2266 iLargest = iIdx;
2267 }
2268 }
danielk1977da184232006-01-05 11:34:32 +00002269 if( iLargest==0 ){
2270 return;
2271 }else{
2272 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002273 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002274 destroyRootPage(pParse, iLargest, iDb);
2275 iDestroyed = iLargest;
2276 }
danielk1977a0bf2652004-11-04 14:30:04 +00002277 }
2278#endif
2279}
2280
2281/*
drh74e7c8f2011-10-21 19:06:32 +00002282** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002283** after a DROP INDEX or DROP TABLE command.
2284*/
2285static void sqlite3ClearStatTables(
2286 Parse *pParse, /* The parsing context */
2287 int iDb, /* The database number */
2288 const char *zType, /* "idx" or "tbl" */
2289 const char *zName /* Name of index or table */
2290){
drha5ae4c32011-08-07 01:31:52 +00002291 int i;
2292 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002293 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002294 char zTab[24];
2295 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2296 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002297 sqlite3NestedParse(pParse,
2298 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002299 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002300 );
2301 }
2302 }
2303}
2304
2305/*
drhfaacf172011-08-12 01:51:45 +00002306** Generate code to drop a table.
2307*/
2308void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2309 Vdbe *v;
2310 sqlite3 *db = pParse->db;
2311 Trigger *pTrigger;
2312 Db *pDb = &db->aDb[iDb];
2313
2314 v = sqlite3GetVdbe(pParse);
2315 assert( v!=0 );
2316 sqlite3BeginWriteOperation(pParse, 1, iDb);
2317
2318#ifndef SQLITE_OMIT_VIRTUALTABLE
2319 if( IsVirtual(pTab) ){
2320 sqlite3VdbeAddOp0(v, OP_VBegin);
2321 }
2322#endif
2323
2324 /* Drop all triggers associated with the table being dropped. Code
2325 ** is generated to remove entries from sqlite_master and/or
2326 ** sqlite_temp_master if required.
2327 */
2328 pTrigger = sqlite3TriggerList(pParse, pTab);
2329 while( pTrigger ){
2330 assert( pTrigger->pSchema==pTab->pSchema ||
2331 pTrigger->pSchema==db->aDb[1].pSchema );
2332 sqlite3DropTriggerPtr(pParse, pTrigger);
2333 pTrigger = pTrigger->pNext;
2334 }
2335
2336#ifndef SQLITE_OMIT_AUTOINCREMENT
2337 /* Remove any entries of the sqlite_sequence table associated with
2338 ** the table being dropped. This is done before the table is dropped
2339 ** at the btree level, in case the sqlite_sequence table needs to
2340 ** move as a result of the drop (can happen in auto-vacuum mode).
2341 */
2342 if( pTab->tabFlags & TF_Autoincrement ){
2343 sqlite3NestedParse(pParse,
2344 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2345 pDb->zName, pTab->zName
2346 );
2347 }
2348#endif
2349
2350 /* Drop all SQLITE_MASTER table and index entries that refer to the
2351 ** table. The program name loops through the master table and deletes
2352 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002353 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002354 ** created in the temp database that refers to a table in another
2355 ** database.
2356 */
2357 sqlite3NestedParse(pParse,
2358 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2359 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002360 if( !isView && !IsVirtual(pTab) ){
2361 destroyTable(pParse, pTab);
2362 }
2363
2364 /* Remove the table entry from SQLite's internal schema and modify
2365 ** the schema cookie.
2366 */
2367 if( IsVirtual(pTab) ){
2368 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2369 }
2370 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2371 sqlite3ChangeCookie(pParse, iDb);
2372 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002373}
2374
2375/*
drh75897232000-05-29 14:26:00 +00002376** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002377** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002378*/
drha0733842005-12-29 01:11:36 +00002379void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002380 Table *pTab;
drh75897232000-05-29 14:26:00 +00002381 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002382 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002383 int iDb;
drh75897232000-05-29 14:26:00 +00002384
drh8af73d42009-05-13 22:58:28 +00002385 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002386 goto exit_drop_table;
2387 }
drh8af73d42009-05-13 22:58:28 +00002388 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002389 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002390 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002391 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002392 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002393
drha0733842005-12-29 01:11:36 +00002394 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002395 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002396 goto exit_drop_table;
2397 }
danielk1977da184232006-01-05 11:34:32 +00002398 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002399 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002400
2401 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2402 ** it is initialized.
2403 */
2404 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2405 goto exit_drop_table;
2406 }
drhe5f9c642003-01-13 23:27:31 +00002407#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002408 {
2409 int code;
danielk1977da184232006-01-05 11:34:32 +00002410 const char *zTab = SCHEMA_TABLE(iDb);
2411 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002412 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002413 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002414 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002415 }
drhe5f9c642003-01-13 23:27:31 +00002416 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002417 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002418 code = SQLITE_DROP_TEMP_VIEW;
2419 }else{
2420 code = SQLITE_DROP_VIEW;
2421 }
danielk19774b2688a2006-06-20 11:01:07 +00002422#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002423 }else if( IsVirtual(pTab) ){
2424 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002425 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002426#endif
drhe5f9c642003-01-13 23:27:31 +00002427 }else{
danielk197753c0f742005-03-29 03:10:59 +00002428 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002429 code = SQLITE_DROP_TEMP_TABLE;
2430 }else{
2431 code = SQLITE_DROP_TABLE;
2432 }
2433 }
danielk1977f1a381e2006-06-16 08:01:02 +00002434 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002435 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002436 }
danielk1977a8858102004-05-28 12:11:21 +00002437 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2438 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002439 }
drhe5f9c642003-01-13 23:27:31 +00002440 }
2441#endif
drh08ccfaa2011-10-07 23:52:25 +00002442 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2443 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002444 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002445 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002446 }
danielk1977576ec6b2005-01-21 11:55:25 +00002447
2448#ifndef SQLITE_OMIT_VIEW
2449 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2450 ** on a table.
2451 */
danielk1977a8858102004-05-28 12:11:21 +00002452 if( isView && pTab->pSelect==0 ){
2453 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2454 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002455 }
danielk1977a8858102004-05-28 12:11:21 +00002456 if( !isView && pTab->pSelect ){
2457 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2458 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002459 }
danielk1977576ec6b2005-01-21 11:55:25 +00002460#endif
drh75897232000-05-29 14:26:00 +00002461
drh1ccde152000-06-17 13:12:39 +00002462 /* Generate code to remove the table from the master table
2463 ** on disk.
2464 */
danielk19774adee202004-05-08 08:23:19 +00002465 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002466 if( v ){
drh77658e22007-12-04 16:54:52 +00002467 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002468 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002469 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002470 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002471 }
danielk1977a8858102004-05-28 12:11:21 +00002472
2473exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002474 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002475}
2476
2477/*
drhc2eef3b2002-08-31 18:53:06 +00002478** This routine is called to create a new foreign key on the table
2479** currently under construction. pFromCol determines which columns
2480** in the current table point to the foreign key. If pFromCol==0 then
2481** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002482** the table referred to (a.k.a the "parent" table). pToCol is a list
2483** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002484** information about the conflict resolution algorithms specified
2485** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2486**
2487** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002488** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002489**
2490** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002491** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002492*/
danielk19774adee202004-05-08 08:23:19 +00002493void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002494 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002495 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002496 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002497 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002498 int flags /* Conflict resolution algorithms. */
2499){
danielk197718576932008-08-06 13:47:40 +00002500 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002501#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002502 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002503 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002504 Table *p = pParse->pNewTable;
2505 int nByte;
2506 int i;
2507 int nCol;
2508 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002509
2510 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002511 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002512 if( pFromCol==0 ){
2513 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002514 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002515 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002516 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002517 " should reference only one column of table %T",
2518 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002519 goto fk_end;
2520 }
2521 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002522 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002523 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002524 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002525 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002526 goto fk_end;
2527 }else{
danielk19770202b292004-06-09 09:55:16 +00002528 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002529 }
drhe61922a2009-05-02 13:29:37 +00002530 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002531 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002532 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002533 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002534 }
2535 }
drh633e6d52008-07-28 19:34:53 +00002536 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002537 if( pFKey==0 ){
2538 goto fk_end;
2539 }
drhc2eef3b2002-08-31 18:53:06 +00002540 pFKey->pFrom = p;
2541 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002542 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002543 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002544 memcpy(z, pTo->z, pTo->n);
2545 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002546 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002547 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002548 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002549 if( pFromCol==0 ){
2550 pFKey->aCol[0].iFrom = p->nCol-1;
2551 }else{
2552 for(i=0; i<nCol; i++){
2553 int j;
2554 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002555 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002556 pFKey->aCol[i].iFrom = j;
2557 break;
2558 }
2559 }
2560 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002561 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002562 "unknown column \"%s\" in foreign key definition",
2563 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002564 goto fk_end;
2565 }
2566 }
2567 }
2568 if( pToCol ){
2569 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002570 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002571 pFKey->aCol[i].zCol = z;
2572 memcpy(z, pToCol->a[i].zName, n);
2573 z[n] = 0;
2574 z += n+1;
2575 }
2576 }
2577 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002578 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2579 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002580
drh21206082011-04-04 18:22:02 +00002581 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002582 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2583 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2584 );
danf59c5ca2009-09-22 16:55:38 +00002585 if( pNextTo==pFKey ){
2586 db->mallocFailed = 1;
2587 goto fk_end;
2588 }
dan1da40a32009-09-19 17:00:31 +00002589 if( pNextTo ){
2590 assert( pNextTo->pPrevTo==0 );
2591 pFKey->pNextTo = pNextTo;
2592 pNextTo->pPrevTo = pFKey;
2593 }
2594
drhc2eef3b2002-08-31 18:53:06 +00002595 /* Link the foreign key to the table as the last step.
2596 */
2597 p->pFKey = pFKey;
2598 pFKey = 0;
2599
2600fk_end:
drh633e6d52008-07-28 19:34:53 +00002601 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002602#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002603 sqlite3ExprListDelete(db, pFromCol);
2604 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002605}
2606
2607/*
2608** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2609** clause is seen as part of a foreign key definition. The isDeferred
2610** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2611** The behavior of the most recently created foreign key is adjusted
2612** accordingly.
2613*/
danielk19774adee202004-05-08 08:23:19 +00002614void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002615#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002616 Table *pTab;
2617 FKey *pFKey;
2618 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002619 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002620 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002621#endif
drhc2eef3b2002-08-31 18:53:06 +00002622}
2623
2624/*
drh063336a2004-11-05 20:58:39 +00002625** Generate code that will erase and refill index *pIdx. This is
2626** used to initialize a newly created index or to recompute the
2627** content of an index in response to a REINDEX command.
2628**
2629** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002630** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002631** root page number of the index. If memRootPage is negative, then
2632** the index already exists and must be cleared before being refilled and
2633** the root page number of the index is taken from pIndex->tnum.
2634*/
2635static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2636 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002637 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2638 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002639 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002640 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002641 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002642 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002643 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002644 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002645 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002646 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002647 sqlite3 *db = pParse->db; /* The database connection */
2648 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002649
danielk19771d54df82004-11-23 15:41:16 +00002650#ifndef SQLITE_OMIT_AUTHORIZATION
2651 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002652 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002653 return;
2654 }
2655#endif
2656
danielk1977c00da102006-01-07 13:21:04 +00002657 /* Require a write-lock on the table to perform this operation */
2658 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2659
drh063336a2004-11-05 20:58:39 +00002660 v = sqlite3GetVdbe(pParse);
2661 if( v==0 ) return;
2662 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002663 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002664 }else{
2665 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002666 }
drh2ec2fb22013-11-06 19:59:23 +00002667 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002668
dan689ab892011-08-12 15:02:00 +00002669 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002670 iSorter = pParse->nTab++;
drh2ec2fb22013-11-06 19:59:23 +00002671 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
2672 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002673
2674 /* Open the table. Loop through all rows of the table, inserting index
2675 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002676 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002677 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002678 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002679
drh9eade082013-10-24 14:16:10 +00002680 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 0, &iPartIdxLabel);
drhca892a72011-09-03 00:17:51 +00002681 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drhb2b9d3d2013-08-01 01:14:43 +00002682 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
drhca892a72011-09-03 00:17:51 +00002683 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2684 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002685 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2686 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002687 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002688 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2689
drhca892a72011-09-03 00:17:51 +00002690 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
drh1153c7b2013-11-01 22:02:56 +00002691 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
2692 if( pIndex->onError!=OE_None && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002693 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2694 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2695 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002696 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
2697 pKey->nField - pIndex->nKeyCol);
drhf9c8ce32013-11-05 13:33:55 +00002698 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002699 }else{
2700 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002701 }
drhca892a72011-09-03 00:17:51 +00002702 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2703 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2704 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002705 sqlite3ReleaseTempReg(pParse, regRecord);
drhca892a72011-09-03 00:17:51 +00002706 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
drhd654be82005-09-20 17:42:23 +00002707 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002708
drh66a51672008-01-03 00:01:23 +00002709 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2710 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002711 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002712}
2713
2714/*
drh77e57df2013-10-22 14:28:02 +00002715** Allocate heap space to hold an Index object with nCol columns.
2716**
2717** Increase the allocation size to provide an extra nExtra bytes
2718** of 8-byte aligned space after the Index object and return a
2719** pointer to this extra space in *ppExtra.
2720*/
2721Index *sqlite3AllocateIndexObject(
2722 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002723 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002724 int nExtra, /* Number of bytes of extra space to alloc */
2725 char **ppExtra /* Pointer to the "extra" space */
2726){
2727 Index *p; /* Allocated index object */
2728 int nByte; /* Bytes of space for Index object + arrays */
2729
2730 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2731 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
2732 ROUND8(sizeof(tRowcnt)*(nCol+1) + /* Index.aiRowEst */
drhbbbdc832013-10-22 18:01:40 +00002733 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002734 sizeof(u8)*nCol); /* Index.aSortOrder */
2735 p = sqlite3DbMallocZero(db, nByte + nExtra);
2736 if( p ){
2737 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
2738 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2739 p->aiRowEst = (tRowcnt*)pExtra; pExtra += sizeof(tRowcnt)*(nCol+1);
drhbbbdc832013-10-22 18:01:40 +00002740 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002741 p->aSortOrder = (u8*)pExtra;
2742 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002743 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002744 *ppExtra = ((char*)p) + nByte;
2745 }
2746 return p;
2747}
2748
2749/*
drh23bf66d2004-12-14 03:34:34 +00002750** Create a new index for an SQL table. pName1.pName2 is the name of the index
2751** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002752** be NULL for a primary key or an index that is created to satisfy a
2753** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002754** as the table to be indexed. pParse->pNewTable is a table that is
2755** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002756**
drh382c0242001-10-06 16:33:02 +00002757** pList is a list of columns to be indexed. pList will be NULL if this
2758** is a primary key or unique-constraint on the most recent column added
2759** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002760**
2761** If the index is created successfully, return a pointer to the new Index
2762** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2763** as the tables primary key (Index.autoIndex==2).
drh75897232000-05-29 14:26:00 +00002764*/
dan1da40a32009-09-19 17:00:31 +00002765Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002766 Parse *pParse, /* All information about this parse */
2767 Token *pName1, /* First part of index name. May be NULL */
2768 Token *pName2, /* Second part of index name. May be NULL */
2769 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002770 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002771 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002772 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002773 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002774 int sortOrder, /* Sort order of primary key when pList==NULL */
2775 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002776){
dan1da40a32009-09-19 17:00:31 +00002777 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002778 Table *pTab = 0; /* Table to be indexed */
2779 Index *pIndex = 0; /* The index to be created */
2780 char *zName = 0; /* Name of the index */
2781 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002782 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002783 DbFixer sFix; /* For assigning database names to pTable */
2784 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002785 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002786 Db *pDb; /* The specific table containing the indexed database */
2787 int iDb; /* Index of the database that is being written */
2788 Token *pName = 0; /* Unqualified name of the index to create */
2789 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002790 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002791 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002792 int nExtraCol; /* Number of extra columns needed */
drhc28c4e52013-10-03 19:21:41 +00002793 char *zExtra; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002794 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002795
drh8af73d42009-05-13 22:58:28 +00002796 assert( pParse->nErr==0 ); /* Never called with prior errors */
2797 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002798 goto exit_create_index;
2799 }
2800 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002801 goto exit_create_index;
2802 }
drhdaffd0e2001-04-11 14:28:42 +00002803
drh75897232000-05-29 14:26:00 +00002804 /*
2805 ** Find the table that is to be indexed. Return early if not found.
2806 */
danielk1977cbb18d22004-05-28 11:37:27 +00002807 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002808
2809 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002810 ** to search for the table. 'Fix' the table name to this db
2811 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002812 */
2813 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002814 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002815 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002816 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002817
danielk197753c0f742005-03-29 03:10:59 +00002818#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002819 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002820 ** is a temp table. If so, set the database to 1. Do not do this
2821 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002822 */
danielk1977fe910332007-12-02 11:46:34 +00002823 if( !db->init.busy ){
2824 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002825 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002826 iDb = 1;
2827 }
danielk1977ef2cb632004-05-29 02:37:19 +00002828 }
danielk197753c0f742005-03-29 03:10:59 +00002829#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002830
drhd100f692013-10-03 15:39:44 +00002831 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2832 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002833 /* Because the parser constructs pTblName from a single identifier,
2834 ** sqlite3FixSrcList can never fail. */
2835 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002836 }
dan41fb5cd2012-10-04 19:33:00 +00002837 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002838 assert( db->mallocFailed==0 || pTab==0 );
2839 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002840 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2841 sqlite3ErrorMsg(pParse,
2842 "cannot create a TEMP index on non-TEMP table \"%s\"",
2843 pTab->zName);
2844 goto exit_create_index;
2845 }
drh44156282013-10-23 22:23:03 +00002846 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002847 }else{
drhe3c41372001-09-17 20:25:58 +00002848 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002849 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002850 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002851 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002852 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002853 }
drhfdd6e852005-12-16 01:06:16 +00002854 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002855
drhd3001712009-05-12 17:46:53 +00002856 assert( pTab!=0 );
2857 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002858 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh503a6862013-03-01 01:07:17 +00002859 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002860 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002861 goto exit_create_index;
2862 }
danielk1977576ec6b2005-01-21 11:55:25 +00002863#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002864 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002865 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002866 goto exit_create_index;
2867 }
danielk1977576ec6b2005-01-21 11:55:25 +00002868#endif
danielk19775ee9d692006-06-21 12:36:25 +00002869#ifndef SQLITE_OMIT_VIRTUALTABLE
2870 if( IsVirtual(pTab) ){
2871 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2872 goto exit_create_index;
2873 }
2874#endif
drh75897232000-05-29 14:26:00 +00002875
2876 /*
2877 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002878 ** index or table with the same name.
2879 **
2880 ** Exception: If we are reading the names of permanent indices from the
2881 ** sqlite_master table (because some other process changed the schema) and
2882 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002883 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002884 **
2885 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002886 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2887 ** own name.
drh75897232000-05-29 14:26:00 +00002888 */
danielk1977d8123362004-06-12 09:25:12 +00002889 if( pName ){
drh17435752007-08-16 04:30:38 +00002890 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002891 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002892 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002893 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002894 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002895 }
danielk1977d8123362004-06-12 09:25:12 +00002896 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002897 if( sqlite3FindTable(db, zName, 0)!=0 ){
2898 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2899 goto exit_create_index;
2900 }
2901 }
danielk197759a33f92007-03-17 10:26:59 +00002902 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2903 if( !ifNotExist ){
2904 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002905 }else{
2906 assert( !db->init.busy );
2907 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002908 }
danielk197759a33f92007-03-17 10:26:59 +00002909 goto exit_create_index;
2910 }
danielk1977a21c6b62005-01-24 10:25:59 +00002911 }else{
drhadbca9c2001-09-27 15:11:53 +00002912 int n;
2913 Index *pLoop;
2914 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002915 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002916 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002917 goto exit_create_index;
2918 }
drh75897232000-05-29 14:26:00 +00002919 }
2920
drhe5f9c642003-01-13 23:27:31 +00002921 /* Check for authorization to create an index.
2922 */
2923#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002924 {
drhfdd6e852005-12-16 01:06:16 +00002925 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002926 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002927 goto exit_create_index;
2928 }
2929 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002930 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002931 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002932 goto exit_create_index;
2933 }
drhe5f9c642003-01-13 23:27:31 +00002934 }
2935#endif
2936
drh75897232000-05-29 14:26:00 +00002937 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002938 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002939 ** So create a fake list to simulate this.
2940 */
2941 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002942 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002943 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002944 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2945 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00002946 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002947 }
2948
danielk1977b3bf5562006-01-10 17:58:23 +00002949 /* Figure out how many bytes of space are required to store explicitly
2950 ** specified collation sequence names.
2951 */
2952 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002953 Expr *pExpr = pList->a[i].pExpr;
2954 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00002955 assert( pExpr->op==TK_COLLATE );
2956 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00002957 }
2958 }
2959
drh75897232000-05-29 14:26:00 +00002960 /*
2961 ** Allocate the index structure.
2962 */
drhea678832008-12-10 19:26:22 +00002963 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00002964 nExtraCol = pPk ? pPk->nKeyCol : 1;
2965 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00002966 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00002967 if( db->mallocFailed ){
2968 goto exit_create_index;
2969 }
drhe09b84c2011-11-14 02:53:54 +00002970 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
2971 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00002972 pIndex->zName = zExtra;
2973 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00002974 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002975 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00002976 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00002977 pIndex->uniqNotNull = onError!=OE_None;
drh1bd10f82008-12-10 21:19:56 +00002978 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002979 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00002980 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00002981 if( pPIWhere ){
2982 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
2983 pIndex->pPartIdxWhere = pPIWhere;
2984 pPIWhere = 0;
2985 }
drh21206082011-04-04 18:22:02 +00002986 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00002987
drhfdd6e852005-12-16 01:06:16 +00002988 /* Check to see if we should honor DESC requests on index columns
2989 */
danielk1977da184232006-01-05 11:34:32 +00002990 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002991 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002992 }else{
2993 sortOrderMask = 0; /* Ignore DESC */
2994 }
2995
drh1ccde152000-06-17 13:12:39 +00002996 /* Scan the names of the columns of the table to be indexed and
2997 ** load the column indices into the Index structure. Report an error
2998 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00002999 **
3000 ** TODO: Add a test to make sure that the same column is not named
3001 ** more than once within the same index. Only the first instance of
3002 ** the column will ever be used by the optimizer. Note that using the
3003 ** same column more than once cannot be an error because that would
3004 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003005 */
drhfdd6e852005-12-16 01:06:16 +00003006 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3007 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003008 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003009 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003010
drhfdd6e852005-12-16 01:06:16 +00003011 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3012 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003013 }
3014 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003015 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003016 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003017 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003018 goto exit_create_index;
3019 }
drhbbbdc832013-10-22 18:01:40 +00003020 assert( pTab->nCol<=0x7fff && j<=0x7fff );
3021 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003022 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003023 int nColl;
dan911ce412013-05-15 15:16:50 +00003024 assert( pListItem->pExpr->op==TK_COLLATE );
3025 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003026 nColl = sqlite3Strlen30(zColl) + 1;
3027 assert( nExtra>=nColl );
3028 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003029 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003030 zExtra += nColl;
3031 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003032 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003033 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003034 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003035 }
drhb7f24de2009-05-13 17:35:23 +00003036 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003037 goto exit_create_index;
3038 }
danielk1977b3bf5562006-01-10 17:58:23 +00003039 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003040 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003041 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003042 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003043 }
drh44156282013-10-23 22:23:03 +00003044 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003045 for(j=0; j<pPk->nKeyCol; j++){
3046 int x = pPk->aiColumn[j];
3047 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3048 pIndex->nColumn--;
3049 }else{
3050 pIndex->aiColumn[i] = x;
3051 pIndex->azColl[i] = pPk->azColl[j];
3052 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3053 i++;
3054 }
drh44156282013-10-23 22:23:03 +00003055 }
drh7913e412013-11-01 20:30:36 +00003056 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003057 }else{
3058 pIndex->aiColumn[i] = -1;
3059 pIndex->azColl[i] = "BINARY";
3060 }
drh51147ba2005-07-23 22:59:55 +00003061 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003062 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003063
danielk1977d8123362004-06-12 09:25:12 +00003064 if( pTab==pParse->pNewTable ){
3065 /* This routine has been called to create an automatic index as a
3066 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3067 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3068 ** i.e. one of:
3069 **
3070 ** CREATE TABLE t(x PRIMARY KEY, y);
3071 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3072 **
3073 ** Either way, check to see if the table already has such an index. If
3074 ** so, don't bother creating this one. This only applies to
3075 ** automatically created indices. Users can do as they wish with
3076 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003077 **
3078 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3079 ** (and thus suppressing the second one) even if they have different
3080 ** sort orders.
3081 **
3082 ** If there are different collating sequences or if the columns of
3083 ** the constraint occur in different orders, then the constraints are
3084 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003085 */
3086 Index *pIdx;
3087 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3088 int k;
3089 assert( pIdx->onError!=OE_None );
3090 assert( pIdx->autoIndex );
3091 assert( pIndex->onError!=OE_None );
3092
drhbbbdc832013-10-22 18:01:40 +00003093 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3094 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003095 const char *z1;
3096 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003097 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003098 z1 = pIdx->azColl[k];
3099 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003100 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003101 }
drhbbbdc832013-10-22 18:01:40 +00003102 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003103 if( pIdx->onError!=pIndex->onError ){
3104 /* This constraint creates the same index as a previous
3105 ** constraint specified somewhere in the CREATE TABLE statement.
3106 ** However the ON CONFLICT clauses are different. If both this
3107 ** constraint and the previous equivalent constraint have explicit
3108 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003109 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003110 */
3111 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3112 sqlite3ErrorMsg(pParse,
3113 "conflicting ON CONFLICT clauses specified", 0);
3114 }
3115 if( pIdx->onError==OE_Default ){
3116 pIdx->onError = pIndex->onError;
3117 }
3118 }
danielk1977d8123362004-06-12 09:25:12 +00003119 goto exit_create_index;
3120 }
3121 }
3122 }
3123
drh75897232000-05-29 14:26:00 +00003124 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003125 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003126 */
drh234c39d2004-07-24 03:30:47 +00003127 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003128 Index *p;
drh21206082011-04-04 18:22:02 +00003129 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003130 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drha83ccca2009-04-28 13:01:09 +00003131 pIndex->zName, sqlite3Strlen30(pIndex->zName),
drhea678832008-12-10 19:26:22 +00003132 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003133 if( p ){
3134 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003135 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003136 goto exit_create_index;
3137 }
drh5e00f6c2001-09-13 13:46:56 +00003138 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003139 if( pTblName!=0 ){
3140 pIndex->tnum = db->init.newTnum;
3141 }
drhd78eeee2001-09-13 16:18:53 +00003142 }
3143
drh58383402013-11-04 17:00:50 +00003144 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3145 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3146 ** emit code to allocate the index rootpage on disk and make an entry for
3147 ** the index in the sqlite_master table and populate the index with
3148 ** content. But, do not do this if we are simply reading the sqlite_master
3149 ** table to parse the schema, or if this index is the PRIMARY KEY index
3150 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003151 **
drh58383402013-11-04 17:00:50 +00003152 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3153 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003154 ** has just been created, it contains no data and the index initialization
3155 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003156 */
drh58383402013-11-04 17:00:50 +00003157 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003158 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003159 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003160 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003161
danielk19774adee202004-05-08 08:23:19 +00003162 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003163 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003164
drhfdd6e852005-12-16 01:06:16 +00003165
drh063336a2004-11-05 20:58:39 +00003166 /* Create the rootpage for the index
3167 */
drhaee128d2005-02-14 20:48:18 +00003168 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003169 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003170
3171 /* Gather the complete text of the CREATE INDEX statement into
3172 ** the zStmt variable
3173 */
drhd3001712009-05-12 17:46:53 +00003174 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003175 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003176 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003177 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003178 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003179 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003180 }else{
3181 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003182 /* zStmt = sqlite3MPrintf(""); */
3183 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003184 }
drh063336a2004-11-05 20:58:39 +00003185
3186 /* Add an entry in sqlite_master for this index
3187 */
3188 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003189 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003190 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3191 pIndex->zName,
3192 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003193 iMem,
drh063336a2004-11-05 20:58:39 +00003194 zStmt
3195 );
drh633e6d52008-07-28 19:34:53 +00003196 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003197
danielk1977a21c6b62005-01-24 10:25:59 +00003198 /* Fill the index with data and reparse the schema. Code an OP_Expire
3199 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003200 */
danielk1977cbb18d22004-05-28 11:37:27 +00003201 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003202 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003203 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003204 sqlite3VdbeAddParseSchemaOp(v, iDb,
3205 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003206 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003207 }
drh75897232000-05-29 14:26:00 +00003208 }
3209
danielk1977d8123362004-06-12 09:25:12 +00003210 /* When adding an index to the list of indices for a table, make
3211 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003212 ** OE_Ignore. This is necessary for the correct constraint check
3213 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3214 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003215 */
drh234c39d2004-07-24 03:30:47 +00003216 if( db->init.busy || pTblName==0 ){
3217 if( onError!=OE_Replace || pTab->pIndex==0
3218 || pTab->pIndex->onError==OE_Replace){
3219 pIndex->pNext = pTab->pIndex;
3220 pTab->pIndex = pIndex;
3221 }else{
3222 Index *pOther = pTab->pIndex;
3223 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3224 pOther = pOther->pNext;
3225 }
3226 pIndex->pNext = pOther->pNext;
3227 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003228 }
dan1da40a32009-09-19 17:00:31 +00003229 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003230 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003231 }
danielk1977d8123362004-06-12 09:25:12 +00003232
drh75897232000-05-29 14:26:00 +00003233 /* Clean up before exiting */
3234exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003235 if( pIndex ) freeIndex(db, pIndex);
3236 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003237 sqlite3ExprListDelete(db, pList);
3238 sqlite3SrcListDelete(db, pTblName);
3239 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003240 return pRet;
drh75897232000-05-29 14:26:00 +00003241}
3242
3243/*
drh51147ba2005-07-23 22:59:55 +00003244** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003245** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003246**
3247** aiRowEst[0] is suppose to contain the number of elements in the index.
3248** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3249** number of rows in the table that match any particular value of the
3250** first column of the index. aiRowEst[2] is an estimate of the number
3251** of rows that match any particular combiniation of the first 2 columns
3252** of the index. And so forth. It must always be the case that
3253*
3254** aiRowEst[N]<=aiRowEst[N-1]
3255** aiRowEst[N]>=1
3256**
3257** Apart from that, we have little to go on besides intuition as to
3258** how aiRowEst[] should be initialized. The numbers generated here
3259** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003260*/
3261void sqlite3DefaultRowEst(Index *pIdx){
drhfaacf172011-08-12 01:51:45 +00003262 tRowcnt *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00003263 int i;
drhfaacf172011-08-12 01:51:45 +00003264 tRowcnt n;
drh28c4cf42005-07-27 20:41:43 +00003265 assert( a!=0 );
drh15564052010-09-25 22:32:56 +00003266 a[0] = pIdx->pTable->nRowEst;
3267 if( a[0]<10 ) a[0] = 10;
3268 n = 10;
drhbbbdc832013-10-22 18:01:40 +00003269 for(i=1; i<=pIdx->nKeyCol; i++){
drh15564052010-09-25 22:32:56 +00003270 a[i] = n;
3271 if( n>5 ) n--;
drh28c4cf42005-07-27 20:41:43 +00003272 }
3273 if( pIdx->onError!=OE_None ){
drhbbbdc832013-10-22 18:01:40 +00003274 a[pIdx->nKeyCol] = 1;
drh51147ba2005-07-23 22:59:55 +00003275 }
3276}
3277
3278/*
drh74e24cd2002-01-09 03:19:59 +00003279** This routine will drop an existing named index. This routine
3280** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003281*/
drh4d91a702006-01-04 15:54:36 +00003282void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003283 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003284 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003285 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003286 int iDb;
drh75897232000-05-29 14:26:00 +00003287
drh8af73d42009-05-13 22:58:28 +00003288 assert( pParse->nErr==0 ); /* Never called with prior errors */
3289 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003290 goto exit_drop_index;
3291 }
drhd24cc422003-03-27 12:51:24 +00003292 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003293 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3294 goto exit_drop_index;
3295 }
danielk19774adee202004-05-08 08:23:19 +00003296 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003297 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003298 if( !ifExists ){
3299 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003300 }else{
3301 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003302 }
drha6ecd332004-06-10 00:29:09 +00003303 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003304 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003305 }
drh485b39b2002-07-13 03:11:52 +00003306 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00003307 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003308 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003309 goto exit_drop_index;
3310 }
danielk1977da184232006-01-05 11:34:32 +00003311 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003312#ifndef SQLITE_OMIT_AUTHORIZATION
3313 {
3314 int code = SQLITE_DROP_INDEX;
3315 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003316 const char *zDb = db->aDb[iDb].zName;
3317 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003318 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003319 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003320 }
danielk1977da184232006-01-05 11:34:32 +00003321 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003322 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003323 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003324 }
drhed6c8672003-01-12 18:02:16 +00003325 }
drhe5f9c642003-01-13 23:27:31 +00003326#endif
drh75897232000-05-29 14:26:00 +00003327
3328 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003329 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003330 if( v ){
drh77658e22007-12-04 16:54:52 +00003331 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003332 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003333 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003334 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003335 );
drha5ae4c32011-08-07 01:31:52 +00003336 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003337 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003338 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003339 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003340 }
3341
drhd24cc422003-03-27 12:51:24 +00003342exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003343 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003344}
3345
3346/*
dan9ace1122012-03-29 07:51:45 +00003347** pArray is a pointer to an array of objects. Each object in the
3348** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3349** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003350**
dan9ace1122012-03-29 07:51:45 +00003351** When this function is called, *pnEntry contains the current size of
3352** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3353** in total).
drh13449892005-09-07 21:22:45 +00003354**
dan9ace1122012-03-29 07:51:45 +00003355** If the realloc() is successful (i.e. if no OOM condition occurs), the
3356** space allocated for the new object is zeroed, *pnEntry updated to
3357** reflect the new size of the array and a pointer to the new allocation
3358** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003359**
dan9ace1122012-03-29 07:51:45 +00003360** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3361** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003362*/
drhcf643722007-03-27 13:36:37 +00003363void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003364 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003365 void *pArray, /* Array of objects. Might be reallocated */
3366 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003367 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003368 int *pIdx /* Write the index of a new slot here */
3369){
3370 char *z;
drh6c535152012-02-02 03:38:30 +00003371 int n = *pnEntry;
3372 if( (n & (n-1))==0 ){
3373 int sz = (n==0) ? 1 : 2*n;
3374 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003375 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003376 *pIdx = -1;
3377 return pArray;
drh13449892005-09-07 21:22:45 +00003378 }
drhcf643722007-03-27 13:36:37 +00003379 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003380 }
drhcf643722007-03-27 13:36:37 +00003381 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003382 memset(&z[n * szEntry], 0, szEntry);
3383 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003384 ++*pnEntry;
3385 return pArray;
drh13449892005-09-07 21:22:45 +00003386}
3387
3388/*
drh75897232000-05-29 14:26:00 +00003389** Append a new element to the given IdList. Create a new IdList if
3390** need be.
drhdaffd0e2001-04-11 14:28:42 +00003391**
3392** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003393*/
drh17435752007-08-16 04:30:38 +00003394IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003395 int i;
drh75897232000-05-29 14:26:00 +00003396 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003397 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003398 if( pList==0 ) return 0;
3399 }
drhcf643722007-03-27 13:36:37 +00003400 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003401 db,
drhcf643722007-03-27 13:36:37 +00003402 pList->a,
3403 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003404 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003405 &i
3406 );
drh13449892005-09-07 21:22:45 +00003407 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003408 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003409 return 0;
drh75897232000-05-29 14:26:00 +00003410 }
drh17435752007-08-16 04:30:38 +00003411 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003412 return pList;
3413}
3414
3415/*
drhfe05af82005-07-21 03:14:59 +00003416** Delete an IdList.
3417*/
drh633e6d52008-07-28 19:34:53 +00003418void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003419 int i;
3420 if( pList==0 ) return;
3421 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003422 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003423 }
drh633e6d52008-07-28 19:34:53 +00003424 sqlite3DbFree(db, pList->a);
3425 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003426}
3427
3428/*
3429** Return the index in pList of the identifier named zId. Return -1
3430** if not found.
3431*/
3432int sqlite3IdListIndex(IdList *pList, const char *zName){
3433 int i;
3434 if( pList==0 ) return -1;
3435 for(i=0; i<pList->nId; i++){
3436 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3437 }
3438 return -1;
3439}
3440
3441/*
drha78c22c2008-11-11 18:28:58 +00003442** Expand the space allocated for the given SrcList object by
3443** creating nExtra new slots beginning at iStart. iStart is zero based.
3444** New slots are zeroed.
3445**
3446** For example, suppose a SrcList initially contains two entries: A,B.
3447** To append 3 new entries onto the end, do this:
3448**
3449** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3450**
3451** After the call above it would contain: A, B, nil, nil, nil.
3452** If the iStart argument had been 1 instead of 2, then the result
3453** would have been: A, nil, nil, nil, B. To prepend the new slots,
3454** the iStart value would be 0. The result then would
3455** be: nil, nil, nil, A, B.
3456**
3457** If a memory allocation fails the SrcList is unchanged. The
3458** db->mallocFailed flag will be set to true.
3459*/
3460SrcList *sqlite3SrcListEnlarge(
3461 sqlite3 *db, /* Database connection to notify of OOM errors */
3462 SrcList *pSrc, /* The SrcList to be enlarged */
3463 int nExtra, /* Number of new slots to add to pSrc->a[] */
3464 int iStart /* Index in pSrc->a[] of first new slot */
3465){
3466 int i;
3467
3468 /* Sanity checking on calling parameters */
3469 assert( iStart>=0 );
3470 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003471 assert( pSrc!=0 );
3472 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003473
3474 /* Allocate additional space if needed */
3475 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3476 SrcList *pNew;
3477 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003478 int nGot;
drha78c22c2008-11-11 18:28:58 +00003479 pNew = sqlite3DbRealloc(db, pSrc,
3480 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3481 if( pNew==0 ){
3482 assert( db->mallocFailed );
3483 return pSrc;
3484 }
3485 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003486 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drhad01d892013-06-19 13:59:49 +00003487 pSrc->nAlloc = (u8)nGot;
drha78c22c2008-11-11 18:28:58 +00003488 }
3489
3490 /* Move existing slots that come after the newly inserted slots
3491 ** out of the way */
3492 for(i=pSrc->nSrc-1; i>=iStart; i--){
3493 pSrc->a[i+nExtra] = pSrc->a[i];
3494 }
drhad01d892013-06-19 13:59:49 +00003495 pSrc->nSrc += (i8)nExtra;
drha78c22c2008-11-11 18:28:58 +00003496
3497 /* Zero the newly allocated slots */
3498 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3499 for(i=iStart; i<iStart+nExtra; i++){
3500 pSrc->a[i].iCursor = -1;
3501 }
3502
3503 /* Return a pointer to the enlarged SrcList */
3504 return pSrc;
3505}
3506
3507
3508/*
drhad3cab52002-05-24 02:04:32 +00003509** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003510** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003511**
drha78c22c2008-11-11 18:28:58 +00003512** A SrcList is returned, or NULL if there is an OOM error. The returned
3513** SrcList might be the same as the SrcList that was input or it might be
3514** a new one. If an OOM error does occurs, then the prior value of pList
3515** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003516**
3517** If pDatabase is not null, it means that the table has an optional
3518** database name prefix. Like this: "database.table". The pDatabase
3519** points to the table name and the pTable points to the database name.
3520** The SrcList.a[].zName field is filled with the table name which might
3521** come from pTable (if pDatabase is NULL) or from pDatabase.
3522** SrcList.a[].zDatabase is filled with the database name from pTable,
3523** or with NULL if no database is specified.
3524**
3525** In other words, if call like this:
3526**
drh17435752007-08-16 04:30:38 +00003527** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003528**
3529** Then B is a table name and the database name is unspecified. If called
3530** like this:
3531**
drh17435752007-08-16 04:30:38 +00003532** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003533**
drhd3001712009-05-12 17:46:53 +00003534** Then C is the table name and B is the database name. If C is defined
3535** then so is B. In other words, we never have a case where:
3536**
3537** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003538**
3539** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3540** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003541*/
drh17435752007-08-16 04:30:38 +00003542SrcList *sqlite3SrcListAppend(
3543 sqlite3 *db, /* Connection to notify of malloc failures */
3544 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3545 Token *pTable, /* Table to append */
3546 Token *pDatabase /* Database of the table */
3547){
drha99db3b2004-06-19 14:49:12 +00003548 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003549 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003550 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003551 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003552 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003553 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003554 }
drha78c22c2008-11-11 18:28:58 +00003555 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3556 if( db->mallocFailed ){
3557 sqlite3SrcListDelete(db, pList);
3558 return 0;
drhad3cab52002-05-24 02:04:32 +00003559 }
drha78c22c2008-11-11 18:28:58 +00003560 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003561 if( pDatabase && pDatabase->z==0 ){
3562 pDatabase = 0;
3563 }
drhd3001712009-05-12 17:46:53 +00003564 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003565 Token *pTemp = pDatabase;
3566 pDatabase = pTable;
3567 pTable = pTemp;
3568 }
drh17435752007-08-16 04:30:38 +00003569 pItem->zName = sqlite3NameFromToken(db, pTable);
3570 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003571 return pList;
3572}
3573
3574/*
drhdfe88ec2008-11-03 20:55:06 +00003575** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003576*/
danielk19774adee202004-05-08 08:23:19 +00003577void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003578 int i;
drh9b3187e2005-01-18 14:45:47 +00003579 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003580 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003581 if( pList ){
3582 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3583 if( pItem->iCursor>=0 ) break;
3584 pItem->iCursor = pParse->nTab++;
3585 if( pItem->pSelect ){
3586 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3587 }
drh63eb5f22003-04-29 16:20:44 +00003588 }
3589 }
3590}
3591
3592/*
drhad3cab52002-05-24 02:04:32 +00003593** Delete an entire SrcList including all its substructure.
3594*/
drh633e6d52008-07-28 19:34:53 +00003595void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003596 int i;
drhbe5c89a2004-07-26 00:31:09 +00003597 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003598 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003599 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003600 sqlite3DbFree(db, pItem->zDatabase);
3601 sqlite3DbFree(db, pItem->zName);
3602 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003603 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003604 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003605 sqlite3SelectDelete(db, pItem->pSelect);
3606 sqlite3ExprDelete(db, pItem->pOn);
3607 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003608 }
drh633e6d52008-07-28 19:34:53 +00003609 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003610}
3611
drh982cef72000-05-30 16:27:03 +00003612/*
drh61dfc312006-12-16 16:25:15 +00003613** This routine is called by the parser to add a new term to the
3614** end of a growing FROM clause. The "p" parameter is the part of
3615** the FROM clause that has already been constructed. "p" is NULL
3616** if this is the first term of the FROM clause. pTable and pDatabase
3617** are the name of the table and database named in the FROM clause term.
3618** pDatabase is NULL if the database name qualifier is missing - the
3619** usual case. If the term has a alias, then pAlias points to the
3620** alias token. If the term is a subquery, then pSubquery is the
3621** SELECT statement that the subquery encodes. The pTable and
3622** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3623** parameters are the content of the ON and USING clauses.
3624**
3625** Return a new SrcList which encodes is the FROM with the new
3626** term added.
3627*/
3628SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003629 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003630 SrcList *p, /* The left part of the FROM clause already seen */
3631 Token *pTable, /* Name of the table to add to the FROM clause */
3632 Token *pDatabase, /* Name of the database containing pTable */
3633 Token *pAlias, /* The right-hand side of the AS subexpression */
3634 Select *pSubquery, /* A subquery used in place of a table name */
3635 Expr *pOn, /* The ON clause of a join */
3636 IdList *pUsing /* The USING clause of a join */
3637){
3638 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003639 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003640 if( !p && (pOn || pUsing) ){
3641 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3642 (pOn ? "ON" : "USING")
3643 );
3644 goto append_from_error;
3645 }
drh17435752007-08-16 04:30:38 +00003646 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003647 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003648 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003649 }
3650 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003651 assert( pAlias!=0 );
3652 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003653 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003654 }
3655 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003656 pItem->pOn = pOn;
3657 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003658 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003659
3660 append_from_error:
3661 assert( p==0 );
3662 sqlite3ExprDelete(db, pOn);
3663 sqlite3IdListDelete(db, pUsing);
3664 sqlite3SelectDelete(db, pSubquery);
3665 return 0;
drh61dfc312006-12-16 16:25:15 +00003666}
3667
3668/*
danielk1977b1c685b2008-10-06 16:18:39 +00003669** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3670** element of the source-list passed as the second argument.
3671*/
3672void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003673 assert( pIndexedBy!=0 );
3674 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003675 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3676 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3677 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3678 /* A "NOT INDEXED" clause was supplied. See parse.y
3679 ** construct "indexed_opt" for details. */
3680 pItem->notIndexed = 1;
3681 }else{
3682 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3683 }
3684 }
3685}
3686
3687/*
drh61dfc312006-12-16 16:25:15 +00003688** When building up a FROM clause in the parser, the join operator
3689** is initially attached to the left operand. But the code generator
3690** expects the join operator to be on the right operand. This routine
3691** Shifts all join operators from left to right for an entire FROM
3692** clause.
3693**
3694** Example: Suppose the join is like this:
3695**
3696** A natural cross join B
3697**
3698** The operator is "natural cross join". The A and B operands are stored
3699** in p->a[0] and p->a[1], respectively. The parser initially stores the
3700** operator with A. This routine shifts that operator over to B.
3701*/
3702void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003703 if( p ){
drh61dfc312006-12-16 16:25:15 +00003704 int i;
drhd017ab92011-08-23 00:01:58 +00003705 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003706 for(i=p->nSrc-1; i>0; i--){
3707 p->a[i].jointype = p->a[i-1].jointype;
3708 }
3709 p->a[0].jointype = 0;
3710 }
3711}
3712
3713/*
drhc4a3c772001-04-04 11:48:57 +00003714** Begin a transaction
3715*/
drh684917c2004-10-05 02:41:42 +00003716void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003717 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003718 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003719 int i;
drh5e00f6c2001-09-13 13:46:56 +00003720
drhd3001712009-05-12 17:46:53 +00003721 assert( pParse!=0 );
3722 db = pParse->db;
3723 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003724/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003725 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3726 return;
3727 }
danielk19771d850a72004-05-31 08:26:49 +00003728 v = sqlite3GetVdbe(pParse);
3729 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003730 if( type!=TK_DEFERRED ){
3731 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003732 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003733 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003734 }
3735 }
drh66a51672008-01-03 00:01:23 +00003736 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003737}
3738
3739/*
3740** Commit a transaction
3741*/
danielk19774adee202004-05-08 08:23:19 +00003742void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003743 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003744
drhd3001712009-05-12 17:46:53 +00003745 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003746 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003747 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3748 return;
3749 }
danielk19771d850a72004-05-31 08:26:49 +00003750 v = sqlite3GetVdbe(pParse);
3751 if( v ){
drh66a51672008-01-03 00:01:23 +00003752 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003753 }
drhc4a3c772001-04-04 11:48:57 +00003754}
3755
3756/*
3757** Rollback a transaction
3758*/
danielk19774adee202004-05-08 08:23:19 +00003759void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003760 Vdbe *v;
3761
drhd3001712009-05-12 17:46:53 +00003762 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003763 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003764 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3765 return;
3766 }
danielk19774adee202004-05-08 08:23:19 +00003767 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003768 if( v ){
drh66a51672008-01-03 00:01:23 +00003769 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003770 }
drhc4a3c772001-04-04 11:48:57 +00003771}
drhf57b14a2001-09-14 18:54:08 +00003772
3773/*
danielk1977fd7f0452008-12-17 17:30:26 +00003774** This function is called by the parser when it parses a command to create,
3775** release or rollback an SQL savepoint.
3776*/
3777void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003778 char *zName = sqlite3NameFromToken(pParse->db, pName);
3779 if( zName ){
3780 Vdbe *v = sqlite3GetVdbe(pParse);
3781#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003782 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003783 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3784#endif
3785 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3786 sqlite3DbFree(pParse->db, zName);
3787 return;
3788 }
3789 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003790 }
3791}
3792
3793/*
drhdc3ff9c2004-08-18 02:10:15 +00003794** Make sure the TEMP database is open and available for use. Return
3795** the number of errors. Leave any error messages in the pParse structure.
3796*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003797int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003798 sqlite3 *db = pParse->db;
3799 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003800 int rc;
drh10a76c92010-01-26 01:25:26 +00003801 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003802 static const int flags =
3803 SQLITE_OPEN_READWRITE |
3804 SQLITE_OPEN_CREATE |
3805 SQLITE_OPEN_EXCLUSIVE |
3806 SQLITE_OPEN_DELETEONCLOSE |
3807 SQLITE_OPEN_TEMP_DB;
3808
dan3a6d8ae2011-04-23 15:54:54 +00003809 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003810 if( rc!=SQLITE_OK ){
3811 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3812 "file for storing temporary tables");
3813 pParse->rc = rc;
3814 return 1;
3815 }
drh10a76c92010-01-26 01:25:26 +00003816 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003817 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003818 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3819 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003820 return 1;
drh10a76c92010-01-26 01:25:26 +00003821 }
drhdc3ff9c2004-08-18 02:10:15 +00003822 }
3823 return 0;
3824}
3825
3826/*
drh80242052004-06-09 00:48:12 +00003827** Generate VDBE code that will verify the schema cookie and start
3828** a read-transaction for all named database files.
3829**
3830** It is important that all schema cookies be verified and all
3831** read transactions be started before anything else happens in
3832** the VDBE program. But this routine can be called after much other
3833** code has been generated. So here is what we do:
3834**
drhc275b4e2004-07-19 17:25:24 +00003835** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003836** will jump to a subroutine at the end of the program. Then we
3837** record every database that needs its schema verified in the
3838** pParse->cookieMask field. Later, after all other code has been
3839** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003840** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003841** will be made to point to that subroutine. The generation of the
3842** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003843**
3844** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3845** schema on any databases. This can be used to position the OP_Goto
3846** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003847*/
danielk19774adee202004-05-08 08:23:19 +00003848void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003849 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003850
danf78baaf2012-12-06 19:37:22 +00003851#ifndef SQLITE_OMIT_TRIGGER
3852 if( pToplevel!=pParse ){
3853 /* This branch is taken if a trigger is currently being coded. In this
3854 ** case, set cookieGoto to a non-zero value to show that this function
3855 ** has been called. This is used by the sqlite3ExprCodeConstants()
3856 ** function. */
3857 pParse->cookieGoto = -1;
3858 }
3859#endif
dan65a7cd12009-09-01 12:16:01 +00003860 if( pToplevel->cookieGoto==0 ){
3861 Vdbe *v = sqlite3GetVdbe(pToplevel);
3862 if( v==0 ) return; /* This only happens if there was a prior error */
3863 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003864 }
drhc275b4e2004-07-19 17:25:24 +00003865 if( iDb>=0 ){
dan65a7cd12009-09-01 12:16:01 +00003866 sqlite3 *db = pToplevel->db;
drh64123582011-04-02 20:01:02 +00003867 yDbMask mask;
dan65a7cd12009-09-01 12:16:01 +00003868
drhc275b4e2004-07-19 17:25:24 +00003869 assert( iDb<db->nDb );
3870 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003871 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drh21206082011-04-04 18:22:02 +00003872 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh64123582011-04-02 20:01:02 +00003873 mask = ((yDbMask)1)<<iDb;
dan65a7cd12009-09-01 12:16:01 +00003874 if( (pToplevel->cookieMask & mask)==0 ){
3875 pToplevel->cookieMask |= mask;
3876 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003877 if( !OMIT_TEMPDB && iDb==1 ){
dan65a7cd12009-09-01 12:16:01 +00003878 sqlite3OpenTempDatabase(pToplevel);
drhdc3ff9c2004-08-18 02:10:15 +00003879 }
drhc275b4e2004-07-19 17:25:24 +00003880 }
drh001bbcb2003-03-19 03:14:00 +00003881 }
drh001bbcb2003-03-19 03:14:00 +00003882}
3883
3884/*
dan57966752011-04-09 17:32:58 +00003885** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3886** attached database. Otherwise, invoke it for the database named zDb only.
3887*/
3888void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3889 sqlite3 *db = pParse->db;
3890 int i;
3891 for(i=0; i<db->nDb; i++){
3892 Db *pDb = &db->aDb[i];
3893 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3894 sqlite3CodeVerifySchema(pParse, i);
3895 }
3896 }
3897}
3898
3899/*
drh1c928532002-01-31 15:54:21 +00003900** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003901** might change the database.
3902**
3903** This routine starts a new transaction if we are not already within
3904** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003905** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003906** be set for operations that might fail (due to a constraint) part of
3907** the way through and which will need to undo some writes without having to
3908** rollback the whole transaction. For operations where all constraints
3909** can be checked before any changes are made to the database, it is never
3910** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003911*/
drh7f0f12e2004-05-21 13:39:50 +00003912void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003913 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003914 sqlite3CodeVerifySchema(pParse, iDb);
drh64123582011-04-02 20:01:02 +00003915 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
dane0af83a2009-09-08 19:15:01 +00003916 pToplevel->isMultiWrite |= setStatement;
3917}
3918
drhff738bc2009-09-24 00:09:58 +00003919/*
3920** Indicate that the statement currently under construction might write
3921** more than one entry (example: deleting one row then inserting another,
3922** inserting multiple rows in a table, or inserting a row and index entries.)
3923** If an abort occurs after some of these writes have completed, then it will
3924** be necessary to undo the completed writes.
3925*/
3926void sqlite3MultiWrite(Parse *pParse){
3927 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3928 pToplevel->isMultiWrite = 1;
3929}
3930
dane0af83a2009-09-08 19:15:01 +00003931/*
drhff738bc2009-09-24 00:09:58 +00003932** The code generator calls this routine if is discovers that it is
3933** possible to abort a statement prior to completion. In order to
3934** perform this abort without corrupting the database, we need to make
3935** sure that the statement is protected by a statement transaction.
3936**
3937** Technically, we only need to set the mayAbort flag if the
3938** isMultiWrite flag was previously set. There is a time dependency
3939** such that the abort must occur after the multiwrite. This makes
3940** some statements involving the REPLACE conflict resolution algorithm
3941** go a little faster. But taking advantage of this time dependency
3942** makes it more difficult to prove that the code is correct (in
3943** particular, it prevents us from writing an effective
3944** implementation of sqlite3AssertMayAbort()) and so we have chosen
3945** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003946*/
3947void sqlite3MayAbort(Parse *pParse){
3948 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3949 pToplevel->mayAbort = 1;
3950}
3951
3952/*
3953** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3954** error. The onError parameter determines which (if any) of the statement
3955** and/or current transaction is rolled back.
3956*/
drhd91c1a12013-02-09 13:58:25 +00003957void sqlite3HaltConstraint(
3958 Parse *pParse, /* Parsing context */
3959 int errCode, /* extended error code */
3960 int onError, /* Constraint type */
3961 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003962 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3963 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003964){
dane0af83a2009-09-08 19:15:01 +00003965 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003966 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003967 if( onError==OE_Abort ){
3968 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003969 }
drhd91c1a12013-02-09 13:58:25 +00003970 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003971 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3972}
3973
3974/*
3975** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3976*/
3977void sqlite3UniqueConstraint(
3978 Parse *pParse, /* Parsing context */
3979 int onError, /* Constraint type */
3980 Index *pIdx /* The index that triggers the constraint */
3981){
3982 char *zErr;
3983 int j;
3984 StrAccum errMsg;
3985 Table *pTab = pIdx->pTable;
3986
3987 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
3988 errMsg.db = pParse->db;
3989 for(j=0; j<pIdx->nKeyCol; j++){
3990 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
3991 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
3992 sqlite3StrAccumAppend(&errMsg, pTab->zName, -1);
3993 sqlite3StrAccumAppend(&errMsg, ".", 1);
3994 sqlite3StrAccumAppend(&errMsg, zCol, -1);
3995 }
3996 zErr = sqlite3StrAccumFinish(&errMsg);
3997 sqlite3HaltConstraint(pParse,
3998 (pIdx->autoIndex==2)?SQLITE_CONSTRAINT_PRIMARYKEY:SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00003999 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004000}
4001
4002
4003/*
4004** Code an OP_Halt due to non-unique rowid.
4005*/
4006void sqlite3RowidConstraint(
4007 Parse *pParse, /* Parsing context */
4008 int onError, /* Conflict resolution algorithm */
4009 Table *pTab /* The table with the non-unique rowid */
4010){
4011 char *zMsg;
4012 int rc;
4013 if( pTab->iPKey>=0 ){
4014 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4015 pTab->aCol[pTab->iPKey].zName);
4016 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4017 }else{
4018 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4019 rc = SQLITE_CONSTRAINT_ROWID;
4020 }
4021 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4022 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004023}
4024
drh4343fea2004-11-05 23:46:15 +00004025/*
4026** Check to see if pIndex uses the collating sequence pColl. Return
4027** true if it does and false if it does not.
4028*/
4029#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004030static int collationMatch(const char *zColl, Index *pIndex){
4031 int i;
drh04491712009-05-13 17:21:13 +00004032 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004033 for(i=0; i<pIndex->nColumn; i++){
4034 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004035 assert( z!=0 || pIndex->aiColumn[i]<0 );
4036 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004037 return 1;
4038 }
drh4343fea2004-11-05 23:46:15 +00004039 }
4040 return 0;
4041}
4042#endif
4043
4044/*
4045** Recompute all indices of pTab that use the collating sequence pColl.
4046** If pColl==0 then recompute all indices of pTab.
4047*/
4048#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004049static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004050 Index *pIndex; /* An index associated with pTab */
4051
4052 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004053 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004054 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4055 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004056 sqlite3RefillIndex(pParse, pIndex, -1);
4057 }
4058 }
4059}
4060#endif
4061
4062/*
4063** Recompute all indices of all tables in all databases where the
4064** indices use the collating sequence pColl. If pColl==0 then recompute
4065** all indices everywhere.
4066*/
4067#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004068static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004069 Db *pDb; /* A single database */
4070 int iDb; /* The database index number */
4071 sqlite3 *db = pParse->db; /* The database connection */
4072 HashElem *k; /* For looping over tables in pDb */
4073 Table *pTab; /* A table in the database */
4074
drh21206082011-04-04 18:22:02 +00004075 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004076 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004077 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004078 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004079 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004080 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004081 }
4082 }
4083}
4084#endif
4085
4086/*
drheee46cf2004-11-06 00:02:48 +00004087** Generate code for the REINDEX command.
4088**
4089** REINDEX -- 1
4090** REINDEX <collation> -- 2
4091** REINDEX ?<database>.?<tablename> -- 3
4092** REINDEX ?<database>.?<indexname> -- 4
4093**
4094** Form 1 causes all indices in all attached databases to be rebuilt.
4095** Form 2 rebuilds all indices in all databases that use the named
4096** collating function. Forms 3 and 4 rebuild the named index or all
4097** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004098*/
4099#ifndef SQLITE_OMIT_REINDEX
4100void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4101 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4102 char *z; /* Name of a table or index */
4103 const char *zDb; /* Name of the database */
4104 Table *pTab; /* A table in the database */
4105 Index *pIndex; /* An index associated with pTab */
4106 int iDb; /* The database index number */
4107 sqlite3 *db = pParse->db; /* The database connection */
4108 Token *pObjName; /* Name of the table or index to be reindexed */
4109
danielk197733a5edc2005-01-27 00:22:02 +00004110 /* Read the database schema. If an error occurs, leave an error message
4111 ** and code in pParse and return NULL. */
4112 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004113 return;
danielk197733a5edc2005-01-27 00:22:02 +00004114 }
4115
drh8af73d42009-05-13 22:58:28 +00004116 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004117 reindexDatabases(pParse, 0);
4118 return;
drhd3001712009-05-12 17:46:53 +00004119 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004120 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004121 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004122 zColl = sqlite3NameFromToken(pParse->db, pName1);
4123 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004124 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004125 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004126 reindexDatabases(pParse, zColl);
4127 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004128 return;
4129 }
drh633e6d52008-07-28 19:34:53 +00004130 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004131 }
4132 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4133 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004134 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004135 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004136 zDb = db->aDb[iDb].zName;
4137 pTab = sqlite3FindTable(db, z, zDb);
4138 if( pTab ){
4139 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004140 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004141 return;
4142 }
4143 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004144 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004145 if( pIndex ){
4146 sqlite3BeginWriteOperation(pParse, 0, iDb);
4147 sqlite3RefillIndex(pParse, pIndex, -1);
4148 return;
4149 }
4150 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4151}
4152#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004153
4154/*
drh2ec2fb22013-11-06 19:59:23 +00004155** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004156**
drh2ec2fb22013-11-06 19:59:23 +00004157** The KeyInfo structure for an index is cached in the Index object.
4158** So there might be multiple references to the returned pointer. The
4159** caller should not try to modify the KeyInfo object.
4160**
4161** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4162** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004163*/
drh2ec2fb22013-11-06 19:59:23 +00004164KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004165 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004166#ifndef SQLITE_OMIT_SHARED_CACHE
4167 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4168 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4169 pIdx->pKeyInfo = 0;
4170 }
4171#endif
drh2ec2fb22013-11-06 19:59:23 +00004172 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004173 int i;
4174 int nCol = pIdx->nColumn;
4175 int nKey = pIdx->nKeyCol;
4176 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004177 if( pIdx->uniqNotNull ){
4178 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4179 }else{
4180 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4181 }
4182 if( pKey ){
4183 assert( sqlite3KeyInfoIsWriteable(pKey) );
4184 for(i=0; i<nCol; i++){
4185 char *zColl = pIdx->azColl[i];
drh4308e342013-11-11 16:55:52 +00004186 if( NEVER(zColl==0) ) zColl = "BINARY";
drh2ec2fb22013-11-06 19:59:23 +00004187 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
4188 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4189 }
4190 if( pParse->nErr ){
4191 sqlite3KeyInfoUnref(pKey);
4192 }else{
4193 pIdx->pKeyInfo = pKey;
4194 }
danielk1977b3bf5562006-01-10 17:58:23 +00004195 }
danielk1977b3bf5562006-01-10 17:58:23 +00004196 }
drh2ec2fb22013-11-06 19:59:23 +00004197 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004198}