blob: c94c5a1310ff363ff42f3072a67fda7e83564f86 [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/*
drha7ab6d82014-07-21 15:44:39 +0000117** Return TRUE if the given yDbMask object is empty - if it contains no
118** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
119** macros when SQLITE_MAX_ATTACHED is greater than 30.
120*/
121#if SQLITE_MAX_ATTACHED>30
122int sqlite3DbMaskAllZero(yDbMask m){
123 int i;
124 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
125 return 1;
126}
127#endif
128
129/*
drh75897232000-05-29 14:26:00 +0000130** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000131** parsed and a VDBE program to execute that statement has been
132** prepared. This routine puts the finishing touches on the
133** VDBE program and resets the pParse structure for the next
134** parse.
drh75897232000-05-29 14:26:00 +0000135**
136** Note that if an error occurred, it might be the case that
137** no VDBE code was generated.
138*/
drh80242052004-06-09 00:48:12 +0000139void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000140 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000141 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000142
danf78baaf2012-12-06 19:37:22 +0000143 assert( pParse->pToplevel==0 );
drh17435752007-08-16 04:30:38 +0000144 db = pParse->db;
145 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000146 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000147 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000148
drh80242052004-06-09 00:48:12 +0000149 /* Begin by generating some termination code at the end of the
150 ** vdbe program
151 */
drh80242052004-06-09 00:48:12 +0000152 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000153 assert( !pParse->isMultiWrite
154 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000155 if( v ){
drh61019c72014-01-04 16:49:02 +0000156 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
drh66a51672008-01-03 00:01:23 +0000157 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000158
159 /* The cookie mask contains one bit for each database file open.
160 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
161 ** set for each database that is used. Generate code to start a
162 ** transaction on each used database and to verify the schema cookie
163 ** on each used database.
164 */
drha7ab6d82014-07-21 15:44:39 +0000165 if( db->mallocFailed==0
166 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
167 ){
drhaceb31b2014-02-08 01:40:27 +0000168 int iDb, i;
169 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
170 sqlite3VdbeJumpHere(v, 0);
drha7ab6d82014-07-21 15:44:39 +0000171 for(iDb=0; iDb<db->nDb; iDb++){
172 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000173 sqlite3VdbeUsesBtree(v, iDb);
drhb22f7c82014-02-06 23:56:27 +0000174 sqlite3VdbeAddOp4Int(v,
175 OP_Transaction, /* Opcode */
176 iDb, /* P1 */
drha7ab6d82014-07-21 15:44:39 +0000177 DbMaskTest(pParse->writeMask,iDb), /* P2 */
drhb22f7c82014-02-06 23:56:27 +0000178 pParse->cookieValue[iDb], /* P3 */
179 db->aDb[iDb].pSchema->iGeneration /* P4 */
180 );
181 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
drh80242052004-06-09 00:48:12 +0000182 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000183#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000184 for(i=0; i<pParse->nVtabLock; i++){
185 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
186 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000187 }
drhf30a9692013-11-15 01:10:18 +0000188 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000189#endif
danielk1977c00da102006-01-07 13:21:04 +0000190
191 /* Once all the cookies have been verified and transactions opened,
192 ** obtain the required table-locks. This is a no-op unless the
193 ** shared-cache feature is enabled.
194 */
195 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000196
197 /* Initialize any AUTOINCREMENT data structures required.
198 */
199 sqlite3AutoincrementBegin(pParse);
200
drhf30a9692013-11-15 01:10:18 +0000201 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000202 if( pParse->pConstExpr ){
203 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000204 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000205 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000206 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000207 }
208 }
209
drh0b9f50d2009-06-23 20:28:53 +0000210 /* Finally, jump back to the beginning of the executable code. */
drhaceb31b2014-02-08 01:40:27 +0000211 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
drh80242052004-06-09 00:48:12 +0000212 }
drh71c697e2004-08-08 23:39:19 +0000213 }
214
drh3f7d4e42004-07-24 14:35:58 +0000215
drh80242052004-06-09 00:48:12 +0000216 /* Get the VDBE program ready for execution
217 */
drh04491712009-05-13 17:21:13 +0000218 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000219 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000220 /* A minimum of one cursor is required if autoincrement is used
221 * See ticket [a696379c1f08866] */
222 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000223 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000224 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000225 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000226 }else{
drh483750b2003-01-29 18:46:51 +0000227 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000228 }
drha226d052002-09-25 19:04:07 +0000229 pParse->nTab = 0;
230 pParse->nMem = 0;
231 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000232 pParse->nVar = 0;
drha7ab6d82014-07-21 15:44:39 +0000233 DbMaskZero(pParse->cookieMask);
drh75897232000-05-29 14:26:00 +0000234}
235
236/*
drh205f48e2004-11-05 00:43:11 +0000237** Run the parser and code generator recursively in order to generate
238** code for the SQL statement given onto the end of the pParse context
239** currently under construction. When the parser is run recursively
240** this way, the final OP_Halt is not appended and other initialization
241** and finalization steps are omitted because those are handling by the
242** outermost parser.
243**
244** Not everything is nestable. This facility is designed to permit
245** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000246** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000247*/
248void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
249 va_list ap;
250 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000251 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000252 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000253# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
254 char saveBuf[SAVE_SZ];
255
drh205f48e2004-11-05 00:43:11 +0000256 if( pParse->nErr ) return;
257 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
258 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000259 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000260 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000261 if( zSql==0 ){
262 return; /* A malloc must have failed */
263 }
drh205f48e2004-11-05 00:43:11 +0000264 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000265 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
266 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000267 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000268 sqlite3DbFree(db, zErrMsg);
269 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000270 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000271 pParse->nested--;
272}
273
drhd4530972014-09-09 14:47:53 +0000274#if SQLITE_USER_AUTHENTICATION
275/*
276** Return TRUE if zTable is the name of the system table that stores the
277** list of users and their access credentials.
278*/
279int sqlite3UserAuthTable(const char *zTable){
280 return sqlite3_stricmp(zTable, "sqlite_user")==0;
281}
282#endif
283
drh205f48e2004-11-05 00:43:11 +0000284/*
danielk19778a414492004-06-29 08:59:35 +0000285** Locate the in-memory structure that describes a particular database
286** table given the name of that table and (optionally) the name of the
287** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000288**
danielk19778a414492004-06-29 08:59:35 +0000289** If zDatabase is 0, all databases are searched for the table and the
290** first matching table is returned. (No checking for duplicate table
291** names is done.) The search order is TEMP first, then MAIN, then any
292** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000293**
danielk19774adee202004-05-08 08:23:19 +0000294** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000295*/
drh9bb575f2004-09-06 17:24:11 +0000296Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000297 Table *p = 0;
298 int i;
drh645f63e2004-06-22 13:22:40 +0000299 assert( zName!=0 );
drh21206082011-04-04 18:22:02 +0000300 /* All mutexes are required for schema access. Make sure we hold them. */
301 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
drhd4530972014-09-09 14:47:53 +0000302#if SQLITE_USER_AUTHENTICATION
303 /* Only the admin user is allowed to know that the sqlite_user table
304 ** exists */
drhe933b832014-09-10 17:34:28 +0000305 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
306 return 0;
307 }
drhd4530972014-09-09 14:47:53 +0000308#endif
danielk197753c0f742005-03-29 03:10:59 +0000309 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000310 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000311 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000312 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000313 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
drhd24cc422003-03-27 12:51:24 +0000314 if( p ) break;
315 }
drh74e24cd2002-01-09 03:19:59 +0000316 return p;
drh75897232000-05-29 14:26:00 +0000317}
318
319/*
danielk19778a414492004-06-29 08:59:35 +0000320** Locate the in-memory structure that describes a particular database
321** table given the name of that table and (optionally) the name of the
322** database containing the table. Return NULL if not found. Also leave an
323** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000324**
danielk19778a414492004-06-29 08:59:35 +0000325** The difference between this routine and sqlite3FindTable() is that this
326** routine leaves an error message in pParse->zErrMsg where
327** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000328*/
drhca424112008-01-25 15:04:48 +0000329Table *sqlite3LocateTable(
330 Parse *pParse, /* context in which to report errors */
331 int isView, /* True if looking for a VIEW rather than a TABLE */
332 const char *zName, /* Name of the table we are looking for */
333 const char *zDbase /* Name of the database. Might be NULL */
334){
drha69d9162003-04-17 22:57:53 +0000335 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000336
danielk19778a414492004-06-29 08:59:35 +0000337 /* Read the database schema. If an error occurs, leave an error message
338 ** and code in pParse and return NULL. */
339 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
340 return 0;
341 }
342
danielk19774adee202004-05-08 08:23:19 +0000343 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000344 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000345 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000346 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000347 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000348 }else{
drhca424112008-01-25 15:04:48 +0000349 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000350 }
drha6ecd332004-06-10 00:29:09 +0000351 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000352 }
drhe933b832014-09-10 17:34:28 +0000353#if SQLITE_USER_AUTHENICATION
354 else if( pParse->db->auth.authLevel<UAUTH_User ){
355 sqlite3ErrorMsg(pParse, "user not authenticated");
356 p = 0;
357 }
358#endif
drha69d9162003-04-17 22:57:53 +0000359 return p;
360}
361
362/*
dan41fb5cd2012-10-04 19:33:00 +0000363** Locate the table identified by *p.
364**
365** This is a wrapper around sqlite3LocateTable(). The difference between
366** sqlite3LocateTable() and this function is that this function restricts
367** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
368** non-NULL if it is part of a view or trigger program definition. See
369** sqlite3FixSrcList() for details.
370*/
371Table *sqlite3LocateTableItem(
372 Parse *pParse,
373 int isView,
374 struct SrcList_item *p
375){
376 const char *zDb;
377 assert( p->pSchema==0 || p->zDatabase==0 );
378 if( p->pSchema ){
379 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
380 zDb = pParse->db->aDb[iDb].zName;
381 }else{
382 zDb = p->zDatabase;
383 }
384 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
385}
386
387/*
drha69d9162003-04-17 22:57:53 +0000388** Locate the in-memory structure that describes
389** a particular index given the name of that index
390** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000391** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000392**
393** If zDatabase is 0, all databases are searched for the
394** table and the first matching index is returned. (No checking
395** for duplicate index names is done.) The search order is
396** TEMP first, then MAIN, then any auxiliary databases added
397** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000398*/
drh9bb575f2004-09-06 17:24:11 +0000399Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000400 Index *p = 0;
401 int i;
drh21206082011-04-04 18:22:02 +0000402 /* All mutexes are required for schema access. Make sure we hold them. */
403 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000404 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000405 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000406 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000407 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000408 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000409 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000410 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000411 if( p ) break;
412 }
drh74e24cd2002-01-09 03:19:59 +0000413 return p;
drh75897232000-05-29 14:26:00 +0000414}
415
416/*
drh956bc922004-07-24 17:38:29 +0000417** Reclaim the memory used by an index
418*/
dan1feeaed2010-07-23 15:41:47 +0000419static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000420#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000421 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000422#endif
drh2ec2fb22013-11-06 19:59:23 +0000423 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
drh1fe05372013-07-31 18:12:26 +0000424 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000425 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000426 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh633e6d52008-07-28 19:34:53 +0000427 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000428}
429
430/*
drhc96d8532005-05-03 12:30:33 +0000431** For the index called zIdxName which is found in the database iDb,
432** unlike that index from its Table then remove the index from
433** the index hash table and free all memory structures associated
434** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000435*/
drh9bb575f2004-09-06 17:24:11 +0000436void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000437 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000438 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000439
drh21206082011-04-04 18:22:02 +0000440 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
441 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000442 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000443 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000444 if( pIndex->pTable->pIndex==pIndex ){
445 pIndex->pTable->pIndex = pIndex->pNext;
446 }else{
447 Index *p;
drh04491712009-05-13 17:21:13 +0000448 /* Justification of ALWAYS(); The index must be on the list of
449 ** indices. */
450 p = pIndex->pTable->pIndex;
451 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
452 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000453 p->pNext = pIndex->pNext;
454 }
drh5e00f6c2001-09-13 13:46:56 +0000455 }
dan1feeaed2010-07-23 15:41:47 +0000456 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000457 }
drh956bc922004-07-24 17:38:29 +0000458 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000459}
460
461/*
drh81028a42012-05-15 18:28:27 +0000462** Look through the list of open database files in db->aDb[] and if
463** any have been closed, remove them from the list. Reallocate the
464** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000465**
drh81028a42012-05-15 18:28:27 +0000466** Entry 0 (the "main" database) and entry 1 (the "temp" database)
467** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000468*/
drh81028a42012-05-15 18:28:27 +0000469void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000470 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000471 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000472 struct Db *pDb = &db->aDb[i];
473 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000474 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000475 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000476 continue;
477 }
478 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000479 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000480 }
drh8bf8dc92003-05-17 17:35:10 +0000481 j++;
drh1c2d8412003-03-31 00:30:47 +0000482 }
483 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
484 db->nDb = j;
485 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
486 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000487 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000488 db->aDb = db->aDbStatic;
489 }
drhe0bc4042002-06-25 01:09:11 +0000490}
491
492/*
drh81028a42012-05-15 18:28:27 +0000493** Reset the schema for the database at index iDb. Also reset the
494** TEMP schema.
495*/
496void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000497 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000498 assert( iDb<db->nDb );
499
500 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000501 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000502 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
503 assert( pDb->pSchema!=0 );
504 sqlite3SchemaClear(pDb->pSchema);
505
506 /* If any database other than TEMP is reset, then also reset TEMP
507 ** since TEMP might be holding triggers that reference tables in the
508 ** other database.
509 */
510 if( iDb!=1 ){
511 pDb = &db->aDb[1];
512 assert( pDb->pSchema!=0 );
513 sqlite3SchemaClear(pDb->pSchema);
514 }
515 return;
516}
517
518/*
519** Erase all schema information from all attached databases (including
520** "main" and "temp") for a single database connection.
521*/
522void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
523 int i;
524 sqlite3BtreeEnterAll(db);
525 for(i=0; i<db->nDb; i++){
526 Db *pDb = &db->aDb[i];
527 if( pDb->pSchema ){
528 sqlite3SchemaClear(pDb->pSchema);
529 }
530 }
531 db->flags &= ~SQLITE_InternChanges;
532 sqlite3VtabUnlockList(db);
533 sqlite3BtreeLeaveAll(db);
534 sqlite3CollapseDatabaseArray(db);
535}
536
537/*
drhe0bc4042002-06-25 01:09:11 +0000538** This routine is called when a commit occurs.
539*/
drh9bb575f2004-09-06 17:24:11 +0000540void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000541 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000542}
543
544/*
dand46def72010-07-24 11:28:28 +0000545** Delete memory allocated for the column names of a table or view (the
546** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000547*/
dand46def72010-07-24 11:28:28 +0000548static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000549 int i;
550 Column *pCol;
551 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000552 if( (pCol = pTable->aCol)!=0 ){
553 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000554 sqlite3DbFree(db, pCol->zName);
555 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000556 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000557 sqlite3DbFree(db, pCol->zType);
558 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000559 }
drh633e6d52008-07-28 19:34:53 +0000560 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000561 }
drh956bc922004-07-24 17:38:29 +0000562}
563
564/*
drh75897232000-05-29 14:26:00 +0000565** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000566** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000567**
568** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000569** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000570** memory structures of the indices and foreign keys associated with
571** the table.
drh29ddd3a2012-05-15 12:49:32 +0000572**
573** The db parameter is optional. It is needed if the Table object
574** contains lookaside memory. (Table objects in the schema do not use
575** lookaside memory, but some ephemeral Table objects do.) Or the
576** db parameter can be used with db->pnBytesFreed to measure the memory
577** used by the Table object.
drh75897232000-05-29 14:26:00 +0000578*/
dan1feeaed2010-07-23 15:41:47 +0000579void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000580 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000581 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000582
dand46def72010-07-24 11:28:28 +0000583 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000584
drhed8a3bb2005-06-06 21:19:56 +0000585 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000586 if( !pTable ) return;
587 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000588
drh29ddd3a2012-05-15 12:49:32 +0000589 /* Record the number of outstanding lookaside allocations in schema Tables
590 ** prior to doing any free() operations. Since schema Tables do not use
591 ** lookaside, this number should not change. */
592 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
593 db->lookaside.nOut : 0 );
594
dand46def72010-07-24 11:28:28 +0000595 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000596 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
597 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000598 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000599 if( !db || db->pnBytesFreed==0 ){
600 char *zName = pIndex->zName;
601 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000602 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000603 );
drh21206082011-04-04 18:22:02 +0000604 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000605 assert( pOld==pIndex || pOld==0 );
606 }
607 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000608 }
609
dan1da40a32009-09-19 17:00:31 +0000610 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000611 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000612
613 /* Delete the Table structure itself.
614 */
dand46def72010-07-24 11:28:28 +0000615 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000616 sqlite3DbFree(db, pTable->zName);
617 sqlite3DbFree(db, pTable->zColAff);
618 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000619#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000620 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000621#endif
drh078e4082010-07-28 19:17:51 +0000622#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000623 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000624#endif
drh633e6d52008-07-28 19:34:53 +0000625 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000626
627 /* Verify that no lookaside memory was used by schema tables */
628 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000629}
630
631/*
drh5edc3122001-09-13 21:53:09 +0000632** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000633** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000634*/
drh9bb575f2004-09-06 17:24:11 +0000635void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000636 Table *p;
drh956bc922004-07-24 17:38:29 +0000637 Db *pDb;
638
drhd229ca92002-01-09 13:30:41 +0000639 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000640 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000641 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000642 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000643 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000644 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000645 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000646 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000647 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000648}
649
650/*
drha99db3b2004-06-19 14:49:12 +0000651** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000652** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000653** is obtained from sqliteMalloc() and must be freed by the calling
654** function.
drh75897232000-05-29 14:26:00 +0000655**
drh24fb6272009-05-01 21:13:36 +0000656** Any quotation marks (ex: "name", 'name', [name], or `name`) that
657** surround the body of the token are removed.
658**
drhc96d8532005-05-03 12:30:33 +0000659** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000660** are not \000 terminated and are not persistent. The returned string
661** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000662*/
drh17435752007-08-16 04:30:38 +0000663char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000664 char *zName;
665 if( pName ){
drh17435752007-08-16 04:30:38 +0000666 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000667 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000668 }else{
669 zName = 0;
670 }
drh75897232000-05-29 14:26:00 +0000671 return zName;
672}
673
674/*
danielk1977cbb18d22004-05-28 11:37:27 +0000675** Open the sqlite_master table stored in database number iDb for
676** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000677*/
danielk1977c00da102006-01-07 13:21:04 +0000678void sqlite3OpenMasterTable(Parse *p, int iDb){
679 Vdbe *v = sqlite3GetVdbe(p);
680 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000681 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000682 if( p->nTab==0 ){
683 p->nTab = 1;
684 }
drhe0bc4042002-06-25 01:09:11 +0000685}
686
687/*
danielk197704103022009-02-03 16:51:24 +0000688** Parameter zName points to a nul-terminated buffer containing the name
689** of a database ("main", "temp" or the name of an attached db). This
690** function returns the index of the named database in db->aDb[], or
691** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000692*/
danielk197704103022009-02-03 16:51:24 +0000693int sqlite3FindDbName(sqlite3 *db, const char *zName){
694 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000695 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000696 Db *pDb;
697 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000698 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000699 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000700 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000701 break;
drh73c42a12004-11-20 18:13:10 +0000702 }
danielk1977cbb18d22004-05-28 11:37:27 +0000703 }
704 }
danielk1977576ec6b2005-01-21 11:55:25 +0000705 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000706}
707
danielk197704103022009-02-03 16:51:24 +0000708/*
709** The token *pName contains the name of a database (either "main" or
710** "temp" or the name of an attached db). This routine returns the
711** index of the named database in db->aDb[], or -1 if the named db
712** does not exist.
713*/
714int sqlite3FindDb(sqlite3 *db, Token *pName){
715 int i; /* Database number */
716 char *zName; /* Name we are searching for */
717 zName = sqlite3NameFromToken(db, pName);
718 i = sqlite3FindDbName(db, zName);
719 sqlite3DbFree(db, zName);
720 return i;
721}
722
drh0e3d7472004-06-19 17:33:07 +0000723/* The table or view or trigger name is passed to this routine via tokens
724** pName1 and pName2. If the table name was fully qualified, for example:
725**
726** CREATE TABLE xxx.yyy (...);
727**
728** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
729** the table name is not fully qualified, i.e.:
730**
731** CREATE TABLE yyy(...);
732**
733** Then pName1 is set to "yyy" and pName2 is "".
734**
735** This routine sets the *ppUnqual pointer to point at the token (pName1 or
736** pName2) that stores the unqualified table name. The index of the
737** database "xxx" is returned.
738*/
danielk1977ef2cb632004-05-29 02:37:19 +0000739int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000740 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000741 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000742 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
743 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000744){
drh0e3d7472004-06-19 17:33:07 +0000745 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000746 sqlite3 *db = pParse->db;
747
drhc4a64fa2009-05-11 20:53:28 +0000748 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000749 if( db->init.busy ) {
750 sqlite3ErrorMsg(pParse, "corrupt database");
751 pParse->nErr++;
752 return -1;
753 }
danielk1977cbb18d22004-05-28 11:37:27 +0000754 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000755 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000756 if( iDb<0 ){
757 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
758 pParse->nErr++;
759 return -1;
760 }
761 }else{
762 assert( db->init.iDb==0 || db->init.busy );
763 iDb = db->init.iDb;
764 *pUnqual = pName1;
765 }
766 return iDb;
767}
768
769/*
danielk1977d8123362004-06-12 09:25:12 +0000770** This routine is used to check if the UTF-8 string zName is a legal
771** unqualified name for a new schema object (table, index, view or
772** trigger). All names are legal except those that begin with the string
773** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
774** is reserved for internal use.
775*/
776int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000777 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000778 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000779 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000780 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
781 return SQLITE_ERROR;
782 }
783 return SQLITE_OK;
784}
785
786/*
drh44156282013-10-23 22:23:03 +0000787** Return the PRIMARY KEY index of a table
788*/
789Index *sqlite3PrimaryKeyIndex(Table *pTab){
790 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000791 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000792 return p;
793}
794
795/*
796** Return the column of index pIdx that corresponds to table
797** column iCol. Return -1 if not found.
798*/
799i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
800 int i;
801 for(i=0; i<pIdx->nColumn; i++){
802 if( iCol==pIdx->aiColumn[i] ) return i;
803 }
804 return -1;
805}
806
807/*
drh75897232000-05-29 14:26:00 +0000808** Begin constructing a new table representation in memory. This is
809** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000810** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000811** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000812** flag is true if the table should be stored in the auxiliary database
813** file instead of in the main database file. This is normally the case
814** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000815** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000816**
drhf57b3392001-10-08 13:22:32 +0000817** The new table record is initialized and put in pParse->pNewTable.
818** As more of the CREATE TABLE statement is parsed, additional action
819** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000820** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000821** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000822*/
danielk19774adee202004-05-08 08:23:19 +0000823void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000824 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000825 Token *pName1, /* First part of the name of the table or view */
826 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000827 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000828 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000829 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000830 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000831){
drh75897232000-05-29 14:26:00 +0000832 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000833 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000834 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000835 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000836 int iDb; /* Database number to create the table in */
837 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000838
danielk1977cbb18d22004-05-28 11:37:27 +0000839 /* The table or view name to create is passed to this routine via tokens
840 ** pName1 and pName2. If the table name was fully qualified, for example:
841 **
842 ** CREATE TABLE xxx.yyy (...);
843 **
844 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
845 ** the table name is not fully qualified, i.e.:
846 **
847 ** CREATE TABLE yyy(...);
848 **
849 ** Then pName1 is set to "yyy" and pName2 is "".
850 **
851 ** The call below sets the pName pointer to point at the token (pName1 or
852 ** pName2) that stores the unqualified table name. The variable iDb is
853 ** set to the index of the database that the table or view is to be
854 ** created in.
855 */
danielk1977ef2cb632004-05-29 02:37:19 +0000856 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000857 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000858 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
859 /* If creating a temp table, the name may not be qualified. Unless
860 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000861 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000862 return;
863 }
danielk197753c0f742005-03-29 03:10:59 +0000864 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000865
866 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000867 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000868 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000869 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000870 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000871 }
drh1d85d932004-02-14 23:05:52 +0000872 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000873#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000874 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000875 {
876 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000877 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000878 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000879 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000880 }
drhe5f9c642003-01-13 23:27:31 +0000881 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000882 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000883 code = SQLITE_CREATE_TEMP_VIEW;
884 }else{
885 code = SQLITE_CREATE_VIEW;
886 }
887 }else{
danielk197753c0f742005-03-29 03:10:59 +0000888 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000889 code = SQLITE_CREATE_TEMP_TABLE;
890 }else{
891 code = SQLITE_CREATE_TABLE;
892 }
893 }
danielk1977f1a381e2006-06-16 08:01:02 +0000894 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000895 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000896 }
897 }
898#endif
drhf57b3392001-10-08 13:22:32 +0000899
drhf57b3392001-10-08 13:22:32 +0000900 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000901 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000902 ** it does. The exception is if the statement being parsed was passed
903 ** to an sqlite3_declare_vtab() call. In that case only the column names
904 ** and types will be used, so there is no need to test for namespace
905 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000906 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000907 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000908 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000909 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
910 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000911 }
dana16d1062010-09-28 17:37:28 +0000912 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000913 if( pTable ){
914 if( !noErr ){
915 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000916 }else{
917 assert( !db->init.busy );
918 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000919 }
920 goto begin_table_error;
921 }
drh8a8a0d12010-09-28 20:26:44 +0000922 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000923 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
924 goto begin_table_error;
925 }
drh75897232000-05-29 14:26:00 +0000926 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000927
danielk197726783a52007-08-29 14:06:22 +0000928 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000929 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000930 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000931 pParse->rc = SQLITE_NOMEM;
932 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000933 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000934 }
drh75897232000-05-29 14:26:00 +0000935 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000936 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000937 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000938 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000939 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000940 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000941 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000942
drh4794f732004-11-05 17:17:50 +0000943 /* If this is the magic sqlite_sequence table used by autoincrement,
944 ** then record a pointer to this table in the main database structure
945 ** so that INSERT can find the table easily.
946 */
947#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000948 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000949 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000950 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000951 }
952#endif
953
drh17f71932002-02-21 12:01:27 +0000954 /* Begin generating the code that will insert the table record into
955 ** the SQLITE_MASTER table. Note in particular that we must go ahead
956 ** and allocate the record number for the table entry now. Before any
957 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
958 ** indices to be created and the table record must come before the
959 ** indices. Hence, the record number for the table must be allocated
960 ** now.
961 */
danielk19774adee202004-05-08 08:23:19 +0000962 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000963 int j1;
drhe321c292006-01-12 01:56:43 +0000964 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000965 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000966 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000967
danielk197720b1eaf2006-07-26 16:22:14 +0000968#ifndef SQLITE_OMIT_VIRTUALTABLE
969 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000970 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000971 }
972#endif
973
danielk197736963fd2005-02-19 08:18:05 +0000974 /* If the file format and encoding in the database have not been set,
975 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000976 */
drhb7654112008-01-12 12:48:07 +0000977 reg1 = pParse->regRowid = ++pParse->nMem;
978 reg2 = pParse->regRoot = ++pParse->nMem;
979 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000980 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000981 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +0000982 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +0000983 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000984 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000985 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000986 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000987 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000988 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +0000989 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000990
drh4794f732004-11-05 17:17:50 +0000991 /* This just creates a place-holder record in the sqlite_master table.
992 ** The record created does not contain anything yet. It will be replaced
993 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000994 **
drh0fa991b2009-03-21 16:19:26 +0000995 ** The rowid for the new entry is left in register pParse->regRowid.
996 ** The root page number of the new table is left in reg pParse->regRoot.
997 ** The rowid and root page number values are needed by the code that
998 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +0000999 */
danielk1977f1a381e2006-06-16 08:01:02 +00001000#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1001 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001002 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001003 }else
1004#endif
1005 {
drh8a120f82013-11-01 17:59:53 +00001006 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001007 }
danielk1977c00da102006-01-07 13:21:04 +00001008 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001009 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1010 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1011 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1012 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001013 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001014 }
drh23bf66d2004-12-14 03:34:34 +00001015
1016 /* Normal (non-error) return. */
1017 return;
1018
1019 /* If an error occurs, we jump here */
1020begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001021 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001022 return;
drh75897232000-05-29 14:26:00 +00001023}
1024
1025/*
danielk1977c60e9b82005-01-31 12:42:29 +00001026** This macro is used to compare two strings in a case-insensitive manner.
1027** It is slightly faster than calling sqlite3StrICmp() directly, but
1028** produces larger code.
1029**
1030** WARNING: This macro is not compatible with the strcmp() family. It
1031** returns true if the two strings are equal, otherwise false.
1032*/
1033#define STRICMP(x, y) (\
1034sqlite3UpperToLower[*(unsigned char *)(x)]== \
1035sqlite3UpperToLower[*(unsigned char *)(y)] \
1036&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1037
1038/*
drh75897232000-05-29 14:26:00 +00001039** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001040**
1041** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001042** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001043** first to get things going. Then this routine is called for each
1044** column.
drh75897232000-05-29 14:26:00 +00001045*/
danielk19774adee202004-05-08 08:23:19 +00001046void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001047 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001048 int i;
drha99db3b2004-06-19 14:49:12 +00001049 char *z;
drhc9b84a12002-06-20 11:36:48 +00001050 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001051 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001052 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001053#if SQLITE_MAX_COLUMN
1054 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001055 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1056 return;
1057 }
drhbb4957f2008-03-20 14:03:29 +00001058#endif
danielk1977ae74e032008-12-23 11:11:51 +00001059 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001060 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001061 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001062 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001063 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001064 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001065 return;
1066 }
1067 }
drh75897232000-05-29 14:26:00 +00001068 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001069 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001070 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001071 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001072 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001073 return;
1074 }
drh6d4abfb2001-10-22 02:58:08 +00001075 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001076 }
drhc9b84a12002-06-20 11:36:48 +00001077 pCol = &p->aCol[p->nCol];
1078 memset(pCol, 0, sizeof(p->aCol[0]));
1079 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001080
1081 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001082 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1083 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001084 */
danielk19774f057f92004-06-08 00:02:33 +00001085 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001086 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001087 p->nCol++;
drh75897232000-05-29 14:26:00 +00001088}
1089
1090/*
drh382c0242001-10-06 16:33:02 +00001091** This routine is called by the parser while in the middle of
1092** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1093** been seen on a column. This routine sets the notNull flag on
1094** the column currently under construction.
1095*/
danielk19774adee202004-05-08 08:23:19 +00001096void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001097 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001098 p = pParse->pNewTable;
1099 if( p==0 || NEVER(p->nCol<1) ) return;
1100 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001101}
1102
1103/*
danielk197752a83fb2005-01-31 12:56:44 +00001104** Scan the column type name zType (length nType) and return the
1105** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001106**
1107** This routine does a case-independent search of zType for the
1108** substrings in the following table. If one of the substrings is
1109** found, the corresponding affinity is returned. If zType contains
1110** more than one of the substrings, entries toward the top of
1111** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001112** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001113**
1114** Substring | Affinity
1115** --------------------------------
1116** 'INT' | SQLITE_AFF_INTEGER
1117** 'CHAR' | SQLITE_AFF_TEXT
1118** 'CLOB' | SQLITE_AFF_TEXT
1119** 'TEXT' | SQLITE_AFF_TEXT
1120** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001121** 'REAL' | SQLITE_AFF_REAL
1122** 'FLOA' | SQLITE_AFF_REAL
1123** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001124**
1125** If none of the substrings in the above table are found,
1126** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001127*/
drhfdaac672013-10-04 15:30:21 +00001128char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001129 u32 h = 0;
1130 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001131 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001132
drhfdaac672013-10-04 15:30:21 +00001133 if( zIn==0 ) return aff;
1134 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001135 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001136 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001137 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001138 aff = SQLITE_AFF_TEXT;
1139 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001140 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1141 aff = SQLITE_AFF_TEXT;
1142 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1143 aff = SQLITE_AFF_TEXT;
1144 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001145 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001146 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001147 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001148#ifndef SQLITE_OMIT_FLOATING_POINT
1149 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1150 && aff==SQLITE_AFF_NUMERIC ){
1151 aff = SQLITE_AFF_REAL;
1152 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1153 && aff==SQLITE_AFF_NUMERIC ){
1154 aff = SQLITE_AFF_REAL;
1155 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1156 && aff==SQLITE_AFF_NUMERIC ){
1157 aff = SQLITE_AFF_REAL;
1158#endif
danielk1977201f7162005-02-01 02:13:29 +00001159 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001160 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001161 break;
danielk197752a83fb2005-01-31 12:56:44 +00001162 }
1163 }
drhd3037a42013-10-04 18:29:25 +00001164
1165 /* If pszEst is not NULL, store an estimate of the field size. The
1166 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001167 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001168 *pszEst = 1; /* default size is approx 4 bytes */
1169 if( aff<=SQLITE_AFF_NONE ){
1170 if( zChar ){
1171 while( zChar[0] ){
1172 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001173 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001174 sqlite3GetInt32(zChar, &v);
1175 v = v/4 + 1;
1176 if( v>255 ) v = 255;
1177 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1178 break;
1179 }
1180 zChar++;
drhfdaac672013-10-04 15:30:21 +00001181 }
drhd3037a42013-10-04 18:29:25 +00001182 }else{
1183 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001184 }
drhfdaac672013-10-04 15:30:21 +00001185 }
1186 }
danielk1977b3dff962005-02-01 01:21:55 +00001187 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001188}
1189
1190/*
drh382c0242001-10-06 16:33:02 +00001191** This routine is called by the parser while in the middle of
1192** parsing a CREATE TABLE statement. The pFirst token is the first
1193** token in the sequence of tokens that describe the type of the
1194** column currently under construction. pLast is the last token
1195** in the sequence. Use this information to construct a string
1196** that contains the typename of the column and store that string
1197** in zType.
1198*/
drh487e2622005-06-25 18:42:14 +00001199void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001200 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001201 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001202
drhc4a64fa2009-05-11 20:53:28 +00001203 p = pParse->pNewTable;
1204 if( p==0 || NEVER(p->nCol<1) ) return;
1205 pCol = &p->aCol[p->nCol-1];
1206 assert( pCol->zType==0 );
1207 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001208 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001209}
1210
1211/*
danielk19777977a172004-11-09 12:44:37 +00001212** The expression is the default value for the most recently added column
1213** of the table currently under construction.
1214**
1215** Default value expressions must be constant. Raise an exception if this
1216** is not the case.
drhd9b02572001-04-15 00:37:09 +00001217**
1218** This routine is called by the parser while in the middle of
1219** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001220*/
drhb7916a72009-05-27 10:31:29 +00001221void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001222 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001223 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001224 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001225 p = pParse->pNewTable;
1226 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001227 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001228 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001229 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1230 pCol->zName);
1231 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001232 /* A copy of pExpr is used instead of the original, as pExpr contains
1233 ** tokens that point to volatile memory. The 'span' of the expression
1234 ** is required by pragma table_info.
1235 */
drh633e6d52008-07-28 19:34:53 +00001236 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001237 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1238 sqlite3DbFree(db, pCol->zDflt);
1239 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001240 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001241 }
danielk19777977a172004-11-09 12:44:37 +00001242 }
drhb7916a72009-05-27 10:31:29 +00001243 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001244}
1245
1246/*
drh4a324312001-12-21 14:30:42 +00001247** Designate the PRIMARY KEY for the table. pList is a list of names
1248** of columns that form the primary key. If pList is NULL, then the
1249** most recently added column of the table is the primary key.
1250**
1251** A table can have at most one primary key. If the table already has
1252** a primary key (and this is the second primary key) then create an
1253** error.
1254**
1255** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001256** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001257** field of the table under construction to be the index of the
1258** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1259** no INTEGER PRIMARY KEY.
1260**
1261** If the key is not an INTEGER PRIMARY KEY, then create a unique
1262** index for the key. No index is created for INTEGER PRIMARY KEYs.
1263*/
drh205f48e2004-11-05 00:43:11 +00001264void sqlite3AddPrimaryKey(
1265 Parse *pParse, /* Parsing context */
1266 ExprList *pList, /* List of field names to be indexed */
1267 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001268 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1269 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001270){
drh4a324312001-12-21 14:30:42 +00001271 Table *pTab = pParse->pNewTable;
1272 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001273 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001274 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001275 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001276 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001277 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001278 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001279 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001280 }
drh7d10d5a2008-08-20 16:35:10 +00001281 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001282 if( pList==0 ){
1283 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001284 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001285 zType = pTab->aCol[iCol].zType;
1286 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001287 }else{
drh8ea30bf2013-10-22 01:18:17 +00001288 nTerm = pList->nExpr;
1289 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001290 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001291 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001292 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1293 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001294 break;
1295 }
drh78100cc2003-08-23 22:40:53 +00001296 }
drh4a324312001-12-21 14:30:42 +00001297 }
1298 }
drh8ea30bf2013-10-22 01:18:17 +00001299 if( nTerm==1
1300 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1301 && sortOrder==SQLITE_SO_ASC
1302 ){
drh4a324312001-12-21 14:30:42 +00001303 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001304 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001305 assert( autoInc==0 || autoInc==1 );
1306 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001307 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001308 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001309#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001310 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1311 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001312#endif
drh4a324312001-12-21 14:30:42 +00001313 }else{
drhc6bd4e42013-11-02 14:37:18 +00001314 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001315 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001316 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001317 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001318 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001319 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001320 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drhc6bd4e42013-11-02 14:37:18 +00001321 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001322 }
drhe0194f22003-02-26 13:52:51 +00001323 pList = 0;
drh4a324312001-12-21 14:30:42 +00001324 }
drhe0194f22003-02-26 13:52:51 +00001325
1326primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001327 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001328 return;
drh4a324312001-12-21 14:30:42 +00001329}
1330
1331/*
drhffe07b22005-11-03 00:41:17 +00001332** Add a new CHECK constraint to the table currently under construction.
1333*/
1334void sqlite3AddCheckConstraint(
1335 Parse *pParse, /* Parsing context */
1336 Expr *pCheckExpr /* The check expression */
1337){
1338#ifndef SQLITE_OMIT_CHECK
1339 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001340 sqlite3 *db = pParse->db;
1341 if( pTab && !IN_DECLARE_VTAB
1342 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1343 ){
drh2938f922012-03-07 19:13:29 +00001344 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1345 if( pParse->constraintName.n ){
1346 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1347 }
drh33e619f2009-05-28 01:00:55 +00001348 }else
drhffe07b22005-11-03 00:41:17 +00001349#endif
drh33e619f2009-05-28 01:00:55 +00001350 {
drh2938f922012-03-07 19:13:29 +00001351 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001352 }
drhffe07b22005-11-03 00:41:17 +00001353}
1354
1355/*
drhd3d39e92004-05-20 22:16:29 +00001356** Set the collation function of the most recently parsed table column
1357** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001358*/
danielk197739002502007-11-12 09:50:26 +00001359void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001360 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001361 int i;
danielk197739002502007-11-12 09:50:26 +00001362 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001363 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001364
danielk1977b8cbb872006-06-19 05:33:45 +00001365 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001366 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001367 db = pParse->db;
1368 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001369 if( !zColl ) return;
1370
drhc4a64fa2009-05-11 20:53:28 +00001371 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001372 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001373 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001374 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001375
1376 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1377 ** then an index may have been created on this column before the
1378 ** collation type was added. Correct this if it is the case.
1379 */
1380 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001381 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001382 if( pIdx->aiColumn[0]==i ){
1383 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001384 }
1385 }
danielk197739002502007-11-12 09:50:26 +00001386 }else{
drh633e6d52008-07-28 19:34:53 +00001387 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001388 }
danielk19777cedc8d2004-06-10 10:50:08 +00001389}
1390
danielk1977466be562004-06-10 02:16:01 +00001391/*
1392** This function returns the collation sequence for database native text
1393** encoding identified by the string zName, length nName.
1394**
1395** If the requested collation sequence is not available, or not available
1396** in the database native encoding, the collation factory is invoked to
1397** request it. If the collation factory does not supply such a sequence,
1398** and the sequence is available in another text encoding, then that is
1399** returned instead.
1400**
1401** If no versions of the requested collations sequence are available, or
1402** another error occurs, NULL is returned and an error message written into
1403** pParse.
drha34001c2007-02-02 12:44:37 +00001404**
1405** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1406** invokes the collation factory if the named collation cannot be found
1407** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001408**
1409** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001410*/
drhc4a64fa2009-05-11 20:53:28 +00001411CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001412 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001413 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001414 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001415 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001416
drhc4a64fa2009-05-11 20:53:28 +00001417 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001418 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001419 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001420 }
1421
danielk19770202b292004-06-09 09:55:16 +00001422 return pColl;
1423}
1424
1425
drh8e2ca022002-06-17 17:07:19 +00001426/*
drh3f7d4e42004-07-24 14:35:58 +00001427** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001428**
1429** The schema cookie is used to determine when the schema for the
1430** database changes. After each schema change, the cookie value
1431** changes. When a process first reads the schema it records the
1432** cookie. Thereafter, whenever it goes to access the database,
1433** it checks the cookie to make sure the schema has not changed
1434** since it was last read.
1435**
1436** This plan is not completely bullet-proof. It is possible for
1437** the schema to change multiple times and for the cookie to be
1438** set back to prior value. But schema changes are infrequent
1439** and the probability of hitting the same cookie value is only
1440** 1 chance in 2^32. So we're safe enough.
1441*/
drh9cbf3422008-01-17 16:22:13 +00001442void sqlite3ChangeCookie(Parse *pParse, int iDb){
1443 int r1 = sqlite3GetTempReg(pParse);
1444 sqlite3 *db = pParse->db;
1445 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001446 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001447 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001448 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001449 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001450}
1451
1452/*
drh969fa7c2002-02-18 18:30:32 +00001453** Measure the number of characters needed to output the given
1454** identifier. The number returned includes any quotes used
1455** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001456**
1457** The estimate is conservative. It might be larger that what is
1458** really needed.
drh969fa7c2002-02-18 18:30:32 +00001459*/
1460static int identLength(const char *z){
1461 int n;
drh17f71932002-02-21 12:01:27 +00001462 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001463 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001464 }
drh234c39d2004-07-24 03:30:47 +00001465 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001466}
1467
1468/*
danielk19771b870de2009-03-14 08:37:23 +00001469** The first parameter is a pointer to an output buffer. The second
1470** parameter is a pointer to an integer that contains the offset at
1471** which to write into the output buffer. This function copies the
1472** nul-terminated string pointed to by the third parameter, zSignedIdent,
1473** to the specified offset in the buffer and updates *pIdx to refer
1474** to the first byte after the last byte written before returning.
1475**
1476** If the string zSignedIdent consists entirely of alpha-numeric
1477** characters, does not begin with a digit and is not an SQL keyword,
1478** then it is copied to the output buffer exactly as it is. Otherwise,
1479** it is quoted using double-quotes.
1480*/
drhc4a64fa2009-05-11 20:53:28 +00001481static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001482 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001483 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001484 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001485
drh17f71932002-02-21 12:01:27 +00001486 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001487 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001488 }
drhc7407522014-01-10 20:38:12 +00001489 needQuote = sqlite3Isdigit(zIdent[0])
1490 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1491 || zIdent[j]!=0
1492 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001493
drh234c39d2004-07-24 03:30:47 +00001494 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001495 for(j=0; zIdent[j]; j++){
1496 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001497 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001498 }
drh234c39d2004-07-24 03:30:47 +00001499 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001500 z[i] = 0;
1501 *pIdx = i;
1502}
1503
1504/*
1505** Generate a CREATE TABLE statement appropriate for the given
1506** table. Memory to hold the text of the statement is obtained
1507** from sqliteMalloc() and must be freed by the calling function.
1508*/
drh1d34fde2009-02-03 15:50:33 +00001509static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001510 int i, k, n;
1511 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001512 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001513 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001514 n = 0;
drh234c39d2004-07-24 03:30:47 +00001515 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001516 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001517 }
1518 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001519 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001520 zSep = "";
1521 zSep2 = ",";
1522 zEnd = ")";
1523 }else{
1524 zSep = "\n ";
1525 zSep2 = ",\n ";
1526 zEnd = "\n)";
1527 }
drhe0bc4042002-06-25 01:09:11 +00001528 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001529 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001530 if( zStmt==0 ){
1531 db->mallocFailed = 1;
1532 return 0;
1533 }
drhbdb339f2009-02-02 18:03:21 +00001534 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001535 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001536 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001537 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001538 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001539 static const char * const azType[] = {
1540 /* SQLITE_AFF_TEXT */ " TEXT",
1541 /* SQLITE_AFF_NONE */ "",
1542 /* SQLITE_AFF_NUMERIC */ " NUM",
1543 /* SQLITE_AFF_INTEGER */ " INT",
1544 /* SQLITE_AFF_REAL */ " REAL"
1545 };
1546 int len;
1547 const char *zType;
1548
drh5bb3eb92007-05-04 13:15:55 +00001549 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001550 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001551 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001552 identPut(zStmt, &k, pCol->zName);
1553 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001554 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001555 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1556 testcase( pCol->affinity==SQLITE_AFF_NONE );
1557 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1558 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1559 testcase( pCol->affinity==SQLITE_AFF_REAL );
1560
1561 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1562 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001563 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001564 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001565 memcpy(&zStmt[k], zType, len);
1566 k += len;
1567 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001568 }
drh5bb3eb92007-05-04 13:15:55 +00001569 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001570 return zStmt;
1571}
1572
1573/*
drh7f9c5db2013-10-23 00:32:58 +00001574** Resize an Index object to hold N columns total. Return SQLITE_OK
1575** on success and SQLITE_NOMEM on an OOM error.
1576*/
1577static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1578 char *zExtra;
1579 int nByte;
1580 if( pIdx->nColumn>=N ) return SQLITE_OK;
1581 assert( pIdx->isResized==0 );
1582 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1583 zExtra = sqlite3DbMallocZero(db, nByte);
1584 if( zExtra==0 ) return SQLITE_NOMEM;
1585 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1586 pIdx->azColl = (char**)zExtra;
1587 zExtra += sizeof(char*)*N;
1588 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1589 pIdx->aiColumn = (i16*)zExtra;
1590 zExtra += sizeof(i16)*N;
1591 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1592 pIdx->aSortOrder = (u8*)zExtra;
1593 pIdx->nColumn = N;
1594 pIdx->isResized = 1;
1595 return SQLITE_OK;
1596}
1597
1598/*
drhfdaac672013-10-04 15:30:21 +00001599** Estimate the total row width for a table.
1600*/
drhe13e9f52013-10-05 19:18:00 +00001601static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001602 unsigned wTable = 0;
1603 const Column *pTabCol;
1604 int i;
1605 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1606 wTable += pTabCol->szEst;
1607 }
1608 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001609 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001610}
1611
1612/*
drhe13e9f52013-10-05 19:18:00 +00001613** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001614*/
drhe13e9f52013-10-05 19:18:00 +00001615static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001616 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001617 int i;
1618 const Column *aCol = pIdx->pTable->aCol;
1619 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001620 i16 x = pIdx->aiColumn[i];
1621 assert( x<pIdx->pTable->nCol );
1622 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001623 }
drhe13e9f52013-10-05 19:18:00 +00001624 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001625}
1626
drh7f9c5db2013-10-23 00:32:58 +00001627/* Return true if value x is found any of the first nCol entries of aiCol[]
1628*/
1629static int hasColumn(const i16 *aiCol, int nCol, int x){
1630 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1631 return 0;
1632}
1633
1634/*
drhc6bd4e42013-11-02 14:37:18 +00001635** This routine runs at the end of parsing a CREATE TABLE statement that
1636** has a WITHOUT ROWID clause. The job of this routine is to convert both
1637** internal schema data structures and the generated VDBE code so that they
1638** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1639** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001640**
drhc6bd4e42013-11-02 14:37:18 +00001641** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1642** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1643** data storage is a covering index btree.
1644** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001645** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001646** identified by the sqlite_master table entry of the table itself.
1647** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1648** schema to the rootpage from the main table.
1649** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1650** (5) Add all table columns to the PRIMARY KEY Index object
1651** so that the PRIMARY KEY is a covering index. The surplus
1652** columns are part of KeyInfo.nXField and are not used for
1653** sorting or lookup or uniqueness checks.
1654** (6) Replace the rowid tail on all automatically generated UNIQUE
1655** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001656*/
1657static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1658 Index *pIdx;
1659 Index *pPk;
1660 int nPk;
1661 int i, j;
1662 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001663 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001664
1665 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001666 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001667 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001668 */
1669 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001670 assert( v );
1671 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1672 }
1673
1674 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1675 ** table entry.
1676 */
1677 if( pParse->addrSkipPK ){
1678 assert( v );
1679 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001680 }
1681
1682 /* Locate the PRIMARY KEY index. Or, if this table was originally
1683 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1684 */
1685 if( pTab->iPKey>=0 ){
1686 ExprList *pList;
1687 pList = sqlite3ExprListAppend(pParse, 0, 0);
1688 if( pList==0 ) return;
1689 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1690 pTab->aCol[pTab->iPKey].zName);
1691 pList->a[0].sortOrder = pParse->iPkSortOrder;
1692 assert( pParse->pNewTable==pTab );
1693 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1694 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001695 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001696 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001697 }else{
1698 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001699 }
drh12826092013-11-05 22:39:17 +00001700 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001701 assert( pPk!=0 );
1702 nPk = pPk->nKeyCol;
1703
drhec95c442013-10-23 01:57:32 +00001704 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1705 for(i=0; i<nPk; i++){
1706 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1707 }
drh9eade082013-10-24 14:16:10 +00001708 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001709
drhc6bd4e42013-11-02 14:37:18 +00001710 /* The root page of the PRIMARY KEY is the table root page */
1711 pPk->tnum = pTab->tnum;
1712
drh7f9c5db2013-10-23 00:32:58 +00001713 /* Update the in-memory representation of all UNIQUE indices by converting
1714 ** the final rowid column into one or more columns of the PRIMARY KEY.
1715 */
1716 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1717 int n;
drh48dd1d82014-05-27 18:18:58 +00001718 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001719 for(i=n=0; i<nPk; i++){
1720 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1721 }
drh5a9a37b2013-11-05 17:30:04 +00001722 if( n==0 ){
1723 /* This index is a superset of the primary key */
1724 pIdx->nColumn = pIdx->nKeyCol;
1725 continue;
1726 }
drh7f9c5db2013-10-23 00:32:58 +00001727 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1728 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001729 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001730 pIdx->aiColumn[j] = pPk->aiColumn[i];
1731 pIdx->azColl[j] = pPk->azColl[i];
1732 j++;
1733 }
1734 }
drh00012df2013-11-05 01:59:07 +00001735 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1736 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001737 }
1738
1739 /* Add all table columns to the PRIMARY KEY index
1740 */
1741 if( nPk<pTab->nCol ){
1742 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1743 for(i=0, j=nPk; i<pTab->nCol; i++){
1744 if( !hasColumn(pPk->aiColumn, j, i) ){
1745 assert( j<pPk->nColumn );
1746 pPk->aiColumn[j] = i;
1747 pPk->azColl[j] = "BINARY";
1748 j++;
1749 }
1750 }
1751 assert( pPk->nColumn==j );
1752 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001753 }else{
1754 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001755 }
1756}
1757
drhfdaac672013-10-04 15:30:21 +00001758/*
drh75897232000-05-29 14:26:00 +00001759** This routine is called to report the final ")" that terminates
1760** a CREATE TABLE statement.
1761**
drhf57b3392001-10-08 13:22:32 +00001762** The table structure that other action routines have been building
1763** is added to the internal hash tables, assuming no errors have
1764** occurred.
drh75897232000-05-29 14:26:00 +00001765**
drh1d85d932004-02-14 23:05:52 +00001766** An entry for the table is made in the master table on disk, unless
1767** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001768** it means we are reading the sqlite_master table because we just
1769** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001770** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001771** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001772**
1773** If the pSelect argument is not NULL, it means that this routine
1774** was called to create a table generated from a
1775** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1776** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001777*/
danielk197719a8e7e2005-03-17 05:03:38 +00001778void sqlite3EndTable(
1779 Parse *pParse, /* Parse context */
1780 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001781 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1782 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001783 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1784){
drhfdaac672013-10-04 15:30:21 +00001785 Table *p; /* The new table */
1786 sqlite3 *db = pParse->db; /* The database connection */
1787 int iDb; /* Database in which the table lives */
1788 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001789
drh5969da42013-10-21 02:14:45 +00001790 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1791 return;
danielk1977261919c2005-12-06 12:52:59 +00001792 }
drh28037572000-08-02 13:47:41 +00001793 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001794 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001795
danielk1977517eb642004-06-07 10:00:31 +00001796 assert( !db->init.busy || !pSelect );
1797
drhc6bd4e42013-11-02 14:37:18 +00001798 /* If the db->init.busy is 1 it means we are reading the SQL off the
1799 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1800 ** So do not write to the disk again. Extract the root page number
1801 ** for the table from the db->init.newTnum field. (The page number
1802 ** should have been put there by the sqliteOpenCb routine.)
1803 */
1804 if( db->init.busy ){
1805 p->tnum = db->init.newTnum;
1806 }
1807
1808 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001809 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001810 if( (p->tabFlags & TF_Autoincrement) ){
1811 sqlite3ErrorMsg(pParse,
1812 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1813 return;
1814 }
drh5969da42013-10-21 02:14:45 +00001815 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001816 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001817 }else{
1818 p->tabFlags |= TF_WithoutRowid;
1819 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001820 }
1821 }
1822
drhb9bb7c12006-06-11 23:41:55 +00001823 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001824
drhffe07b22005-11-03 00:41:17 +00001825#ifndef SQLITE_OMIT_CHECK
1826 /* Resolve names in all CHECK constraint expressions.
1827 */
1828 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001829 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001830 }
1831#endif /* !defined(SQLITE_OMIT_CHECK) */
1832
drhe13e9f52013-10-05 19:18:00 +00001833 /* Estimate the average row size for the table and for all implied indices */
1834 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001835 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001836 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001837 }
1838
drhe3c41372001-09-17 20:25:58 +00001839 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001840 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001841 **
drhe0bc4042002-06-25 01:09:11 +00001842 ** If this is a TEMPORARY table, write the entry into the auxiliary
1843 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001844 */
drh1d85d932004-02-14 23:05:52 +00001845 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001846 int n;
drhd8bc7082000-06-07 23:51:50 +00001847 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001848 char *zType; /* "view" or "table" */
1849 char *zType2; /* "VIEW" or "TABLE" */
1850 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001851
danielk19774adee202004-05-08 08:23:19 +00001852 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001853 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001854
drh66a51672008-01-03 00:01:23 +00001855 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001856
drh0fa991b2009-03-21 16:19:26 +00001857 /*
1858 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001859 */
drh4ff6dfa2002-03-03 23:06:00 +00001860 if( p->pSelect==0 ){
1861 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001862 zType = "table";
1863 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001864#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001865 }else{
1866 /* A view */
drh4794f732004-11-05 17:17:50 +00001867 zType = "view";
1868 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001869#endif
drh4ff6dfa2002-03-03 23:06:00 +00001870 }
danielk1977517eb642004-06-07 10:00:31 +00001871
danielk1977517eb642004-06-07 10:00:31 +00001872 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1873 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001874 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001875 **
1876 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1877 ** suitable state to query for the column names and types to be used
1878 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001879 **
1880 ** A shared-cache write-lock is not required to write to the new table,
1881 ** as a schema-lock must have already been obtained to create it. Since
1882 ** a schema-lock excludes all other database users, the write-lock would
1883 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001884 */
1885 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001886 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001887 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001888
danielk19776ab3a2e2009-02-19 14:39:25 +00001889 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001890 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001891 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001892 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001893 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001894 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001895 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001896 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001897 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001898 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001899 assert( p->aCol==0 );
1900 p->nCol = pSelTab->nCol;
1901 p->aCol = pSelTab->aCol;
1902 pSelTab->nCol = 0;
1903 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001904 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001905 }
1906 }
drh4794f732004-11-05 17:17:50 +00001907
drh4794f732004-11-05 17:17:50 +00001908 /* Compute the complete text of the CREATE statement */
1909 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001910 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001911 }else{
drh8ea30bf2013-10-22 01:18:17 +00001912 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1913 n = (int)(pEnd2->z - pParse->sNameToken.z);
1914 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001915 zStmt = sqlite3MPrintf(db,
1916 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1917 );
drh4794f732004-11-05 17:17:50 +00001918 }
1919
1920 /* A slot for the record has already been allocated in the
1921 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001922 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001923 */
1924 sqlite3NestedParse(pParse,
1925 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001926 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1927 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001928 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001929 zType,
1930 p->zName,
1931 p->zName,
drhb7654112008-01-12 12:48:07 +00001932 pParse->regRoot,
1933 zStmt,
1934 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001935 );
drh633e6d52008-07-28 19:34:53 +00001936 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001937 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001938
1939#ifndef SQLITE_OMIT_AUTOINCREMENT
1940 /* Check to see if we need to create an sqlite_sequence table for
1941 ** keeping track of autoincrement keys.
1942 */
drh7d10d5a2008-08-20 16:35:10 +00001943 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001944 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001945 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001946 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001947 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001948 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1949 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001950 );
1951 }
1952 }
1953#endif
drh4794f732004-11-05 17:17:50 +00001954
1955 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001956 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001957 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001958 }
drh17e9e292003-02-01 13:53:28 +00001959
drh2958a4e2004-11-12 03:56:15 +00001960
drh17e9e292003-02-01 13:53:28 +00001961 /* Add the table to the in-memory representation of the database.
1962 */
drh8af73d42009-05-13 22:58:28 +00001963 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001964 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001965 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001966 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00001967 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00001968 if( pOld ){
1969 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001970 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001971 return;
drh17e9e292003-02-01 13:53:28 +00001972 }
drh17e9e292003-02-01 13:53:28 +00001973 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001974 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001975
1976#ifndef SQLITE_OMIT_ALTERTABLE
1977 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001978 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001979 int nName;
drh5969da42013-10-21 02:14:45 +00001980 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001981 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00001982 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00001983 }
drh1bd10f82008-12-10 21:19:56 +00001984 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001985 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001986 }
1987#endif
drh17e9e292003-02-01 13:53:28 +00001988 }
drh75897232000-05-29 14:26:00 +00001989}
1990
drhb7f91642004-10-31 02:22:47 +00001991#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001992/*
drha76b5df2002-02-23 02:32:10 +00001993** The parser calls this routine in order to create a new VIEW
1994*/
danielk19774adee202004-05-08 08:23:19 +00001995void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001996 Parse *pParse, /* The parsing context */
1997 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001998 Token *pName1, /* The token that holds the name of the view */
1999 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00002000 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002001 int isTemp, /* TRUE for a TEMPORARY view */
2002 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002003){
drha76b5df2002-02-23 02:32:10 +00002004 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002005 int n;
drhb7916a72009-05-27 10:31:29 +00002006 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002007 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002008 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002009 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002010 int iDb;
drh17435752007-08-16 04:30:38 +00002011 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002012
drh7c3d64f2005-06-06 15:32:08 +00002013 if( pParse->nVar>0 ){
2014 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002015 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002016 return;
2017 }
drhfdd48a72006-09-11 23:45:48 +00002018 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002019 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00002020 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00002021 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00002022 return;
2023 }
danielk1977ef2cb632004-05-29 02:37:19 +00002024 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002025 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002026 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2027 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00002028 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00002029 return;
2030 }
drh174b6192002-12-03 02:22:52 +00002031
drh4b59ab52002-08-24 18:24:51 +00002032 /* Make a copy of the entire SELECT statement that defines the view.
2033 ** This will force all the Expr.token.z values to be dynamically
2034 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002035 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002036 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002037 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002038 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002039 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002040 return;
2041 }
drh17435752007-08-16 04:30:38 +00002042 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002043 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002044 }
drh4b59ab52002-08-24 18:24:51 +00002045
2046 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2047 ** the end.
2048 */
drha76b5df2002-02-23 02:32:10 +00002049 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002050 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002051 sEnd.z += sEnd.n;
2052 }
2053 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002054 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002055 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002056 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002057 sEnd.z = &z[n-1];
2058 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002059
danielk19774adee202004-05-08 08:23:19 +00002060 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002061 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002062 return;
drh417be792002-03-03 18:59:40 +00002063}
drhb7f91642004-10-31 02:22:47 +00002064#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002065
danielk1977fe3fcbe22006-06-12 12:08:45 +00002066#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002067/*
2068** The Table structure pTable is really a VIEW. Fill in the names of
2069** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002070** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002071*/
danielk19774adee202004-05-08 08:23:19 +00002072int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002073 Table *pSelTab; /* A fake table from which we get the result set */
2074 Select *pSel; /* Copy of the SELECT that implements the view */
2075 int nErr = 0; /* Number of errors encountered */
2076 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002077 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002078 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh417be792002-03-03 18:59:40 +00002079
2080 assert( pTable );
2081
danielk1977fe3fcbe22006-06-12 12:08:45 +00002082#ifndef SQLITE_OMIT_VIRTUALTABLE
2083 if( sqlite3VtabCallConnect(pParse, pTable) ){
2084 return SQLITE_ERROR;
2085 }
drh4cbdda92006-06-14 19:00:20 +00002086 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002087#endif
2088
2089#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002090 /* A positive nCol means the columns names for this view are
2091 ** already known.
2092 */
2093 if( pTable->nCol>0 ) return 0;
2094
2095 /* A negative nCol is a special marker meaning that we are currently
2096 ** trying to compute the column names. If we enter this routine with
2097 ** a negative nCol, it means two or more views form a loop, like this:
2098 **
2099 ** CREATE VIEW one AS SELECT * FROM two;
2100 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002101 **
drh768578e2009-05-12 00:40:12 +00002102 ** Actually, the error above is now caught prior to reaching this point.
2103 ** But the following test is still important as it does come up
2104 ** in the following:
2105 **
2106 ** CREATE TABLE main.ex1(a);
2107 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2108 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002109 */
2110 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002111 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002112 return 1;
2113 }
drh85c23c62005-08-20 03:03:04 +00002114 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002115
2116 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002117 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2118 ** "*" elements in the results set of the view and will assign cursors
2119 ** to the elements of the FROM clause. But we do not want these changes
2120 ** to be permanent. So the computation is done on a copy of the SELECT
2121 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002122 */
drh9b3187e2005-01-18 14:45:47 +00002123 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002124 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002125 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002126 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002127 n = pParse->nTab;
2128 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2129 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002130 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002131#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002132 xAuth = db->xAuth;
2133 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002134 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002135 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002136#else
drh7d10d5a2008-08-20 16:35:10 +00002137 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002138#endif
drhd9da78a2009-03-24 15:08:09 +00002139 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002140 pParse->nTab = n;
2141 if( pSelTab ){
2142 assert( pTable->aCol==0 );
2143 pTable->nCol = pSelTab->nCol;
2144 pTable->aCol = pSelTab->aCol;
2145 pSelTab->nCol = 0;
2146 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002147 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002148 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
drh2c5e35f2014-08-05 11:04:21 +00002149 pTable->pSchema->schemaFlags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002150 }else{
2151 pTable->nCol = 0;
2152 nErr++;
2153 }
drh633e6d52008-07-28 19:34:53 +00002154 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002155 } else {
drh417be792002-03-03 18:59:40 +00002156 nErr++;
2157 }
drhb7f91642004-10-31 02:22:47 +00002158#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002159 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002160}
2161#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002162
drhb7f91642004-10-31 02:22:47 +00002163#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002164/*
drh8bf8dc92003-05-17 17:35:10 +00002165** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002166*/
drh9bb575f2004-09-06 17:24:11 +00002167static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002168 HashElem *i;
drh21206082011-04-04 18:22:02 +00002169 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002170 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002171 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002172 Table *pTab = sqliteHashData(i);
2173 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002174 sqliteDeleteColumnNames(db, pTab);
2175 pTab->aCol = 0;
2176 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002177 }
2178 }
drh8bf8dc92003-05-17 17:35:10 +00002179 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002180}
drhb7f91642004-10-31 02:22:47 +00002181#else
2182# define sqliteViewResetAll(A,B)
2183#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002184
drh75897232000-05-29 14:26:00 +00002185/*
danielk1977a0bf2652004-11-04 14:30:04 +00002186** This function is called by the VDBE to adjust the internal schema
2187** used by SQLite when the btree layer moves a table root page. The
2188** root-page of a table or index in database iDb has changed from iFrom
2189** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002190**
2191** Ticket #1728: The symbol table might still contain information
2192** on tables and/or indices that are the process of being deleted.
2193** If you are unlucky, one of those deleted indices or tables might
2194** have the same rootpage number as the real table or index that is
2195** being moved. So we cannot stop searching after the first match
2196** because the first match might be for one of the deleted indices
2197** or tables and not the table/index that is actually being moved.
2198** We must continue looping until all tables and indices with
2199** rootpage==iFrom have been converted to have a rootpage of iTo
2200** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002201*/
2202#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002203void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002204 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002205 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002206 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002207
drhcdf011d2011-04-04 21:25:28 +00002208 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2209 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002210 pHash = &pDb->pSchema->tblHash;
2211 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002212 Table *pTab = sqliteHashData(pElem);
2213 if( pTab->tnum==iFrom ){
2214 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002215 }
2216 }
danielk1977da184232006-01-05 11:34:32 +00002217 pHash = &pDb->pSchema->idxHash;
2218 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002219 Index *pIdx = sqliteHashData(pElem);
2220 if( pIdx->tnum==iFrom ){
2221 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002222 }
2223 }
danielk1977a0bf2652004-11-04 14:30:04 +00002224}
2225#endif
2226
2227/*
2228** Write code to erase the table with root-page iTable from database iDb.
2229** Also write code to modify the sqlite_master table and internal schema
2230** if a root-page of another table is moved by the btree-layer whilst
2231** erasing iTable (this can happen with an auto-vacuum database).
2232*/
drh4e0cff62004-11-05 05:10:28 +00002233static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2234 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002235 int r1 = sqlite3GetTempReg(pParse);
2236 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002237 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002238#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002239 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002240 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002241 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002242 ** reflect this.
2243 **
drh0fa991b2009-03-21 16:19:26 +00002244 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002245 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2246 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002247 */
danielk197763e3e9f2004-11-05 09:19:27 +00002248 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002249 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2250 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002251#endif
drhb7654112008-01-12 12:48:07 +00002252 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002253}
2254
2255/*
2256** Write VDBE code to erase table pTab and all associated indices on disk.
2257** Code to update the sqlite_master tables and internal schema definitions
2258** in case a root-page belonging to another table is moved by the btree layer
2259** is also added (this can happen with an auto-vacuum database).
2260*/
drh4e0cff62004-11-05 05:10:28 +00002261static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002262#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002263 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002264 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2265 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002266 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002267 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002268 }
2269#else
2270 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2271 ** is not defined), then it is important to call OP_Destroy on the
2272 ** table and index root-pages in order, starting with the numerically
2273 ** largest root-page number. This guarantees that none of the root-pages
2274 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2275 ** following were coded:
2276 **
2277 ** OP_Destroy 4 0
2278 ** ...
2279 ** OP_Destroy 5 0
2280 **
2281 ** and root page 5 happened to be the largest root-page number in the
2282 ** database, then root page 5 would be moved to page 4 by the
2283 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2284 ** a free-list page.
2285 */
2286 int iTab = pTab->tnum;
2287 int iDestroyed = 0;
2288
2289 while( 1 ){
2290 Index *pIdx;
2291 int iLargest = 0;
2292
2293 if( iDestroyed==0 || iTab<iDestroyed ){
2294 iLargest = iTab;
2295 }
2296 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2297 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002298 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002299 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2300 iLargest = iIdx;
2301 }
2302 }
danielk1977da184232006-01-05 11:34:32 +00002303 if( iLargest==0 ){
2304 return;
2305 }else{
2306 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002307 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002308 destroyRootPage(pParse, iLargest, iDb);
2309 iDestroyed = iLargest;
2310 }
danielk1977a0bf2652004-11-04 14:30:04 +00002311 }
2312#endif
2313}
2314
2315/*
drh74e7c8f2011-10-21 19:06:32 +00002316** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002317** after a DROP INDEX or DROP TABLE command.
2318*/
2319static void sqlite3ClearStatTables(
2320 Parse *pParse, /* The parsing context */
2321 int iDb, /* The database number */
2322 const char *zType, /* "idx" or "tbl" */
2323 const char *zName /* Name of index or table */
2324){
drha5ae4c32011-08-07 01:31:52 +00002325 int i;
2326 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002327 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002328 char zTab[24];
2329 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2330 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002331 sqlite3NestedParse(pParse,
2332 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002333 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002334 );
2335 }
2336 }
2337}
2338
2339/*
drhfaacf172011-08-12 01:51:45 +00002340** Generate code to drop a table.
2341*/
2342void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2343 Vdbe *v;
2344 sqlite3 *db = pParse->db;
2345 Trigger *pTrigger;
2346 Db *pDb = &db->aDb[iDb];
2347
2348 v = sqlite3GetVdbe(pParse);
2349 assert( v!=0 );
2350 sqlite3BeginWriteOperation(pParse, 1, iDb);
2351
2352#ifndef SQLITE_OMIT_VIRTUALTABLE
2353 if( IsVirtual(pTab) ){
2354 sqlite3VdbeAddOp0(v, OP_VBegin);
2355 }
2356#endif
2357
2358 /* Drop all triggers associated with the table being dropped. Code
2359 ** is generated to remove entries from sqlite_master and/or
2360 ** sqlite_temp_master if required.
2361 */
2362 pTrigger = sqlite3TriggerList(pParse, pTab);
2363 while( pTrigger ){
2364 assert( pTrigger->pSchema==pTab->pSchema ||
2365 pTrigger->pSchema==db->aDb[1].pSchema );
2366 sqlite3DropTriggerPtr(pParse, pTrigger);
2367 pTrigger = pTrigger->pNext;
2368 }
2369
2370#ifndef SQLITE_OMIT_AUTOINCREMENT
2371 /* Remove any entries of the sqlite_sequence table associated with
2372 ** the table being dropped. This is done before the table is dropped
2373 ** at the btree level, in case the sqlite_sequence table needs to
2374 ** move as a result of the drop (can happen in auto-vacuum mode).
2375 */
2376 if( pTab->tabFlags & TF_Autoincrement ){
2377 sqlite3NestedParse(pParse,
2378 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2379 pDb->zName, pTab->zName
2380 );
2381 }
2382#endif
2383
2384 /* Drop all SQLITE_MASTER table and index entries that refer to the
2385 ** table. The program name loops through the master table and deletes
2386 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002387 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002388 ** created in the temp database that refers to a table in another
2389 ** database.
2390 */
2391 sqlite3NestedParse(pParse,
2392 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2393 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002394 if( !isView && !IsVirtual(pTab) ){
2395 destroyTable(pParse, pTab);
2396 }
2397
2398 /* Remove the table entry from SQLite's internal schema and modify
2399 ** the schema cookie.
2400 */
2401 if( IsVirtual(pTab) ){
2402 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2403 }
2404 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2405 sqlite3ChangeCookie(pParse, iDb);
2406 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002407}
2408
2409/*
drh75897232000-05-29 14:26:00 +00002410** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002411** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002412*/
drha0733842005-12-29 01:11:36 +00002413void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002414 Table *pTab;
drh75897232000-05-29 14:26:00 +00002415 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002416 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002417 int iDb;
drh75897232000-05-29 14:26:00 +00002418
drh8af73d42009-05-13 22:58:28 +00002419 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002420 goto exit_drop_table;
2421 }
drh8af73d42009-05-13 22:58:28 +00002422 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002423 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002424 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002425 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002426 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002427
drha0733842005-12-29 01:11:36 +00002428 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002429 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002430 goto exit_drop_table;
2431 }
danielk1977da184232006-01-05 11:34:32 +00002432 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002433 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002434
2435 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2436 ** it is initialized.
2437 */
2438 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2439 goto exit_drop_table;
2440 }
drhe5f9c642003-01-13 23:27:31 +00002441#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002442 {
2443 int code;
danielk1977da184232006-01-05 11:34:32 +00002444 const char *zTab = SCHEMA_TABLE(iDb);
2445 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002446 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002447 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002448 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002449 }
drhe5f9c642003-01-13 23:27:31 +00002450 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002451 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002452 code = SQLITE_DROP_TEMP_VIEW;
2453 }else{
2454 code = SQLITE_DROP_VIEW;
2455 }
danielk19774b2688a2006-06-20 11:01:07 +00002456#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002457 }else if( IsVirtual(pTab) ){
2458 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002459 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002460#endif
drhe5f9c642003-01-13 23:27:31 +00002461 }else{
danielk197753c0f742005-03-29 03:10:59 +00002462 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002463 code = SQLITE_DROP_TEMP_TABLE;
2464 }else{
2465 code = SQLITE_DROP_TABLE;
2466 }
2467 }
danielk1977f1a381e2006-06-16 08:01:02 +00002468 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002469 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002470 }
danielk1977a8858102004-05-28 12:11:21 +00002471 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2472 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002473 }
drhe5f9c642003-01-13 23:27:31 +00002474 }
2475#endif
drh08ccfaa2011-10-07 23:52:25 +00002476 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2477 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002478 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002479 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002480 }
danielk1977576ec6b2005-01-21 11:55:25 +00002481
2482#ifndef SQLITE_OMIT_VIEW
2483 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2484 ** on a table.
2485 */
danielk1977a8858102004-05-28 12:11:21 +00002486 if( isView && pTab->pSelect==0 ){
2487 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2488 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002489 }
danielk1977a8858102004-05-28 12:11:21 +00002490 if( !isView && pTab->pSelect ){
2491 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2492 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002493 }
danielk1977576ec6b2005-01-21 11:55:25 +00002494#endif
drh75897232000-05-29 14:26:00 +00002495
drh1ccde152000-06-17 13:12:39 +00002496 /* Generate code to remove the table from the master table
2497 ** on disk.
2498 */
danielk19774adee202004-05-08 08:23:19 +00002499 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002500 if( v ){
drh77658e22007-12-04 16:54:52 +00002501 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002502 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002503 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002504 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002505 }
danielk1977a8858102004-05-28 12:11:21 +00002506
2507exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002508 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002509}
2510
2511/*
drhc2eef3b2002-08-31 18:53:06 +00002512** This routine is called to create a new foreign key on the table
2513** currently under construction. pFromCol determines which columns
2514** in the current table point to the foreign key. If pFromCol==0 then
2515** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002516** the table referred to (a.k.a the "parent" table). pToCol is a list
2517** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002518** information about the conflict resolution algorithms specified
2519** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2520**
2521** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002522** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002523**
2524** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002525** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002526*/
danielk19774adee202004-05-08 08:23:19 +00002527void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002528 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002529 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002530 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002531 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002532 int flags /* Conflict resolution algorithms. */
2533){
danielk197718576932008-08-06 13:47:40 +00002534 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002535#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002536 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002537 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002538 Table *p = pParse->pNewTable;
2539 int nByte;
2540 int i;
2541 int nCol;
2542 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002543
2544 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002545 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002546 if( pFromCol==0 ){
2547 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002548 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002549 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002550 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002551 " should reference only one column of table %T",
2552 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002553 goto fk_end;
2554 }
2555 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002556 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002557 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002558 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002559 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002560 goto fk_end;
2561 }else{
danielk19770202b292004-06-09 09:55:16 +00002562 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002563 }
drhe61922a2009-05-02 13:29:37 +00002564 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002565 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002566 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002567 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002568 }
2569 }
drh633e6d52008-07-28 19:34:53 +00002570 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002571 if( pFKey==0 ){
2572 goto fk_end;
2573 }
drhc2eef3b2002-08-31 18:53:06 +00002574 pFKey->pFrom = p;
2575 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002576 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002577 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002578 memcpy(z, pTo->z, pTo->n);
2579 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002580 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002581 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002582 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002583 if( pFromCol==0 ){
2584 pFKey->aCol[0].iFrom = p->nCol-1;
2585 }else{
2586 for(i=0; i<nCol; i++){
2587 int j;
2588 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002589 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002590 pFKey->aCol[i].iFrom = j;
2591 break;
2592 }
2593 }
2594 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002595 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002596 "unknown column \"%s\" in foreign key definition",
2597 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002598 goto fk_end;
2599 }
2600 }
2601 }
2602 if( pToCol ){
2603 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002604 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002605 pFKey->aCol[i].zCol = z;
2606 memcpy(z, pToCol->a[i].zName, n);
2607 z[n] = 0;
2608 z += n+1;
2609 }
2610 }
2611 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002612 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2613 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002614
drh21206082011-04-04 18:22:02 +00002615 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002616 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002617 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002618 );
danf59c5ca2009-09-22 16:55:38 +00002619 if( pNextTo==pFKey ){
2620 db->mallocFailed = 1;
2621 goto fk_end;
2622 }
dan1da40a32009-09-19 17:00:31 +00002623 if( pNextTo ){
2624 assert( pNextTo->pPrevTo==0 );
2625 pFKey->pNextTo = pNextTo;
2626 pNextTo->pPrevTo = pFKey;
2627 }
2628
drhc2eef3b2002-08-31 18:53:06 +00002629 /* Link the foreign key to the table as the last step.
2630 */
2631 p->pFKey = pFKey;
2632 pFKey = 0;
2633
2634fk_end:
drh633e6d52008-07-28 19:34:53 +00002635 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002636#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002637 sqlite3ExprListDelete(db, pFromCol);
2638 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002639}
2640
2641/*
2642** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2643** clause is seen as part of a foreign key definition. The isDeferred
2644** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2645** The behavior of the most recently created foreign key is adjusted
2646** accordingly.
2647*/
danielk19774adee202004-05-08 08:23:19 +00002648void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002649#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002650 Table *pTab;
2651 FKey *pFKey;
2652 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002653 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002654 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002655#endif
drhc2eef3b2002-08-31 18:53:06 +00002656}
2657
2658/*
drh063336a2004-11-05 20:58:39 +00002659** Generate code that will erase and refill index *pIdx. This is
2660** used to initialize a newly created index or to recompute the
2661** content of an index in response to a REINDEX command.
2662**
2663** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002664** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002665** root page number of the index. If memRootPage is negative, then
2666** the index already exists and must be cleared before being refilled and
2667** the root page number of the index is taken from pIndex->tnum.
2668*/
2669static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2670 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002671 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2672 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002673 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002674 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002675 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002676 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002677 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002678 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002679 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002680 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002681 sqlite3 *db = pParse->db; /* The database connection */
2682 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002683
danielk19771d54df82004-11-23 15:41:16 +00002684#ifndef SQLITE_OMIT_AUTHORIZATION
2685 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002686 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002687 return;
2688 }
2689#endif
2690
danielk1977c00da102006-01-07 13:21:04 +00002691 /* Require a write-lock on the table to perform this operation */
2692 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2693
drh063336a2004-11-05 20:58:39 +00002694 v = sqlite3GetVdbe(pParse);
2695 if( v==0 ) return;
2696 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002697 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002698 }else{
2699 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002700 }
drh2ec2fb22013-11-06 19:59:23 +00002701 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002702
dan689ab892011-08-12 15:02:00 +00002703 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002704 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002705 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002706 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002707
2708 /* Open the table. Loop through all rows of the table, inserting index
2709 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002710 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002711 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002712 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002713
drh1c2c0b72014-01-04 19:27:05 +00002714 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002715 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002716 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002717 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002718 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002719 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2720 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002721 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002722 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2723
drh688852a2014-02-17 22:40:43 +00002724 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002725 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002726 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002727 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2728 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2729 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002730 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002731 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002732 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002733 }else{
2734 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002735 }
drhca892a72011-09-03 00:17:51 +00002736 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2737 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2738 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002739 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002740 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002741 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002742
drh66a51672008-01-03 00:01:23 +00002743 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2744 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002745 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002746}
2747
2748/*
drh77e57df2013-10-22 14:28:02 +00002749** Allocate heap space to hold an Index object with nCol columns.
2750**
2751** Increase the allocation size to provide an extra nExtra bytes
2752** of 8-byte aligned space after the Index object and return a
2753** pointer to this extra space in *ppExtra.
2754*/
2755Index *sqlite3AllocateIndexObject(
2756 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002757 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002758 int nExtra, /* Number of bytes of extra space to alloc */
2759 char **ppExtra /* Pointer to the "extra" space */
2760){
2761 Index *p; /* Allocated index object */
2762 int nByte; /* Bytes of space for Index object + arrays */
2763
2764 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2765 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002766 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002767 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002768 sizeof(u8)*nCol); /* Index.aSortOrder */
2769 p = sqlite3DbMallocZero(db, nByte + nExtra);
2770 if( p ){
2771 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002772 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2773 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2774 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002775 p->aSortOrder = (u8*)pExtra;
2776 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002777 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002778 *ppExtra = ((char*)p) + nByte;
2779 }
2780 return p;
2781}
2782
2783/*
drh23bf66d2004-12-14 03:34:34 +00002784** Create a new index for an SQL table. pName1.pName2 is the name of the index
2785** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002786** be NULL for a primary key or an index that is created to satisfy a
2787** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002788** as the table to be indexed. pParse->pNewTable is a table that is
2789** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002790**
drh382c0242001-10-06 16:33:02 +00002791** pList is a list of columns to be indexed. pList will be NULL if this
2792** is a primary key or unique-constraint on the most recent column added
2793** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002794**
2795** If the index is created successfully, return a pointer to the new Index
2796** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002797** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002798*/
dan1da40a32009-09-19 17:00:31 +00002799Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002800 Parse *pParse, /* All information about this parse */
2801 Token *pName1, /* First part of index name. May be NULL */
2802 Token *pName2, /* Second part of index name. May be NULL */
2803 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002804 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002805 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002806 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002807 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002808 int sortOrder, /* Sort order of primary key when pList==NULL */
2809 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002810){
dan1da40a32009-09-19 17:00:31 +00002811 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002812 Table *pTab = 0; /* Table to be indexed */
2813 Index *pIndex = 0; /* The index to be created */
2814 char *zName = 0; /* Name of the index */
2815 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002816 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002817 DbFixer sFix; /* For assigning database names to pTable */
2818 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002819 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002820 Db *pDb; /* The specific table containing the indexed database */
2821 int iDb; /* Index of the database that is being written */
2822 Token *pName = 0; /* Unqualified name of the index to create */
2823 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002824 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002825 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002826 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002827 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002828 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002829
drh8af73d42009-05-13 22:58:28 +00002830 assert( pParse->nErr==0 ); /* Never called with prior errors */
2831 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002832 goto exit_create_index;
2833 }
2834 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002835 goto exit_create_index;
2836 }
drhdaffd0e2001-04-11 14:28:42 +00002837
drh75897232000-05-29 14:26:00 +00002838 /*
2839 ** Find the table that is to be indexed. Return early if not found.
2840 */
danielk1977cbb18d22004-05-28 11:37:27 +00002841 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002842
2843 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002844 ** to search for the table. 'Fix' the table name to this db
2845 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002846 */
2847 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002848 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002849 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002850 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002851
danielk197753c0f742005-03-29 03:10:59 +00002852#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002853 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002854 ** is a temp table. If so, set the database to 1. Do not do this
2855 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002856 */
danielk1977fe910332007-12-02 11:46:34 +00002857 if( !db->init.busy ){
2858 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002859 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002860 iDb = 1;
2861 }
danielk1977ef2cb632004-05-29 02:37:19 +00002862 }
danielk197753c0f742005-03-29 03:10:59 +00002863#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002864
drhd100f692013-10-03 15:39:44 +00002865 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2866 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002867 /* Because the parser constructs pTblName from a single identifier,
2868 ** sqlite3FixSrcList can never fail. */
2869 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002870 }
dan41fb5cd2012-10-04 19:33:00 +00002871 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002872 assert( db->mallocFailed==0 || pTab==0 );
2873 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002874 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2875 sqlite3ErrorMsg(pParse,
2876 "cannot create a TEMP index on non-TEMP table \"%s\"",
2877 pTab->zName);
2878 goto exit_create_index;
2879 }
drh44156282013-10-23 22:23:03 +00002880 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002881 }else{
drhe3c41372001-09-17 20:25:58 +00002882 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002883 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002884 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002885 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002886 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002887 }
drhfdd6e852005-12-16 01:06:16 +00002888 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002889
drhd3001712009-05-12 17:46:53 +00002890 assert( pTab!=0 );
2891 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002892 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drhd4530972014-09-09 14:47:53 +00002893#if SQLITE_USER_AUTHENTICATION
2894 && sqlite3UserAuthTable(pTab->zName)==0
2895#endif
drh503a6862013-03-01 01:07:17 +00002896 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002897 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002898 goto exit_create_index;
2899 }
danielk1977576ec6b2005-01-21 11:55:25 +00002900#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002901 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002902 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002903 goto exit_create_index;
2904 }
danielk1977576ec6b2005-01-21 11:55:25 +00002905#endif
danielk19775ee9d692006-06-21 12:36:25 +00002906#ifndef SQLITE_OMIT_VIRTUALTABLE
2907 if( IsVirtual(pTab) ){
2908 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2909 goto exit_create_index;
2910 }
2911#endif
drh75897232000-05-29 14:26:00 +00002912
2913 /*
2914 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002915 ** index or table with the same name.
2916 **
2917 ** Exception: If we are reading the names of permanent indices from the
2918 ** sqlite_master table (because some other process changed the schema) and
2919 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002920 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002921 **
2922 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002923 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2924 ** own name.
drh75897232000-05-29 14:26:00 +00002925 */
danielk1977d8123362004-06-12 09:25:12 +00002926 if( pName ){
drh17435752007-08-16 04:30:38 +00002927 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002928 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002929 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002930 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002931 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002932 }
danielk1977d8123362004-06-12 09:25:12 +00002933 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002934 if( sqlite3FindTable(db, zName, 0)!=0 ){
2935 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2936 goto exit_create_index;
2937 }
2938 }
danielk197759a33f92007-03-17 10:26:59 +00002939 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2940 if( !ifNotExist ){
2941 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002942 }else{
2943 assert( !db->init.busy );
2944 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002945 }
danielk197759a33f92007-03-17 10:26:59 +00002946 goto exit_create_index;
2947 }
danielk1977a21c6b62005-01-24 10:25:59 +00002948 }else{
drhadbca9c2001-09-27 15:11:53 +00002949 int n;
2950 Index *pLoop;
2951 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002952 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002953 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002954 goto exit_create_index;
2955 }
drh75897232000-05-29 14:26:00 +00002956 }
2957
drhe5f9c642003-01-13 23:27:31 +00002958 /* Check for authorization to create an index.
2959 */
2960#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002961 {
drhfdd6e852005-12-16 01:06:16 +00002962 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002963 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002964 goto exit_create_index;
2965 }
2966 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002967 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002968 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002969 goto exit_create_index;
2970 }
drhe5f9c642003-01-13 23:27:31 +00002971 }
2972#endif
2973
drh75897232000-05-29 14:26:00 +00002974 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002975 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002976 ** So create a fake list to simulate this.
2977 */
2978 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002979 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002980 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002981 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2982 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00002983 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002984 }
2985
danielk1977b3bf5562006-01-10 17:58:23 +00002986 /* Figure out how many bytes of space are required to store explicitly
2987 ** specified collation sequence names.
2988 */
2989 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00002990 Expr *pExpr = pList->a[i].pExpr;
2991 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00002992 assert( pExpr->op==TK_COLLATE );
2993 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00002994 }
2995 }
2996
drh75897232000-05-29 14:26:00 +00002997 /*
2998 ** Allocate the index structure.
2999 */
drhea678832008-12-10 19:26:22 +00003000 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003001 nExtraCol = pPk ? pPk->nKeyCol : 1;
3002 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003003 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003004 if( db->mallocFailed ){
3005 goto exit_create_index;
3006 }
dancfc9df72014-04-25 15:01:01 +00003007 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003008 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003009 pIndex->zName = zExtra;
3010 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003011 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003012 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003013 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003014 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003015 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003016 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003017 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003018 if( pPIWhere ){
3019 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3020 pIndex->pPartIdxWhere = pPIWhere;
3021 pPIWhere = 0;
3022 }
drh21206082011-04-04 18:22:02 +00003023 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003024
drhfdd6e852005-12-16 01:06:16 +00003025 /* Check to see if we should honor DESC requests on index columns
3026 */
danielk1977da184232006-01-05 11:34:32 +00003027 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003028 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003029 }else{
3030 sortOrderMask = 0; /* Ignore DESC */
3031 }
3032
drh1ccde152000-06-17 13:12:39 +00003033 /* Scan the names of the columns of the table to be indexed and
3034 ** load the column indices into the Index structure. Report an error
3035 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003036 **
3037 ** TODO: Add a test to make sure that the same column is not named
3038 ** more than once within the same index. Only the first instance of
3039 ** the column will ever be used by the optimizer. Note that using the
3040 ** same column more than once cannot be an error because that would
3041 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003042 */
drhfdd6e852005-12-16 01:06:16 +00003043 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3044 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003045 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003046 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003047
drhfdd6e852005-12-16 01:06:16 +00003048 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3049 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003050 }
3051 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003052 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003053 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003054 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003055 goto exit_create_index;
3056 }
drhbf20a352014-04-04 22:44:59 +00003057 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003058 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003059 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003060 int nColl;
dan911ce412013-05-15 15:16:50 +00003061 assert( pListItem->pExpr->op==TK_COLLATE );
3062 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003063 nColl = sqlite3Strlen30(zColl) + 1;
3064 assert( nExtra>=nColl );
3065 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003066 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003067 zExtra += nColl;
3068 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003069 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003070 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003071 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003072 }
drhb7f24de2009-05-13 17:35:23 +00003073 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003074 goto exit_create_index;
3075 }
danielk1977b3bf5562006-01-10 17:58:23 +00003076 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003077 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003078 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003079 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003080 }
drh44156282013-10-23 22:23:03 +00003081 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003082 for(j=0; j<pPk->nKeyCol; j++){
3083 int x = pPk->aiColumn[j];
3084 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3085 pIndex->nColumn--;
3086 }else{
3087 pIndex->aiColumn[i] = x;
3088 pIndex->azColl[i] = pPk->azColl[j];
3089 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3090 i++;
3091 }
drh44156282013-10-23 22:23:03 +00003092 }
drh7913e412013-11-01 20:30:36 +00003093 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003094 }else{
3095 pIndex->aiColumn[i] = -1;
3096 pIndex->azColl[i] = "BINARY";
3097 }
drh51147ba2005-07-23 22:59:55 +00003098 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003099 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003100
danielk1977d8123362004-06-12 09:25:12 +00003101 if( pTab==pParse->pNewTable ){
3102 /* This routine has been called to create an automatic index as a
3103 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3104 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3105 ** i.e. one of:
3106 **
3107 ** CREATE TABLE t(x PRIMARY KEY, y);
3108 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3109 **
3110 ** Either way, check to see if the table already has such an index. If
3111 ** so, don't bother creating this one. This only applies to
3112 ** automatically created indices. Users can do as they wish with
3113 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003114 **
3115 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3116 ** (and thus suppressing the second one) even if they have different
3117 ** sort orders.
3118 **
3119 ** If there are different collating sequences or if the columns of
3120 ** the constraint occur in different orders, then the constraints are
3121 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003122 */
3123 Index *pIdx;
3124 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3125 int k;
drh5f1d1d92014-07-31 22:59:04 +00003126 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003127 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003128 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003129
drhbbbdc832013-10-22 18:01:40 +00003130 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3131 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003132 const char *z1;
3133 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003134 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003135 z1 = pIdx->azColl[k];
3136 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003137 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003138 }
drhbbbdc832013-10-22 18:01:40 +00003139 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003140 if( pIdx->onError!=pIndex->onError ){
3141 /* This constraint creates the same index as a previous
3142 ** constraint specified somewhere in the CREATE TABLE statement.
3143 ** However the ON CONFLICT clauses are different. If both this
3144 ** constraint and the previous equivalent constraint have explicit
3145 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003146 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003147 */
3148 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3149 sqlite3ErrorMsg(pParse,
3150 "conflicting ON CONFLICT clauses specified", 0);
3151 }
3152 if( pIdx->onError==OE_Default ){
3153 pIdx->onError = pIndex->onError;
3154 }
3155 }
danielk1977d8123362004-06-12 09:25:12 +00003156 goto exit_create_index;
3157 }
3158 }
3159 }
3160
drh75897232000-05-29 14:26:00 +00003161 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003162 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003163 */
drh234c39d2004-07-24 03:30:47 +00003164 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003165 Index *p;
drh21206082011-04-04 18:22:02 +00003166 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003167 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003168 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003169 if( p ){
3170 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003171 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003172 goto exit_create_index;
3173 }
drh5e00f6c2001-09-13 13:46:56 +00003174 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003175 if( pTblName!=0 ){
3176 pIndex->tnum = db->init.newTnum;
3177 }
drhd78eeee2001-09-13 16:18:53 +00003178 }
3179
drh58383402013-11-04 17:00:50 +00003180 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3181 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3182 ** emit code to allocate the index rootpage on disk and make an entry for
3183 ** the index in the sqlite_master table and populate the index with
3184 ** content. But, do not do this if we are simply reading the sqlite_master
3185 ** table to parse the schema, or if this index is the PRIMARY KEY index
3186 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003187 **
drh58383402013-11-04 17:00:50 +00003188 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3189 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003190 ** has just been created, it contains no data and the index initialization
3191 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003192 */
drh58383402013-11-04 17:00:50 +00003193 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003194 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003195 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003196 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003197
danielk19774adee202004-05-08 08:23:19 +00003198 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003199 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003200
drhfdd6e852005-12-16 01:06:16 +00003201
drh063336a2004-11-05 20:58:39 +00003202 /* Create the rootpage for the index
3203 */
drhaee128d2005-02-14 20:48:18 +00003204 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003205 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003206
3207 /* Gather the complete text of the CREATE INDEX statement into
3208 ** the zStmt variable
3209 */
drhd3001712009-05-12 17:46:53 +00003210 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003211 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003212 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003213 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003214 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003215 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003216 }else{
3217 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003218 /* zStmt = sqlite3MPrintf(""); */
3219 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003220 }
drh063336a2004-11-05 20:58:39 +00003221
3222 /* Add an entry in sqlite_master for this index
3223 */
3224 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003225 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003226 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3227 pIndex->zName,
3228 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003229 iMem,
drh063336a2004-11-05 20:58:39 +00003230 zStmt
3231 );
drh633e6d52008-07-28 19:34:53 +00003232 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003233
danielk1977a21c6b62005-01-24 10:25:59 +00003234 /* Fill the index with data and reparse the schema. Code an OP_Expire
3235 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003236 */
danielk1977cbb18d22004-05-28 11:37:27 +00003237 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003238 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003239 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003240 sqlite3VdbeAddParseSchemaOp(v, iDb,
3241 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003242 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003243 }
drh75897232000-05-29 14:26:00 +00003244 }
3245
danielk1977d8123362004-06-12 09:25:12 +00003246 /* When adding an index to the list of indices for a table, make
3247 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003248 ** OE_Ignore. This is necessary for the correct constraint check
3249 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3250 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003251 */
drh234c39d2004-07-24 03:30:47 +00003252 if( db->init.busy || pTblName==0 ){
3253 if( onError!=OE_Replace || pTab->pIndex==0
3254 || pTab->pIndex->onError==OE_Replace){
3255 pIndex->pNext = pTab->pIndex;
3256 pTab->pIndex = pIndex;
3257 }else{
3258 Index *pOther = pTab->pIndex;
3259 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3260 pOther = pOther->pNext;
3261 }
3262 pIndex->pNext = pOther->pNext;
3263 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003264 }
dan1da40a32009-09-19 17:00:31 +00003265 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003266 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003267 }
danielk1977d8123362004-06-12 09:25:12 +00003268
drh75897232000-05-29 14:26:00 +00003269 /* Clean up before exiting */
3270exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003271 if( pIndex ) freeIndex(db, pIndex);
3272 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003273 sqlite3ExprListDelete(db, pList);
3274 sqlite3SrcListDelete(db, pTblName);
3275 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003276 return pRet;
drh75897232000-05-29 14:26:00 +00003277}
3278
3279/*
drh51147ba2005-07-23 22:59:55 +00003280** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003281** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003282**
peter.d.reid60ec9142014-09-06 16:39:46 +00003283** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003284** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3285** number of rows in the table that match any particular value of the
3286** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003287** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003288** of the index. And so forth. It must always be the case that
3289*
3290** aiRowEst[N]<=aiRowEst[N-1]
3291** aiRowEst[N]>=1
3292**
3293** Apart from that, we have little to go on besides intuition as to
3294** how aiRowEst[] should be initialized. The numbers generated here
3295** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003296*/
3297void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003298 /* 10, 9, 8, 7, 6 */
3299 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003300 LogEst *a = pIdx->aiRowLogEst;
3301 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003302 int i;
dancfc9df72014-04-25 15:01:01 +00003303
dan264d2b92014-04-29 19:01:57 +00003304 /* Set the first entry (number of rows in the index) to the estimated
3305 ** number of rows in the table. Or 10, if the estimated number of rows
3306 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003307 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003308 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3309
3310 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3311 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003312 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003313 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3314 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003315 }
dan264d2b92014-04-29 19:01:57 +00003316
3317 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003318 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003319}
3320
3321/*
drh74e24cd2002-01-09 03:19:59 +00003322** This routine will drop an existing named index. This routine
3323** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003324*/
drh4d91a702006-01-04 15:54:36 +00003325void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003326 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003327 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003328 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003329 int iDb;
drh75897232000-05-29 14:26:00 +00003330
drh8af73d42009-05-13 22:58:28 +00003331 assert( pParse->nErr==0 ); /* Never called with prior errors */
3332 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003333 goto exit_drop_index;
3334 }
drhd24cc422003-03-27 12:51:24 +00003335 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003336 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3337 goto exit_drop_index;
3338 }
danielk19774adee202004-05-08 08:23:19 +00003339 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003340 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003341 if( !ifExists ){
3342 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003343 }else{
3344 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003345 }
drha6ecd332004-06-10 00:29:09 +00003346 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003347 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003348 }
drh48dd1d82014-05-27 18:18:58 +00003349 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003350 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003351 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003352 goto exit_drop_index;
3353 }
danielk1977da184232006-01-05 11:34:32 +00003354 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003355#ifndef SQLITE_OMIT_AUTHORIZATION
3356 {
3357 int code = SQLITE_DROP_INDEX;
3358 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003359 const char *zDb = db->aDb[iDb].zName;
3360 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003361 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003362 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003363 }
danielk1977da184232006-01-05 11:34:32 +00003364 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003365 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003366 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003367 }
drhed6c8672003-01-12 18:02:16 +00003368 }
drhe5f9c642003-01-13 23:27:31 +00003369#endif
drh75897232000-05-29 14:26:00 +00003370
3371 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003372 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003373 if( v ){
drh77658e22007-12-04 16:54:52 +00003374 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003375 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003376 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003377 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003378 );
drha5ae4c32011-08-07 01:31:52 +00003379 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003380 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003381 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003382 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003383 }
3384
drhd24cc422003-03-27 12:51:24 +00003385exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003386 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003387}
3388
3389/*
dan9ace1122012-03-29 07:51:45 +00003390** pArray is a pointer to an array of objects. Each object in the
3391** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3392** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003393**
dan9ace1122012-03-29 07:51:45 +00003394** When this function is called, *pnEntry contains the current size of
3395** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3396** in total).
drh13449892005-09-07 21:22:45 +00003397**
dan9ace1122012-03-29 07:51:45 +00003398** If the realloc() is successful (i.e. if no OOM condition occurs), the
3399** space allocated for the new object is zeroed, *pnEntry updated to
3400** reflect the new size of the array and a pointer to the new allocation
3401** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003402**
dan9ace1122012-03-29 07:51:45 +00003403** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3404** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003405*/
drhcf643722007-03-27 13:36:37 +00003406void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003407 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003408 void *pArray, /* Array of objects. Might be reallocated */
3409 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003410 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003411 int *pIdx /* Write the index of a new slot here */
3412){
3413 char *z;
drh6c535152012-02-02 03:38:30 +00003414 int n = *pnEntry;
3415 if( (n & (n-1))==0 ){
3416 int sz = (n==0) ? 1 : 2*n;
3417 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003418 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003419 *pIdx = -1;
3420 return pArray;
drh13449892005-09-07 21:22:45 +00003421 }
drhcf643722007-03-27 13:36:37 +00003422 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003423 }
drhcf643722007-03-27 13:36:37 +00003424 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003425 memset(&z[n * szEntry], 0, szEntry);
3426 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003427 ++*pnEntry;
3428 return pArray;
drh13449892005-09-07 21:22:45 +00003429}
3430
3431/*
drh75897232000-05-29 14:26:00 +00003432** Append a new element to the given IdList. Create a new IdList if
3433** need be.
drhdaffd0e2001-04-11 14:28:42 +00003434**
3435** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003436*/
drh17435752007-08-16 04:30:38 +00003437IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003438 int i;
drh75897232000-05-29 14:26:00 +00003439 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003440 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003441 if( pList==0 ) return 0;
3442 }
drhcf643722007-03-27 13:36:37 +00003443 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003444 db,
drhcf643722007-03-27 13:36:37 +00003445 pList->a,
3446 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003447 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003448 &i
3449 );
drh13449892005-09-07 21:22:45 +00003450 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003451 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003452 return 0;
drh75897232000-05-29 14:26:00 +00003453 }
drh17435752007-08-16 04:30:38 +00003454 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003455 return pList;
3456}
3457
3458/*
drhfe05af82005-07-21 03:14:59 +00003459** Delete an IdList.
3460*/
drh633e6d52008-07-28 19:34:53 +00003461void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003462 int i;
3463 if( pList==0 ) return;
3464 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003465 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003466 }
drh633e6d52008-07-28 19:34:53 +00003467 sqlite3DbFree(db, pList->a);
3468 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003469}
3470
3471/*
3472** Return the index in pList of the identifier named zId. Return -1
3473** if not found.
3474*/
3475int sqlite3IdListIndex(IdList *pList, const char *zName){
3476 int i;
3477 if( pList==0 ) return -1;
3478 for(i=0; i<pList->nId; i++){
3479 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3480 }
3481 return -1;
3482}
3483
3484/*
drha78c22c2008-11-11 18:28:58 +00003485** Expand the space allocated for the given SrcList object by
3486** creating nExtra new slots beginning at iStart. iStart is zero based.
3487** New slots are zeroed.
3488**
3489** For example, suppose a SrcList initially contains two entries: A,B.
3490** To append 3 new entries onto the end, do this:
3491**
3492** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3493**
3494** After the call above it would contain: A, B, nil, nil, nil.
3495** If the iStart argument had been 1 instead of 2, then the result
3496** would have been: A, nil, nil, nil, B. To prepend the new slots,
3497** the iStart value would be 0. The result then would
3498** be: nil, nil, nil, A, B.
3499**
3500** If a memory allocation fails the SrcList is unchanged. The
3501** db->mallocFailed flag will be set to true.
3502*/
3503SrcList *sqlite3SrcListEnlarge(
3504 sqlite3 *db, /* Database connection to notify of OOM errors */
3505 SrcList *pSrc, /* The SrcList to be enlarged */
3506 int nExtra, /* Number of new slots to add to pSrc->a[] */
3507 int iStart /* Index in pSrc->a[] of first new slot */
3508){
3509 int i;
3510
3511 /* Sanity checking on calling parameters */
3512 assert( iStart>=0 );
3513 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003514 assert( pSrc!=0 );
3515 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003516
3517 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003518 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003519 SrcList *pNew;
3520 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003521 int nGot;
drha78c22c2008-11-11 18:28:58 +00003522 pNew = sqlite3DbRealloc(db, pSrc,
3523 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3524 if( pNew==0 ){
3525 assert( db->mallocFailed );
3526 return pSrc;
3527 }
3528 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003529 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003530 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003531 }
3532
3533 /* Move existing slots that come after the newly inserted slots
3534 ** out of the way */
3535 for(i=pSrc->nSrc-1; i>=iStart; i--){
3536 pSrc->a[i+nExtra] = pSrc->a[i];
3537 }
drh6d1626e2014-03-05 15:52:43 +00003538 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003539
3540 /* Zero the newly allocated slots */
3541 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3542 for(i=iStart; i<iStart+nExtra; i++){
3543 pSrc->a[i].iCursor = -1;
3544 }
3545
3546 /* Return a pointer to the enlarged SrcList */
3547 return pSrc;
3548}
3549
3550
3551/*
drhad3cab52002-05-24 02:04:32 +00003552** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003553** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003554**
drha78c22c2008-11-11 18:28:58 +00003555** A SrcList is returned, or NULL if there is an OOM error. The returned
3556** SrcList might be the same as the SrcList that was input or it might be
3557** a new one. If an OOM error does occurs, then the prior value of pList
3558** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003559**
3560** If pDatabase is not null, it means that the table has an optional
3561** database name prefix. Like this: "database.table". The pDatabase
3562** points to the table name and the pTable points to the database name.
3563** The SrcList.a[].zName field is filled with the table name which might
3564** come from pTable (if pDatabase is NULL) or from pDatabase.
3565** SrcList.a[].zDatabase is filled with the database name from pTable,
3566** or with NULL if no database is specified.
3567**
3568** In other words, if call like this:
3569**
drh17435752007-08-16 04:30:38 +00003570** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003571**
3572** Then B is a table name and the database name is unspecified. If called
3573** like this:
3574**
drh17435752007-08-16 04:30:38 +00003575** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003576**
drhd3001712009-05-12 17:46:53 +00003577** Then C is the table name and B is the database name. If C is defined
3578** then so is B. In other words, we never have a case where:
3579**
3580** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003581**
3582** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3583** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003584*/
drh17435752007-08-16 04:30:38 +00003585SrcList *sqlite3SrcListAppend(
3586 sqlite3 *db, /* Connection to notify of malloc failures */
3587 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3588 Token *pTable, /* Table to append */
3589 Token *pDatabase /* Database of the table */
3590){
drha99db3b2004-06-19 14:49:12 +00003591 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003592 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003593 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003594 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003595 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003596 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003597 }
drha78c22c2008-11-11 18:28:58 +00003598 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3599 if( db->mallocFailed ){
3600 sqlite3SrcListDelete(db, pList);
3601 return 0;
drhad3cab52002-05-24 02:04:32 +00003602 }
drha78c22c2008-11-11 18:28:58 +00003603 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003604 if( pDatabase && pDatabase->z==0 ){
3605 pDatabase = 0;
3606 }
drhd3001712009-05-12 17:46:53 +00003607 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003608 Token *pTemp = pDatabase;
3609 pDatabase = pTable;
3610 pTable = pTemp;
3611 }
drh17435752007-08-16 04:30:38 +00003612 pItem->zName = sqlite3NameFromToken(db, pTable);
3613 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003614 return pList;
3615}
3616
3617/*
drhdfe88ec2008-11-03 20:55:06 +00003618** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003619*/
danielk19774adee202004-05-08 08:23:19 +00003620void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003621 int i;
drh9b3187e2005-01-18 14:45:47 +00003622 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003623 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003624 if( pList ){
3625 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3626 if( pItem->iCursor>=0 ) break;
3627 pItem->iCursor = pParse->nTab++;
3628 if( pItem->pSelect ){
3629 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3630 }
drh63eb5f22003-04-29 16:20:44 +00003631 }
3632 }
3633}
3634
3635/*
drhad3cab52002-05-24 02:04:32 +00003636** Delete an entire SrcList including all its substructure.
3637*/
drh633e6d52008-07-28 19:34:53 +00003638void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003639 int i;
drhbe5c89a2004-07-26 00:31:09 +00003640 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003641 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003642 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003643 sqlite3DbFree(db, pItem->zDatabase);
3644 sqlite3DbFree(db, pItem->zName);
3645 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003646 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003647 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003648 sqlite3SelectDelete(db, pItem->pSelect);
3649 sqlite3ExprDelete(db, pItem->pOn);
3650 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003651 }
drh633e6d52008-07-28 19:34:53 +00003652 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003653}
3654
drh982cef72000-05-30 16:27:03 +00003655/*
drh61dfc312006-12-16 16:25:15 +00003656** This routine is called by the parser to add a new term to the
3657** end of a growing FROM clause. The "p" parameter is the part of
3658** the FROM clause that has already been constructed. "p" is NULL
3659** if this is the first term of the FROM clause. pTable and pDatabase
3660** are the name of the table and database named in the FROM clause term.
3661** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003662** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003663** alias token. If the term is a subquery, then pSubquery is the
3664** SELECT statement that the subquery encodes. The pTable and
3665** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3666** parameters are the content of the ON and USING clauses.
3667**
3668** Return a new SrcList which encodes is the FROM with the new
3669** term added.
3670*/
3671SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003672 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003673 SrcList *p, /* The left part of the FROM clause already seen */
3674 Token *pTable, /* Name of the table to add to the FROM clause */
3675 Token *pDatabase, /* Name of the database containing pTable */
3676 Token *pAlias, /* The right-hand side of the AS subexpression */
3677 Select *pSubquery, /* A subquery used in place of a table name */
3678 Expr *pOn, /* The ON clause of a join */
3679 IdList *pUsing /* The USING clause of a join */
3680){
3681 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003682 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003683 if( !p && (pOn || pUsing) ){
3684 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3685 (pOn ? "ON" : "USING")
3686 );
3687 goto append_from_error;
3688 }
drh17435752007-08-16 04:30:38 +00003689 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003690 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003691 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003692 }
3693 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003694 assert( pAlias!=0 );
3695 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003696 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003697 }
3698 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003699 pItem->pOn = pOn;
3700 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003701 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003702
3703 append_from_error:
3704 assert( p==0 );
3705 sqlite3ExprDelete(db, pOn);
3706 sqlite3IdListDelete(db, pUsing);
3707 sqlite3SelectDelete(db, pSubquery);
3708 return 0;
drh61dfc312006-12-16 16:25:15 +00003709}
3710
3711/*
danielk1977b1c685b2008-10-06 16:18:39 +00003712** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3713** element of the source-list passed as the second argument.
3714*/
3715void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003716 assert( pIndexedBy!=0 );
3717 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003718 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3719 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3720 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3721 /* A "NOT INDEXED" clause was supplied. See parse.y
3722 ** construct "indexed_opt" for details. */
3723 pItem->notIndexed = 1;
3724 }else{
3725 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3726 }
3727 }
3728}
3729
3730/*
drh61dfc312006-12-16 16:25:15 +00003731** When building up a FROM clause in the parser, the join operator
3732** is initially attached to the left operand. But the code generator
3733** expects the join operator to be on the right operand. This routine
3734** Shifts all join operators from left to right for an entire FROM
3735** clause.
3736**
3737** Example: Suppose the join is like this:
3738**
3739** A natural cross join B
3740**
3741** The operator is "natural cross join". The A and B operands are stored
3742** in p->a[0] and p->a[1], respectively. The parser initially stores the
3743** operator with A. This routine shifts that operator over to B.
3744*/
3745void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003746 if( p ){
drh61dfc312006-12-16 16:25:15 +00003747 int i;
drhd017ab92011-08-23 00:01:58 +00003748 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003749 for(i=p->nSrc-1; i>0; i--){
3750 p->a[i].jointype = p->a[i-1].jointype;
3751 }
3752 p->a[0].jointype = 0;
3753 }
3754}
3755
3756/*
drhc4a3c772001-04-04 11:48:57 +00003757** Begin a transaction
3758*/
drh684917c2004-10-05 02:41:42 +00003759void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003760 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003761 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003762 int i;
drh5e00f6c2001-09-13 13:46:56 +00003763
drhd3001712009-05-12 17:46:53 +00003764 assert( pParse!=0 );
3765 db = pParse->db;
3766 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003767/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003768 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3769 return;
3770 }
danielk19771d850a72004-05-31 08:26:49 +00003771 v = sqlite3GetVdbe(pParse);
3772 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003773 if( type!=TK_DEFERRED ){
3774 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003775 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003776 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003777 }
3778 }
drh66a51672008-01-03 00:01:23 +00003779 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003780}
3781
3782/*
3783** Commit a transaction
3784*/
danielk19774adee202004-05-08 08:23:19 +00003785void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003786 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003787
drhd3001712009-05-12 17:46:53 +00003788 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003789 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003790 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3791 return;
3792 }
danielk19771d850a72004-05-31 08:26:49 +00003793 v = sqlite3GetVdbe(pParse);
3794 if( v ){
drh66a51672008-01-03 00:01:23 +00003795 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003796 }
drhc4a3c772001-04-04 11:48:57 +00003797}
3798
3799/*
3800** Rollback a transaction
3801*/
danielk19774adee202004-05-08 08:23:19 +00003802void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003803 Vdbe *v;
3804
drhd3001712009-05-12 17:46:53 +00003805 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003806 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003807 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3808 return;
3809 }
danielk19774adee202004-05-08 08:23:19 +00003810 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003811 if( v ){
drh66a51672008-01-03 00:01:23 +00003812 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003813 }
drhc4a3c772001-04-04 11:48:57 +00003814}
drhf57b14a2001-09-14 18:54:08 +00003815
3816/*
danielk1977fd7f0452008-12-17 17:30:26 +00003817** This function is called by the parser when it parses a command to create,
3818** release or rollback an SQL savepoint.
3819*/
3820void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003821 char *zName = sqlite3NameFromToken(pParse->db, pName);
3822 if( zName ){
3823 Vdbe *v = sqlite3GetVdbe(pParse);
3824#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003825 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003826 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3827#endif
3828 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3829 sqlite3DbFree(pParse->db, zName);
3830 return;
3831 }
3832 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003833 }
3834}
3835
3836/*
drhdc3ff9c2004-08-18 02:10:15 +00003837** Make sure the TEMP database is open and available for use. Return
3838** the number of errors. Leave any error messages in the pParse structure.
3839*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003840int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003841 sqlite3 *db = pParse->db;
3842 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003843 int rc;
drh10a76c92010-01-26 01:25:26 +00003844 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003845 static const int flags =
3846 SQLITE_OPEN_READWRITE |
3847 SQLITE_OPEN_CREATE |
3848 SQLITE_OPEN_EXCLUSIVE |
3849 SQLITE_OPEN_DELETEONCLOSE |
3850 SQLITE_OPEN_TEMP_DB;
3851
dan3a6d8ae2011-04-23 15:54:54 +00003852 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003853 if( rc!=SQLITE_OK ){
3854 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3855 "file for storing temporary tables");
3856 pParse->rc = rc;
3857 return 1;
3858 }
drh10a76c92010-01-26 01:25:26 +00003859 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003860 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003861 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3862 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003863 return 1;
drh10a76c92010-01-26 01:25:26 +00003864 }
drhdc3ff9c2004-08-18 02:10:15 +00003865 }
3866 return 0;
3867}
3868
3869/*
drhaceb31b2014-02-08 01:40:27 +00003870** Record the fact that the schema cookie will need to be verified
3871** for database iDb. The code to actually verify the schema cookie
3872** will occur at the end of the top-level VDBE and will be generated
3873** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003874*/
danielk19774adee202004-05-08 08:23:19 +00003875void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003876 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003877 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003878
drhaceb31b2014-02-08 01:40:27 +00003879 assert( iDb>=0 && iDb<db->nDb );
3880 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3881 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3882 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003883 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3884 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003885 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3886 if( !OMIT_TEMPDB && iDb==1 ){
3887 sqlite3OpenTempDatabase(pToplevel);
3888 }
drh001bbcb2003-03-19 03:14:00 +00003889 }
drh001bbcb2003-03-19 03:14:00 +00003890}
3891
3892/*
dan57966752011-04-09 17:32:58 +00003893** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3894** attached database. Otherwise, invoke it for the database named zDb only.
3895*/
3896void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3897 sqlite3 *db = pParse->db;
3898 int i;
3899 for(i=0; i<db->nDb; i++){
3900 Db *pDb = &db->aDb[i];
3901 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3902 sqlite3CodeVerifySchema(pParse, i);
3903 }
3904 }
3905}
3906
3907/*
drh1c928532002-01-31 15:54:21 +00003908** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003909** might change the database.
3910**
3911** This routine starts a new transaction if we are not already within
3912** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003913** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003914** be set for operations that might fail (due to a constraint) part of
3915** the way through and which will need to undo some writes without having to
3916** rollback the whole transaction. For operations where all constraints
3917** can be checked before any changes are made to the database, it is never
3918** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003919*/
drh7f0f12e2004-05-21 13:39:50 +00003920void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003921 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003922 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00003923 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00003924 pToplevel->isMultiWrite |= setStatement;
3925}
3926
drhff738bc2009-09-24 00:09:58 +00003927/*
3928** Indicate that the statement currently under construction might write
3929** more than one entry (example: deleting one row then inserting another,
3930** inserting multiple rows in a table, or inserting a row and index entries.)
3931** If an abort occurs after some of these writes have completed, then it will
3932** be necessary to undo the completed writes.
3933*/
3934void sqlite3MultiWrite(Parse *pParse){
3935 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3936 pToplevel->isMultiWrite = 1;
3937}
3938
dane0af83a2009-09-08 19:15:01 +00003939/*
drhff738bc2009-09-24 00:09:58 +00003940** The code generator calls this routine if is discovers that it is
3941** possible to abort a statement prior to completion. In order to
3942** perform this abort without corrupting the database, we need to make
3943** sure that the statement is protected by a statement transaction.
3944**
3945** Technically, we only need to set the mayAbort flag if the
3946** isMultiWrite flag was previously set. There is a time dependency
3947** such that the abort must occur after the multiwrite. This makes
3948** some statements involving the REPLACE conflict resolution algorithm
3949** go a little faster. But taking advantage of this time dependency
3950** makes it more difficult to prove that the code is correct (in
3951** particular, it prevents us from writing an effective
3952** implementation of sqlite3AssertMayAbort()) and so we have chosen
3953** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003954*/
3955void sqlite3MayAbort(Parse *pParse){
3956 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3957 pToplevel->mayAbort = 1;
3958}
3959
3960/*
3961** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3962** error. The onError parameter determines which (if any) of the statement
3963** and/or current transaction is rolled back.
3964*/
drhd91c1a12013-02-09 13:58:25 +00003965void sqlite3HaltConstraint(
3966 Parse *pParse, /* Parsing context */
3967 int errCode, /* extended error code */
3968 int onError, /* Constraint type */
3969 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003970 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3971 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003972){
dane0af83a2009-09-08 19:15:01 +00003973 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003974 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003975 if( onError==OE_Abort ){
3976 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003977 }
drhd91c1a12013-02-09 13:58:25 +00003978 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003979 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3980}
3981
3982/*
3983** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3984*/
3985void sqlite3UniqueConstraint(
3986 Parse *pParse, /* Parsing context */
3987 int onError, /* Constraint type */
3988 Index *pIdx /* The index that triggers the constraint */
3989){
3990 char *zErr;
3991 int j;
3992 StrAccum errMsg;
3993 Table *pTab = pIdx->pTable;
3994
3995 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
3996 errMsg.db = pParse->db;
3997 for(j=0; j<pIdx->nKeyCol; j++){
3998 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
3999 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004000 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004001 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004002 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004003 }
4004 zErr = sqlite3StrAccumFinish(&errMsg);
4005 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004006 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4007 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004008 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004009}
4010
4011
4012/*
4013** Code an OP_Halt due to non-unique rowid.
4014*/
4015void sqlite3RowidConstraint(
4016 Parse *pParse, /* Parsing context */
4017 int onError, /* Conflict resolution algorithm */
4018 Table *pTab /* The table with the non-unique rowid */
4019){
4020 char *zMsg;
4021 int rc;
4022 if( pTab->iPKey>=0 ){
4023 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4024 pTab->aCol[pTab->iPKey].zName);
4025 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4026 }else{
4027 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4028 rc = SQLITE_CONSTRAINT_ROWID;
4029 }
4030 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4031 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004032}
4033
drh4343fea2004-11-05 23:46:15 +00004034/*
4035** Check to see if pIndex uses the collating sequence pColl. Return
4036** true if it does and false if it does not.
4037*/
4038#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004039static int collationMatch(const char *zColl, Index *pIndex){
4040 int i;
drh04491712009-05-13 17:21:13 +00004041 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004042 for(i=0; i<pIndex->nColumn; i++){
4043 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004044 assert( z!=0 || pIndex->aiColumn[i]<0 );
4045 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004046 return 1;
4047 }
drh4343fea2004-11-05 23:46:15 +00004048 }
4049 return 0;
4050}
4051#endif
4052
4053/*
4054** Recompute all indices of pTab that use the collating sequence pColl.
4055** If pColl==0 then recompute all indices of pTab.
4056*/
4057#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004058static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004059 Index *pIndex; /* An index associated with pTab */
4060
4061 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004062 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004063 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4064 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004065 sqlite3RefillIndex(pParse, pIndex, -1);
4066 }
4067 }
4068}
4069#endif
4070
4071/*
4072** Recompute all indices of all tables in all databases where the
4073** indices use the collating sequence pColl. If pColl==0 then recompute
4074** all indices everywhere.
4075*/
4076#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004077static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004078 Db *pDb; /* A single database */
4079 int iDb; /* The database index number */
4080 sqlite3 *db = pParse->db; /* The database connection */
4081 HashElem *k; /* For looping over tables in pDb */
4082 Table *pTab; /* A table in the database */
4083
drh21206082011-04-04 18:22:02 +00004084 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004085 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004086 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004087 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004088 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004089 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004090 }
4091 }
4092}
4093#endif
4094
4095/*
drheee46cf2004-11-06 00:02:48 +00004096** Generate code for the REINDEX command.
4097**
4098** REINDEX -- 1
4099** REINDEX <collation> -- 2
4100** REINDEX ?<database>.?<tablename> -- 3
4101** REINDEX ?<database>.?<indexname> -- 4
4102**
4103** Form 1 causes all indices in all attached databases to be rebuilt.
4104** Form 2 rebuilds all indices in all databases that use the named
4105** collating function. Forms 3 and 4 rebuild the named index or all
4106** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004107*/
4108#ifndef SQLITE_OMIT_REINDEX
4109void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4110 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4111 char *z; /* Name of a table or index */
4112 const char *zDb; /* Name of the database */
4113 Table *pTab; /* A table in the database */
4114 Index *pIndex; /* An index associated with pTab */
4115 int iDb; /* The database index number */
4116 sqlite3 *db = pParse->db; /* The database connection */
4117 Token *pObjName; /* Name of the table or index to be reindexed */
4118
danielk197733a5edc2005-01-27 00:22:02 +00004119 /* Read the database schema. If an error occurs, leave an error message
4120 ** and code in pParse and return NULL. */
4121 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004122 return;
danielk197733a5edc2005-01-27 00:22:02 +00004123 }
4124
drh8af73d42009-05-13 22:58:28 +00004125 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004126 reindexDatabases(pParse, 0);
4127 return;
drhd3001712009-05-12 17:46:53 +00004128 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004129 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004130 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004131 zColl = sqlite3NameFromToken(pParse->db, pName1);
4132 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004133 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004134 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004135 reindexDatabases(pParse, zColl);
4136 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004137 return;
4138 }
drh633e6d52008-07-28 19:34:53 +00004139 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004140 }
4141 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4142 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004143 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004144 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004145 zDb = db->aDb[iDb].zName;
4146 pTab = sqlite3FindTable(db, z, zDb);
4147 if( pTab ){
4148 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004149 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004150 return;
4151 }
4152 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004153 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004154 if( pIndex ){
4155 sqlite3BeginWriteOperation(pParse, 0, iDb);
4156 sqlite3RefillIndex(pParse, pIndex, -1);
4157 return;
4158 }
4159 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4160}
4161#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004162
4163/*
drh2ec2fb22013-11-06 19:59:23 +00004164** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004165**
drh2ec2fb22013-11-06 19:59:23 +00004166** The KeyInfo structure for an index is cached in the Index object.
4167** So there might be multiple references to the returned pointer. The
4168** caller should not try to modify the KeyInfo object.
4169**
4170** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4171** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004172*/
drh2ec2fb22013-11-06 19:59:23 +00004173KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004174 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004175#ifndef SQLITE_OMIT_SHARED_CACHE
4176 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4177 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4178 pIdx->pKeyInfo = 0;
4179 }
4180#endif
drh2ec2fb22013-11-06 19:59:23 +00004181 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004182 int i;
4183 int nCol = pIdx->nColumn;
4184 int nKey = pIdx->nKeyCol;
4185 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004186 if( pIdx->uniqNotNull ){
4187 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4188 }else{
4189 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4190 }
4191 if( pKey ){
4192 assert( sqlite3KeyInfoIsWriteable(pKey) );
4193 for(i=0; i<nCol; i++){
4194 char *zColl = pIdx->azColl[i];
drhb8a9bb42013-12-06 22:45:31 +00004195 assert( zColl!=0 );
4196 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4197 sqlite3LocateCollSeq(pParse, zColl);
drh2ec2fb22013-11-06 19:59:23 +00004198 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4199 }
4200 if( pParse->nErr ){
4201 sqlite3KeyInfoUnref(pKey);
4202 }else{
4203 pIdx->pKeyInfo = pKey;
4204 }
danielk1977b3bf5562006-01-10 17:58:23 +00004205 }
danielk1977b3bf5562006-01-10 17:58:23 +00004206 }
drh2ec2fb22013-11-06 19:59:23 +00004207 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004208}
drh8b471862014-01-11 13:22:17 +00004209
4210#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004211/*
4212** This routine is invoked once per CTE by the parser while parsing a
4213** WITH clause.
drh8b471862014-01-11 13:22:17 +00004214*/
dan7d562db2014-01-11 19:19:36 +00004215With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004216 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004217 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004218 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004219 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004220 Select *pQuery /* Query used to initialize the table */
4221){
dan4e9119d2014-01-13 15:12:23 +00004222 sqlite3 *db = pParse->db;
4223 With *pNew;
4224 char *zName;
4225
4226 /* Check that the CTE name is unique within this WITH clause. If
4227 ** not, store an error in the Parse structure. */
4228 zName = sqlite3NameFromToken(pParse->db, pName);
4229 if( zName && pWith ){
4230 int i;
4231 for(i=0; i<pWith->nCte; i++){
4232 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004233 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004234 }
4235 }
4236 }
4237
4238 if( pWith ){
4239 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4240 pNew = sqlite3DbRealloc(db, pWith, nByte);
4241 }else{
4242 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4243 }
4244 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004245 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004246
4247 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004248 sqlite3ExprListDelete(db, pArglist);
4249 sqlite3SelectDelete(db, pQuery);
4250 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004251 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004252 }else{
4253 pNew->a[pNew->nCte].pSelect = pQuery;
4254 pNew->a[pNew->nCte].pCols = pArglist;
4255 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004256 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004257 pNew->nCte++;
4258 }
4259
4260 return pNew;
drh8b471862014-01-11 13:22:17 +00004261}
4262
dan7d562db2014-01-11 19:19:36 +00004263/*
4264** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004265*/
dan7d562db2014-01-11 19:19:36 +00004266void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004267 if( pWith ){
4268 int i;
4269 for(i=0; i<pWith->nCte; i++){
4270 struct Cte *pCte = &pWith->a[i];
4271 sqlite3ExprListDelete(db, pCte->pCols);
4272 sqlite3SelectDelete(db, pCte->pSelect);
4273 sqlite3DbFree(db, pCte->zName);
4274 }
4275 sqlite3DbFree(db, pWith);
4276 }
drh8b471862014-01-11 13:22:17 +00004277}
4278#endif /* !defined(SQLITE_OMIT_CTE) */