blob: 65f94d2348adab980e6fbf9699f1ed5779243b8b [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;
drh205f48e2004-11-05 00:43:11 +0000145 if( pParse->nested ) return;
drhd99d2832015-04-17 15:58:33 +0000146 if( db->mallocFailed || pParse->nErr ){
147 if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
148 return;
149 }
danielk197748d0d862005-02-01 03:09:52 +0000150
drh80242052004-06-09 00:48:12 +0000151 /* Begin by generating some termination code at the end of the
152 ** vdbe program
153 */
drh80242052004-06-09 00:48:12 +0000154 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000155 assert( !pParse->isMultiWrite
156 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000157 if( v ){
drh61019c72014-01-04 16:49:02 +0000158 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
drh66a51672008-01-03 00:01:23 +0000159 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000160
drhb2445d52014-09-11 14:01:41 +0000161#if SQLITE_USER_AUTHENTICATION
162 if( pParse->nTableLock>0 && db->init.busy==0 ){
drh7883ecf2014-09-11 16:19:31 +0000163 sqlite3UserAuthInit(db);
drhb2445d52014-09-11 14:01:41 +0000164 if( db->auth.authLevel<UAUTH_User ){
drh7883ecf2014-09-11 16:19:31 +0000165 pParse->rc = SQLITE_AUTH_USER;
166 sqlite3ErrorMsg(pParse, "user not authenticated");
167 return;
drhb2445d52014-09-11 14:01:41 +0000168 }
169 }
170#endif
171
drh0e3d7472004-06-19 17:33:07 +0000172 /* The cookie mask contains one bit for each database file open.
173 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
174 ** set for each database that is used. Generate code to start a
175 ** transaction on each used database and to verify the schema cookie
176 ** on each used database.
177 */
drha7ab6d82014-07-21 15:44:39 +0000178 if( db->mallocFailed==0
179 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
180 ){
drhaceb31b2014-02-08 01:40:27 +0000181 int iDb, i;
182 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
183 sqlite3VdbeJumpHere(v, 0);
drha7ab6d82014-07-21 15:44:39 +0000184 for(iDb=0; iDb<db->nDb; iDb++){
185 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000186 sqlite3VdbeUsesBtree(v, iDb);
drhb22f7c82014-02-06 23:56:27 +0000187 sqlite3VdbeAddOp4Int(v,
188 OP_Transaction, /* Opcode */
189 iDb, /* P1 */
drha7ab6d82014-07-21 15:44:39 +0000190 DbMaskTest(pParse->writeMask,iDb), /* P2 */
drhb22f7c82014-02-06 23:56:27 +0000191 pParse->cookieValue[iDb], /* P3 */
192 db->aDb[iDb].pSchema->iGeneration /* P4 */
193 );
194 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
dan076e0f92015-09-28 15:20:58 +0000195 VdbeComment((v,
196 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
drh80242052004-06-09 00:48:12 +0000197 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000198#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000199 for(i=0; i<pParse->nVtabLock; i++){
200 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
201 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000202 }
drhf30a9692013-11-15 01:10:18 +0000203 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000204#endif
danielk1977c00da102006-01-07 13:21:04 +0000205
206 /* Once all the cookies have been verified and transactions opened,
207 ** obtain the required table-locks. This is a no-op unless the
208 ** shared-cache feature is enabled.
209 */
210 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000211
212 /* Initialize any AUTOINCREMENT data structures required.
213 */
214 sqlite3AutoincrementBegin(pParse);
215
drhf30a9692013-11-15 01:10:18 +0000216 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000217 if( pParse->pConstExpr ){
218 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000219 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000220 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000221 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000222 }
223 }
224
drh0b9f50d2009-06-23 20:28:53 +0000225 /* Finally, jump back to the beginning of the executable code. */
drh076e85f2015-09-03 13:46:12 +0000226 sqlite3VdbeGoto(v, 1);
drh80242052004-06-09 00:48:12 +0000227 }
drh71c697e2004-08-08 23:39:19 +0000228 }
229
drh3f7d4e42004-07-24 14:35:58 +0000230
drh80242052004-06-09 00:48:12 +0000231 /* Get the VDBE program ready for execution
232 */
drh126a6e22015-04-15 04:10:50 +0000233 if( v && pParse->nErr==0 && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000234 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000235 /* A minimum of one cursor is required if autoincrement is used
236 * See ticket [a696379c1f08866] */
237 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000238 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000239 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000240 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000241 }else{
drh483750b2003-01-29 18:46:51 +0000242 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000243 }
drha226d052002-09-25 19:04:07 +0000244 pParse->nTab = 0;
245 pParse->nMem = 0;
246 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000247 pParse->nVar = 0;
drha7ab6d82014-07-21 15:44:39 +0000248 DbMaskZero(pParse->cookieMask);
drh75897232000-05-29 14:26:00 +0000249}
250
251/*
drh205f48e2004-11-05 00:43:11 +0000252** Run the parser and code generator recursively in order to generate
253** code for the SQL statement given onto the end of the pParse context
254** currently under construction. When the parser is run recursively
255** this way, the final OP_Halt is not appended and other initialization
256** and finalization steps are omitted because those are handling by the
257** outermost parser.
258**
259** Not everything is nestable. This facility is designed to permit
260** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000261** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000262*/
263void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
264 va_list ap;
265 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000266 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000267 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000268# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
269 char saveBuf[SAVE_SZ];
270
drh205f48e2004-11-05 00:43:11 +0000271 if( pParse->nErr ) return;
272 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
273 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000274 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000275 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000276 if( zSql==0 ){
277 return; /* A malloc must have failed */
278 }
drh205f48e2004-11-05 00:43:11 +0000279 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000280 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
281 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000282 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000283 sqlite3DbFree(db, zErrMsg);
284 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000285 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000286 pParse->nested--;
287}
288
drhd4530972014-09-09 14:47:53 +0000289#if SQLITE_USER_AUTHENTICATION
290/*
291** Return TRUE if zTable is the name of the system table that stores the
292** list of users and their access credentials.
293*/
294int sqlite3UserAuthTable(const char *zTable){
295 return sqlite3_stricmp(zTable, "sqlite_user")==0;
296}
297#endif
298
drh205f48e2004-11-05 00:43:11 +0000299/*
danielk19778a414492004-06-29 08:59:35 +0000300** Locate the in-memory structure that describes a particular database
301** table given the name of that table and (optionally) the name of the
302** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000303**
danielk19778a414492004-06-29 08:59:35 +0000304** If zDatabase is 0, all databases are searched for the table and the
305** first matching table is returned. (No checking for duplicate table
306** names is done.) The search order is TEMP first, then MAIN, then any
307** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000308**
danielk19774adee202004-05-08 08:23:19 +0000309** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000310*/
drh9bb575f2004-09-06 17:24:11 +0000311Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000312 Table *p = 0;
313 int i;
drh9ca95732014-10-24 00:35:58 +0000314
drh21206082011-04-04 18:22:02 +0000315 /* All mutexes are required for schema access. Make sure we hold them. */
316 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
drhd4530972014-09-09 14:47:53 +0000317#if SQLITE_USER_AUTHENTICATION
318 /* Only the admin user is allowed to know that the sqlite_user table
319 ** exists */
drhe933b832014-09-10 17:34:28 +0000320 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
321 return 0;
322 }
drhd4530972014-09-09 14:47:53 +0000323#endif
danielk197753c0f742005-03-29 03:10:59 +0000324 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000325 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000326 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000327 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000328 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
drhd24cc422003-03-27 12:51:24 +0000329 if( p ) break;
330 }
drh74e24cd2002-01-09 03:19:59 +0000331 return p;
drh75897232000-05-29 14:26:00 +0000332}
333
334/*
danielk19778a414492004-06-29 08:59:35 +0000335** Locate the in-memory structure that describes a particular database
336** table given the name of that table and (optionally) the name of the
337** database containing the table. Return NULL if not found. Also leave an
338** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000339**
danielk19778a414492004-06-29 08:59:35 +0000340** The difference between this routine and sqlite3FindTable() is that this
341** routine leaves an error message in pParse->zErrMsg where
342** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000343*/
drhca424112008-01-25 15:04:48 +0000344Table *sqlite3LocateTable(
345 Parse *pParse, /* context in which to report errors */
346 int isView, /* True if looking for a VIEW rather than a TABLE */
347 const char *zName, /* Name of the table we are looking for */
348 const char *zDbase /* Name of the database. Might be NULL */
349){
drha69d9162003-04-17 22:57:53 +0000350 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000351
danielk19778a414492004-06-29 08:59:35 +0000352 /* Read the database schema. If an error occurs, leave an error message
353 ** and code in pParse and return NULL. */
354 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
355 return 0;
356 }
357
danielk19774adee202004-05-08 08:23:19 +0000358 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000359 if( p==0 ){
drhc7435792015-08-20 23:28:18 +0000360 const char *zMsg = isView ? "no such view" : "no such table";
drhd2975922015-08-29 17:22:33 +0000361#ifndef SQLITE_OMIT_VIRTUALTABLE
drhb4d472f2015-09-08 20:26:09 +0000362 if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
363 /* If zName is the not the name of a table in the schema created using
364 ** CREATE, then check to see if it is the name of an virtual table that
365 ** can be an eponymous virtual table. */
366 Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
367 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
368 return pMod->pEpoTab;
369 }
drh51be3872015-08-19 02:32:25 +0000370 }
371#endif
danielk19778a414492004-06-29 08:59:35 +0000372 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000373 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000374 }else{
drhca424112008-01-25 15:04:48 +0000375 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000376 }
drha6ecd332004-06-10 00:29:09 +0000377 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000378 }
drhb1ff9062015-09-14 14:49:23 +0000379#if SQLITE_USER_AUTHENTICATION
drhe933b832014-09-10 17:34:28 +0000380 else if( pParse->db->auth.authLevel<UAUTH_User ){
381 sqlite3ErrorMsg(pParse, "user not authenticated");
382 p = 0;
383 }
384#endif
drha69d9162003-04-17 22:57:53 +0000385 return p;
386}
387
388/*
dan41fb5cd2012-10-04 19:33:00 +0000389** Locate the table identified by *p.
390**
391** This is a wrapper around sqlite3LocateTable(). The difference between
392** sqlite3LocateTable() and this function is that this function restricts
393** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
394** non-NULL if it is part of a view or trigger program definition. See
395** sqlite3FixSrcList() for details.
396*/
397Table *sqlite3LocateTableItem(
398 Parse *pParse,
399 int isView,
400 struct SrcList_item *p
401){
402 const char *zDb;
403 assert( p->pSchema==0 || p->zDatabase==0 );
404 if( p->pSchema ){
405 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
406 zDb = pParse->db->aDb[iDb].zName;
407 }else{
408 zDb = p->zDatabase;
409 }
410 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
411}
412
413/*
drha69d9162003-04-17 22:57:53 +0000414** Locate the in-memory structure that describes
415** a particular index given the name of that index
416** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000417** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000418**
419** If zDatabase is 0, all databases are searched for the
420** table and the first matching index is returned. (No checking
421** for duplicate index names is done.) The search order is
422** TEMP first, then MAIN, then any auxiliary databases added
423** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000424*/
drh9bb575f2004-09-06 17:24:11 +0000425Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000426 Index *p = 0;
427 int i;
drh21206082011-04-04 18:22:02 +0000428 /* All mutexes are required for schema access. Make sure we hold them. */
429 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000430 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000431 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000432 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000433 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000434 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000435 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000436 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000437 if( p ) break;
438 }
drh74e24cd2002-01-09 03:19:59 +0000439 return p;
drh75897232000-05-29 14:26:00 +0000440}
441
442/*
drh956bc922004-07-24 17:38:29 +0000443** Reclaim the memory used by an index
444*/
dan1feeaed2010-07-23 15:41:47 +0000445static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000446#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000447 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000448#endif
drh1fe05372013-07-31 18:12:26 +0000449 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh1f9ca2c2015-08-25 16:57:52 +0000450 sqlite3ExprListDelete(db, p->aColExpr);
drh633e6d52008-07-28 19:34:53 +0000451 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000452 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh75b170b2014-10-04 00:07:44 +0000453#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
454 sqlite3_free(p->aiRowEst);
455#endif
drh633e6d52008-07-28 19:34:53 +0000456 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000457}
458
459/*
drhc96d8532005-05-03 12:30:33 +0000460** For the index called zIdxName which is found in the database iDb,
461** unlike that index from its Table then remove the index from
462** the index hash table and free all memory structures associated
463** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000464*/
drh9bb575f2004-09-06 17:24:11 +0000465void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000466 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000467 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000468
drh21206082011-04-04 18:22:02 +0000469 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
470 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000471 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000472 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000473 if( pIndex->pTable->pIndex==pIndex ){
474 pIndex->pTable->pIndex = pIndex->pNext;
475 }else{
476 Index *p;
drh04491712009-05-13 17:21:13 +0000477 /* Justification of ALWAYS(); The index must be on the list of
478 ** indices. */
479 p = pIndex->pTable->pIndex;
480 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
481 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000482 p->pNext = pIndex->pNext;
483 }
drh5e00f6c2001-09-13 13:46:56 +0000484 }
dan1feeaed2010-07-23 15:41:47 +0000485 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000486 }
drh956bc922004-07-24 17:38:29 +0000487 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000488}
489
490/*
drh81028a42012-05-15 18:28:27 +0000491** Look through the list of open database files in db->aDb[] and if
492** any have been closed, remove them from the list. Reallocate the
493** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000494**
drh81028a42012-05-15 18:28:27 +0000495** Entry 0 (the "main" database) and entry 1 (the "temp" database)
496** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000497*/
drh81028a42012-05-15 18:28:27 +0000498void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000499 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000500 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000501 struct Db *pDb = &db->aDb[i];
502 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000503 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000504 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000505 continue;
506 }
507 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000508 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000509 }
drh8bf8dc92003-05-17 17:35:10 +0000510 j++;
drh1c2d8412003-03-31 00:30:47 +0000511 }
512 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
513 db->nDb = j;
514 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
515 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000516 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000517 db->aDb = db->aDbStatic;
518 }
drhe0bc4042002-06-25 01:09:11 +0000519}
520
521/*
drh81028a42012-05-15 18:28:27 +0000522** Reset the schema for the database at index iDb. Also reset the
523** TEMP schema.
524*/
525void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000526 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000527 assert( iDb<db->nDb );
528
529 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000530 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000531 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
532 assert( pDb->pSchema!=0 );
533 sqlite3SchemaClear(pDb->pSchema);
534
535 /* If any database other than TEMP is reset, then also reset TEMP
536 ** since TEMP might be holding triggers that reference tables in the
537 ** other database.
538 */
539 if( iDb!=1 ){
540 pDb = &db->aDb[1];
541 assert( pDb->pSchema!=0 );
542 sqlite3SchemaClear(pDb->pSchema);
543 }
544 return;
545}
546
547/*
548** Erase all schema information from all attached databases (including
549** "main" and "temp") for a single database connection.
550*/
551void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
552 int i;
553 sqlite3BtreeEnterAll(db);
554 for(i=0; i<db->nDb; i++){
555 Db *pDb = &db->aDb[i];
556 if( pDb->pSchema ){
557 sqlite3SchemaClear(pDb->pSchema);
558 }
559 }
560 db->flags &= ~SQLITE_InternChanges;
561 sqlite3VtabUnlockList(db);
562 sqlite3BtreeLeaveAll(db);
563 sqlite3CollapseDatabaseArray(db);
564}
565
566/*
drhe0bc4042002-06-25 01:09:11 +0000567** This routine is called when a commit occurs.
568*/
drh9bb575f2004-09-06 17:24:11 +0000569void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000570 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000571}
572
573/*
dand46def72010-07-24 11:28:28 +0000574** Delete memory allocated for the column names of a table or view (the
575** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000576*/
drh51be3872015-08-19 02:32:25 +0000577void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000578 int i;
579 Column *pCol;
580 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000581 if( (pCol = pTable->aCol)!=0 ){
582 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000583 sqlite3DbFree(db, pCol->zName);
584 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000585 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000586 sqlite3DbFree(db, pCol->zType);
587 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000588 }
drh633e6d52008-07-28 19:34:53 +0000589 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000590 }
drh956bc922004-07-24 17:38:29 +0000591}
592
593/*
drh75897232000-05-29 14:26:00 +0000594** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000595** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000596**
597** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000598** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000599** memory structures of the indices and foreign keys associated with
600** the table.
drh29ddd3a2012-05-15 12:49:32 +0000601**
602** The db parameter is optional. It is needed if the Table object
603** contains lookaside memory. (Table objects in the schema do not use
604** lookaside memory, but some ephemeral Table objects do.) Or the
605** db parameter can be used with db->pnBytesFreed to measure the memory
606** used by the Table object.
drh75897232000-05-29 14:26:00 +0000607*/
dan1feeaed2010-07-23 15:41:47 +0000608void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000609 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000610 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000611
dand46def72010-07-24 11:28:28 +0000612 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000613
drhed8a3bb2005-06-06 21:19:56 +0000614 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000615 if( !pTable ) return;
616 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000617
drh29ddd3a2012-05-15 12:49:32 +0000618 /* Record the number of outstanding lookaside allocations in schema Tables
619 ** prior to doing any free() operations. Since schema Tables do not use
620 ** lookaside, this number should not change. */
621 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
622 db->lookaside.nOut : 0 );
623
dand46def72010-07-24 11:28:28 +0000624 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000625 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
626 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000627 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000628 if( !db || db->pnBytesFreed==0 ){
629 char *zName = pIndex->zName;
630 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000631 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000632 );
drh21206082011-04-04 18:22:02 +0000633 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000634 assert( pOld==pIndex || pOld==0 );
635 }
636 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000637 }
638
dan1da40a32009-09-19 17:00:31 +0000639 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000640 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000641
642 /* Delete the Table structure itself.
643 */
drh51be3872015-08-19 02:32:25 +0000644 sqlite3DeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000645 sqlite3DbFree(db, pTable->zName);
646 sqlite3DbFree(db, pTable->zColAff);
647 sqlite3SelectDelete(db, pTable->pSelect);
drh2938f922012-03-07 19:13:29 +0000648 sqlite3ExprListDelete(db, pTable->pCheck);
drh078e4082010-07-28 19:17:51 +0000649#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000650 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000651#endif
drh633e6d52008-07-28 19:34:53 +0000652 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000653
654 /* Verify that no lookaside memory was used by schema tables */
655 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000656}
657
658/*
drh5edc3122001-09-13 21:53:09 +0000659** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000660** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000661*/
drh9bb575f2004-09-06 17:24:11 +0000662void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000663 Table *p;
drh956bc922004-07-24 17:38:29 +0000664 Db *pDb;
665
drhd229ca92002-01-09 13:30:41 +0000666 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000667 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000668 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000669 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000670 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000671 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000672 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000673 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000674 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000675}
676
677/*
drha99db3b2004-06-19 14:49:12 +0000678** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000679** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000680** is obtained from sqliteMalloc() and must be freed by the calling
681** function.
drh75897232000-05-29 14:26:00 +0000682**
drh24fb6272009-05-01 21:13:36 +0000683** Any quotation marks (ex: "name", 'name', [name], or `name`) that
684** surround the body of the token are removed.
685**
drhc96d8532005-05-03 12:30:33 +0000686** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000687** are not \000 terminated and are not persistent. The returned string
688** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000689*/
drh17435752007-08-16 04:30:38 +0000690char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000691 char *zName;
692 if( pName ){
drh17435752007-08-16 04:30:38 +0000693 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000694 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000695 }else{
696 zName = 0;
697 }
drh75897232000-05-29 14:26:00 +0000698 return zName;
699}
700
701/*
danielk1977cbb18d22004-05-28 11:37:27 +0000702** Open the sqlite_master table stored in database number iDb for
703** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000704*/
danielk1977c00da102006-01-07 13:21:04 +0000705void sqlite3OpenMasterTable(Parse *p, int iDb){
706 Vdbe *v = sqlite3GetVdbe(p);
707 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000708 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000709 if( p->nTab==0 ){
710 p->nTab = 1;
711 }
drhe0bc4042002-06-25 01:09:11 +0000712}
713
714/*
danielk197704103022009-02-03 16:51:24 +0000715** Parameter zName points to a nul-terminated buffer containing the name
716** of a database ("main", "temp" or the name of an attached db). This
717** function returns the index of the named database in db->aDb[], or
718** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000719*/
danielk197704103022009-02-03 16:51:24 +0000720int sqlite3FindDbName(sqlite3 *db, const char *zName){
721 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000722 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000723 Db *pDb;
724 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000725 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000726 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000727 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000728 break;
drh73c42a12004-11-20 18:13:10 +0000729 }
danielk1977cbb18d22004-05-28 11:37:27 +0000730 }
731 }
danielk1977576ec6b2005-01-21 11:55:25 +0000732 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000733}
734
danielk197704103022009-02-03 16:51:24 +0000735/*
736** The token *pName contains the name of a database (either "main" or
737** "temp" or the name of an attached db). This routine returns the
738** index of the named database in db->aDb[], or -1 if the named db
739** does not exist.
740*/
741int sqlite3FindDb(sqlite3 *db, Token *pName){
742 int i; /* Database number */
743 char *zName; /* Name we are searching for */
744 zName = sqlite3NameFromToken(db, pName);
745 i = sqlite3FindDbName(db, zName);
746 sqlite3DbFree(db, zName);
747 return i;
748}
749
drh0e3d7472004-06-19 17:33:07 +0000750/* The table or view or trigger name is passed to this routine via tokens
751** pName1 and pName2. If the table name was fully qualified, for example:
752**
753** CREATE TABLE xxx.yyy (...);
754**
755** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
756** the table name is not fully qualified, i.e.:
757**
758** CREATE TABLE yyy(...);
759**
760** Then pName1 is set to "yyy" and pName2 is "".
761**
762** This routine sets the *ppUnqual pointer to point at the token (pName1 or
763** pName2) that stores the unqualified table name. The index of the
764** database "xxx" is returned.
765*/
danielk1977ef2cb632004-05-29 02:37:19 +0000766int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000767 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000768 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000769 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
770 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000771){
drh0e3d7472004-06-19 17:33:07 +0000772 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000773 sqlite3 *db = pParse->db;
774
drhc4a64fa2009-05-11 20:53:28 +0000775 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000776 if( db->init.busy ) {
777 sqlite3ErrorMsg(pParse, "corrupt database");
shanedcc50b72008-11-13 18:29:50 +0000778 return -1;
779 }
danielk1977cbb18d22004-05-28 11:37:27 +0000780 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000781 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000782 if( iDb<0 ){
783 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000784 return -1;
785 }
786 }else{
787 assert( db->init.iDb==0 || db->init.busy );
788 iDb = db->init.iDb;
789 *pUnqual = pName1;
790 }
791 return iDb;
792}
793
794/*
danielk1977d8123362004-06-12 09:25:12 +0000795** This routine is used to check if the UTF-8 string zName is a legal
796** unqualified name for a new schema object (table, index, view or
797** trigger). All names are legal except those that begin with the string
798** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
799** is reserved for internal use.
800*/
801int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000802 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000803 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000804 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000805 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
806 return SQLITE_ERROR;
807 }
808 return SQLITE_OK;
809}
810
811/*
drh44156282013-10-23 22:23:03 +0000812** Return the PRIMARY KEY index of a table
813*/
814Index *sqlite3PrimaryKeyIndex(Table *pTab){
815 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000816 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000817 return p;
818}
819
820/*
821** Return the column of index pIdx that corresponds to table
822** column iCol. Return -1 if not found.
823*/
824i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
825 int i;
826 for(i=0; i<pIdx->nColumn; i++){
827 if( iCol==pIdx->aiColumn[i] ) return i;
828 }
829 return -1;
830}
831
832/*
drh75897232000-05-29 14:26:00 +0000833** Begin constructing a new table representation in memory. This is
834** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000835** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000836** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000837** flag is true if the table should be stored in the auxiliary database
838** file instead of in the main database file. This is normally the case
839** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000840** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000841**
drhf57b3392001-10-08 13:22:32 +0000842** The new table record is initialized and put in pParse->pNewTable.
843** As more of the CREATE TABLE statement is parsed, additional action
844** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000845** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000846** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000847*/
danielk19774adee202004-05-08 08:23:19 +0000848void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000849 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000850 Token *pName1, /* First part of the name of the table or view */
851 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000852 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000853 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000854 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000855 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000856){
drh75897232000-05-29 14:26:00 +0000857 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000858 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000859 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000860 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000861 int iDb; /* Database number to create the table in */
862 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000863
danielk1977cbb18d22004-05-28 11:37:27 +0000864 /* The table or view name to create is passed to this routine via tokens
865 ** pName1 and pName2. If the table name was fully qualified, for example:
866 **
867 ** CREATE TABLE xxx.yyy (...);
868 **
869 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
870 ** the table name is not fully qualified, i.e.:
871 **
872 ** CREATE TABLE yyy(...);
873 **
874 ** Then pName1 is set to "yyy" and pName2 is "".
875 **
876 ** The call below sets the pName pointer to point at the token (pName1 or
877 ** pName2) that stores the unqualified table name. The variable iDb is
878 ** set to the index of the database that the table or view is to be
879 ** created in.
880 */
danielk1977ef2cb632004-05-29 02:37:19 +0000881 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000882 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000883 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
884 /* If creating a temp table, the name may not be qualified. Unless
885 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000886 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000887 return;
888 }
danielk197753c0f742005-03-29 03:10:59 +0000889 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000890
891 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000892 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000893 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000894 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000895 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000896 }
drh1d85d932004-02-14 23:05:52 +0000897 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000898#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000899 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000900 {
901 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000902 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000903 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000904 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000905 }
drhe5f9c642003-01-13 23:27:31 +0000906 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000907 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000908 code = SQLITE_CREATE_TEMP_VIEW;
909 }else{
910 code = SQLITE_CREATE_VIEW;
911 }
912 }else{
danielk197753c0f742005-03-29 03:10:59 +0000913 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000914 code = SQLITE_CREATE_TEMP_TABLE;
915 }else{
916 code = SQLITE_CREATE_TABLE;
917 }
918 }
danielk1977f1a381e2006-06-16 08:01:02 +0000919 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000920 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000921 }
922 }
923#endif
drhf57b3392001-10-08 13:22:32 +0000924
drhf57b3392001-10-08 13:22:32 +0000925 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000926 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000927 ** it does. The exception is if the statement being parsed was passed
928 ** to an sqlite3_declare_vtab() call. In that case only the column names
929 ** and types will be used, so there is no need to test for namespace
930 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000931 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000932 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000933 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000934 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
935 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000936 }
dana16d1062010-09-28 17:37:28 +0000937 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000938 if( pTable ){
939 if( !noErr ){
940 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000941 }else{
drh33c59ec2015-04-19 20:39:17 +0000942 assert( !db->init.busy || CORRUPT_DB );
dan7687c832011-04-09 15:39:02 +0000943 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000944 }
945 goto begin_table_error;
946 }
drh8a8a0d12010-09-28 20:26:44 +0000947 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000948 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
949 goto begin_table_error;
950 }
drh75897232000-05-29 14:26:00 +0000951 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000952
danielk197726783a52007-08-29 14:06:22 +0000953 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000954 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000955 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000956 pParse->rc = SQLITE_NOMEM;
957 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000958 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000959 }
drh75897232000-05-29 14:26:00 +0000960 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000961 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000962 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000963 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000964 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000965 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000966 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000967
drh4794f732004-11-05 17:17:50 +0000968 /* If this is the magic sqlite_sequence table used by autoincrement,
969 ** then record a pointer to this table in the main database structure
970 ** so that INSERT can find the table easily.
971 */
972#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000973 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000974 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000975 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000976 }
977#endif
978
drh17f71932002-02-21 12:01:27 +0000979 /* Begin generating the code that will insert the table record into
980 ** the SQLITE_MASTER table. Note in particular that we must go ahead
981 ** and allocate the record number for the table entry now. Before any
982 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
983 ** indices to be created and the table record must come before the
984 ** indices. Hence, the record number for the table must be allocated
985 ** now.
986 */
danielk19774adee202004-05-08 08:23:19 +0000987 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drh728e0f92015-10-10 14:41:28 +0000988 int addr1;
drhe321c292006-01-12 01:56:43 +0000989 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000990 int reg1, reg2, reg3;
drh3c03afd2015-09-09 13:28:06 +0000991 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
992 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
drh0dd5cda2015-06-16 16:39:01 +0000993 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +0000994
danielk197720b1eaf2006-07-26 16:22:14 +0000995#ifndef SQLITE_OMIT_VIRTUALTABLE
996 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000997 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000998 }
999#endif
1000
danielk197736963fd2005-02-19 08:18:05 +00001001 /* If the file format and encoding in the database have not been set,
1002 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +00001003 */
drhb7654112008-01-12 12:48:07 +00001004 reg1 = pParse->regRowid = ++pParse->nMem;
1005 reg2 = pParse->regRoot = ++pParse->nMem;
1006 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +00001007 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +00001008 sqlite3VdbeUsesBtree(v, iDb);
drh728e0f92015-10-10 14:41:28 +00001009 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +00001010 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +00001011 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +00001012 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001013 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +00001014 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001015 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drh728e0f92015-10-10 14:41:28 +00001016 sqlite3VdbeJumpHere(v, addr1);
danielk1977d008cfe2004-06-19 02:22:10 +00001017
drh4794f732004-11-05 17:17:50 +00001018 /* This just creates a place-holder record in the sqlite_master table.
1019 ** The record created does not contain anything yet. It will be replaced
1020 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001021 **
drh0fa991b2009-03-21 16:19:26 +00001022 ** The rowid for the new entry is left in register pParse->regRowid.
1023 ** The root page number of the new table is left in reg pParse->regRoot.
1024 ** The rowid and root page number values are needed by the code that
1025 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001026 */
danielk1977f1a381e2006-06-16 08:01:02 +00001027#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1028 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001029 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001030 }else
1031#endif
1032 {
drh8a120f82013-11-01 17:59:53 +00001033 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001034 }
danielk1977c00da102006-01-07 13:21:04 +00001035 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001036 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
drh3c03afd2015-09-09 13:28:06 +00001037 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
drhb7654112008-01-12 12:48:07 +00001038 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1039 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001040 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001041 }
drh23bf66d2004-12-14 03:34:34 +00001042
1043 /* Normal (non-error) return. */
1044 return;
1045
1046 /* If an error occurs, we jump here */
1047begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001048 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001049 return;
drh75897232000-05-29 14:26:00 +00001050}
1051
drh03d69a62015-11-19 13:53:57 +00001052/* Set properties of a table column based on the (magical)
1053** name of the column.
1054*/
1055void sqlite3ColumnPropertiesFromName(Column *pCol){
1056#if SQLITE_ENABLE_HIDDEN_COLUMNS
1057 if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
1058 pCol->colFlags |= COLFLAG_HIDDEN;
1059 }
1060#endif
1061}
1062
1063
drh75897232000-05-29 14:26:00 +00001064/*
danielk1977c60e9b82005-01-31 12:42:29 +00001065** This macro is used to compare two strings in a case-insensitive manner.
1066** It is slightly faster than calling sqlite3StrICmp() directly, but
1067** produces larger code.
1068**
1069** WARNING: This macro is not compatible with the strcmp() family. It
1070** returns true if the two strings are equal, otherwise false.
1071*/
1072#define STRICMP(x, y) (\
1073sqlite3UpperToLower[*(unsigned char *)(x)]== \
1074sqlite3UpperToLower[*(unsigned char *)(y)] \
1075&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1076
1077/*
drh75897232000-05-29 14:26:00 +00001078** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001079**
1080** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001081** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001082** first to get things going. Then this routine is called for each
1083** column.
drh75897232000-05-29 14:26:00 +00001084*/
danielk19774adee202004-05-08 08:23:19 +00001085void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001086 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001087 int i;
drha99db3b2004-06-19 14:49:12 +00001088 char *z;
drhc9b84a12002-06-20 11:36:48 +00001089 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001090 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001091 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001092#if SQLITE_MAX_COLUMN
1093 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001094 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1095 return;
1096 }
drhbb4957f2008-03-20 14:03:29 +00001097#endif
danielk1977ae74e032008-12-23 11:11:51 +00001098 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001099 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001100 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001101 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001102 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001103 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001104 return;
1105 }
1106 }
drh75897232000-05-29 14:26:00 +00001107 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001108 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001109 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001110 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001111 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001112 return;
1113 }
drh6d4abfb2001-10-22 02:58:08 +00001114 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001115 }
drhc9b84a12002-06-20 11:36:48 +00001116 pCol = &p->aCol[p->nCol];
1117 memset(pCol, 0, sizeof(p->aCol[0]));
1118 pCol->zName = z;
drh03d69a62015-11-19 13:53:57 +00001119 sqlite3ColumnPropertiesFromName(pCol);
danielk1977a37cdde2004-05-16 11:15:36 +00001120
1121 /* If there is no type specified, columns have the default affinity
drh05883a32015-06-02 15:32:08 +00001122 ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
danielk19774f057f92004-06-08 00:02:33 +00001123 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001124 */
drh05883a32015-06-02 15:32:08 +00001125 pCol->affinity = SQLITE_AFF_BLOB;
drhfdaac672013-10-04 15:30:21 +00001126 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001127 p->nCol++;
drh75897232000-05-29 14:26:00 +00001128}
1129
1130/*
drh382c0242001-10-06 16:33:02 +00001131** This routine is called by the parser while in the middle of
1132** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1133** been seen on a column. This routine sets the notNull flag on
1134** the column currently under construction.
1135*/
danielk19774adee202004-05-08 08:23:19 +00001136void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001137 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001138 p = pParse->pNewTable;
1139 if( p==0 || NEVER(p->nCol<1) ) return;
1140 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001141}
1142
1143/*
danielk197752a83fb2005-01-31 12:56:44 +00001144** Scan the column type name zType (length nType) and return the
1145** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001146**
1147** This routine does a case-independent search of zType for the
1148** substrings in the following table. If one of the substrings is
1149** found, the corresponding affinity is returned. If zType contains
1150** more than one of the substrings, entries toward the top of
1151** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001152** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001153**
1154** Substring | Affinity
1155** --------------------------------
1156** 'INT' | SQLITE_AFF_INTEGER
1157** 'CHAR' | SQLITE_AFF_TEXT
1158** 'CLOB' | SQLITE_AFF_TEXT
1159** 'TEXT' | SQLITE_AFF_TEXT
drh05883a32015-06-02 15:32:08 +00001160** 'BLOB' | SQLITE_AFF_BLOB
drh8a512562005-11-14 22:29:05 +00001161** 'REAL' | SQLITE_AFF_REAL
1162** 'FLOA' | SQLITE_AFF_REAL
1163** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001164**
1165** If none of the substrings in the above table are found,
1166** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001167*/
drhfdaac672013-10-04 15:30:21 +00001168char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001169 u32 h = 0;
1170 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001171 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001172
drhfdaac672013-10-04 15:30:21 +00001173 if( zIn==0 ) return aff;
1174 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001175 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001176 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001177 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001178 aff = SQLITE_AFF_TEXT;
1179 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001180 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1181 aff = SQLITE_AFF_TEXT;
1182 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1183 aff = SQLITE_AFF_TEXT;
1184 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001185 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
drh05883a32015-06-02 15:32:08 +00001186 aff = SQLITE_AFF_BLOB;
drhd3037a42013-10-04 18:29:25 +00001187 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001188#ifndef SQLITE_OMIT_FLOATING_POINT
1189 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1190 && aff==SQLITE_AFF_NUMERIC ){
1191 aff = SQLITE_AFF_REAL;
1192 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1193 && aff==SQLITE_AFF_NUMERIC ){
1194 aff = SQLITE_AFF_REAL;
1195 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1196 && aff==SQLITE_AFF_NUMERIC ){
1197 aff = SQLITE_AFF_REAL;
1198#endif
danielk1977201f7162005-02-01 02:13:29 +00001199 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001200 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001201 break;
danielk197752a83fb2005-01-31 12:56:44 +00001202 }
1203 }
drhd3037a42013-10-04 18:29:25 +00001204
1205 /* If pszEst is not NULL, store an estimate of the field size. The
1206 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001207 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001208 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001209 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001210 if( zChar ){
1211 while( zChar[0] ){
1212 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001213 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001214 sqlite3GetInt32(zChar, &v);
1215 v = v/4 + 1;
1216 if( v>255 ) v = 255;
1217 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1218 break;
1219 }
1220 zChar++;
drhfdaac672013-10-04 15:30:21 +00001221 }
drhd3037a42013-10-04 18:29:25 +00001222 }else{
1223 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001224 }
drhfdaac672013-10-04 15:30:21 +00001225 }
1226 }
danielk1977b3dff962005-02-01 01:21:55 +00001227 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001228}
1229
1230/*
drh382c0242001-10-06 16:33:02 +00001231** This routine is called by the parser while in the middle of
1232** parsing a CREATE TABLE statement. The pFirst token is the first
1233** token in the sequence of tokens that describe the type of the
1234** column currently under construction. pLast is the last token
1235** in the sequence. Use this information to construct a string
1236** that contains the typename of the column and store that string
1237** in zType.
1238*/
drh487e2622005-06-25 18:42:14 +00001239void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001240 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001241 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001242
drhc4a64fa2009-05-11 20:53:28 +00001243 p = pParse->pNewTable;
1244 if( p==0 || NEVER(p->nCol<1) ) return;
1245 pCol = &p->aCol[p->nCol-1];
drh5f1d2fa2015-04-19 21:59:19 +00001246 assert( pCol->zType==0 || CORRUPT_DB );
1247 sqlite3DbFree(pParse->db, pCol->zType);
drhc4a64fa2009-05-11 20:53:28 +00001248 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001249 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001250}
1251
1252/*
danielk19777977a172004-11-09 12:44:37 +00001253** The expression is the default value for the most recently added column
1254** of the table currently under construction.
1255**
1256** Default value expressions must be constant. Raise an exception if this
1257** is not the case.
drhd9b02572001-04-15 00:37:09 +00001258**
1259** This routine is called by the parser while in the middle of
1260** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001261*/
drhb7916a72009-05-27 10:31:29 +00001262void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001263 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001264 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001265 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001266 p = pParse->pNewTable;
1267 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001268 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001269 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001270 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1271 pCol->zName);
1272 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001273 /* A copy of pExpr is used instead of the original, as pExpr contains
1274 ** tokens that point to volatile memory. The 'span' of the expression
1275 ** is required by pragma table_info.
1276 */
drh633e6d52008-07-28 19:34:53 +00001277 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001278 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1279 sqlite3DbFree(db, pCol->zDflt);
1280 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001281 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001282 }
danielk19777977a172004-11-09 12:44:37 +00001283 }
drhb7916a72009-05-27 10:31:29 +00001284 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001285}
1286
1287/*
drh153110a2015-11-01 21:19:13 +00001288** Backwards Compatibility Hack:
1289**
1290** Historical versions of SQLite accepted strings as column names in
1291** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1292**
1293** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1294** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1295**
1296** This is goofy. But to preserve backwards compatibility we continue to
1297** accept it. This routine does the necessary conversion. It converts
1298** the expression given in its argument from a TK_STRING into a TK_ID
1299** if the expression is just a TK_STRING with an optional COLLATE clause.
1300** If the epxression is anything other than TK_STRING, the expression is
1301** unchanged.
1302*/
1303static void sqlite3StringToId(Expr *p){
1304 if( p->op==TK_STRING ){
1305 p->op = TK_ID;
1306 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1307 p->pLeft->op = TK_ID;
1308 }
1309}
1310
1311/*
drh4a324312001-12-21 14:30:42 +00001312** Designate the PRIMARY KEY for the table. pList is a list of names
1313** of columns that form the primary key. If pList is NULL, then the
1314** most recently added column of the table is the primary key.
1315**
1316** A table can have at most one primary key. If the table already has
1317** a primary key (and this is the second primary key) then create an
1318** error.
1319**
1320** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001321** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001322** field of the table under construction to be the index of the
1323** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1324** no INTEGER PRIMARY KEY.
1325**
1326** If the key is not an INTEGER PRIMARY KEY, then create a unique
1327** index for the key. No index is created for INTEGER PRIMARY KEYs.
1328*/
drh205f48e2004-11-05 00:43:11 +00001329void sqlite3AddPrimaryKey(
1330 Parse *pParse, /* Parsing context */
1331 ExprList *pList, /* List of field names to be indexed */
1332 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001333 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1334 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001335){
drh4a324312001-12-21 14:30:42 +00001336 Table *pTab = pParse->pNewTable;
1337 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001338 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001339 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001340 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001341 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001342 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001343 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001344 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001345 }
drh7d10d5a2008-08-20 16:35:10 +00001346 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001347 if( pList==0 ){
1348 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001349 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001350 zType = pTab->aCol[iCol].zType;
1351 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001352 }else{
drh8ea30bf2013-10-22 01:18:17 +00001353 nTerm = pList->nExpr;
1354 for(i=0; i<nTerm; i++){
drh108aa002015-08-24 20:21:20 +00001355 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drh7d3d9da2015-09-01 00:42:52 +00001356 assert( pCExpr!=0 );
drh153110a2015-11-01 21:19:13 +00001357 sqlite3StringToId(pCExpr);
drh7d3d9da2015-09-01 00:42:52 +00001358 if( pCExpr->op==TK_ID ){
drh108aa002015-08-24 20:21:20 +00001359 const char *zCName = pCExpr->u.zToken;
1360 for(iCol=0; iCol<pTab->nCol; iCol++){
1361 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1362 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1363 zType = pTab->aCol[iCol].zType;
1364 break;
1365 }
drhd3d39e92004-05-20 22:16:29 +00001366 }
drh78100cc2003-08-23 22:40:53 +00001367 }
drh4a324312001-12-21 14:30:42 +00001368 }
1369 }
drh8ea30bf2013-10-22 01:18:17 +00001370 if( nTerm==1
1371 && zType && sqlite3StrICmp(zType, "INTEGER")==0
drhbc622bc2015-08-24 15:39:42 +00001372 && sortOrder!=SQLITE_SO_DESC
drh8ea30bf2013-10-22 01:18:17 +00001373 ){
drh4a324312001-12-21 14:30:42 +00001374 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001375 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001376 assert( autoInc==0 || autoInc==1 );
1377 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001378 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001379 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001380#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001381 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1382 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001383#endif
drh4a324312001-12-21 14:30:42 +00001384 }else{
dan1da40a32009-09-19 17:00:31 +00001385 Index *p;
drh8a9789b2013-08-01 03:36:59 +00001386 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001387 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001388 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001389 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
dan1da40a32009-09-19 17:00:31 +00001390 }
drhe0194f22003-02-26 13:52:51 +00001391 pList = 0;
drh4a324312001-12-21 14:30:42 +00001392 }
drhe0194f22003-02-26 13:52:51 +00001393
1394primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001395 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001396 return;
drh4a324312001-12-21 14:30:42 +00001397}
1398
1399/*
drhffe07b22005-11-03 00:41:17 +00001400** Add a new CHECK constraint to the table currently under construction.
1401*/
1402void sqlite3AddCheckConstraint(
1403 Parse *pParse, /* Parsing context */
1404 Expr *pCheckExpr /* The check expression */
1405){
1406#ifndef SQLITE_OMIT_CHECK
1407 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001408 sqlite3 *db = pParse->db;
1409 if( pTab && !IN_DECLARE_VTAB
1410 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1411 ){
drh2938f922012-03-07 19:13:29 +00001412 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1413 if( pParse->constraintName.n ){
1414 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1415 }
drh33e619f2009-05-28 01:00:55 +00001416 }else
drhffe07b22005-11-03 00:41:17 +00001417#endif
drh33e619f2009-05-28 01:00:55 +00001418 {
drh2938f922012-03-07 19:13:29 +00001419 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001420 }
drhffe07b22005-11-03 00:41:17 +00001421}
1422
1423/*
drhd3d39e92004-05-20 22:16:29 +00001424** Set the collation function of the most recently parsed table column
1425** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001426*/
danielk197739002502007-11-12 09:50:26 +00001427void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001428 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001429 int i;
danielk197739002502007-11-12 09:50:26 +00001430 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001431 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001432
danielk1977b8cbb872006-06-19 05:33:45 +00001433 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001434 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001435 db = pParse->db;
1436 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001437 if( !zColl ) return;
1438
drhc4a64fa2009-05-11 20:53:28 +00001439 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001440 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001441 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001442 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001443
1444 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1445 ** then an index may have been created on this column before the
1446 ** collation type was added. Correct this if it is the case.
1447 */
1448 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001449 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001450 if( pIdx->aiColumn[0]==i ){
1451 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001452 }
1453 }
danielk197739002502007-11-12 09:50:26 +00001454 }else{
drh633e6d52008-07-28 19:34:53 +00001455 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001456 }
danielk19777cedc8d2004-06-10 10:50:08 +00001457}
1458
danielk1977466be562004-06-10 02:16:01 +00001459/*
1460** This function returns the collation sequence for database native text
1461** encoding identified by the string zName, length nName.
1462**
1463** If the requested collation sequence is not available, or not available
1464** in the database native encoding, the collation factory is invoked to
1465** request it. If the collation factory does not supply such a sequence,
1466** and the sequence is available in another text encoding, then that is
1467** returned instead.
1468**
1469** If no versions of the requested collations sequence are available, or
1470** another error occurs, NULL is returned and an error message written into
1471** pParse.
drha34001c2007-02-02 12:44:37 +00001472**
1473** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1474** invokes the collation factory if the named collation cannot be found
1475** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001476**
1477** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001478*/
drhc4a64fa2009-05-11 20:53:28 +00001479CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001480 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001481 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001482 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001483 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001484
drhc4a64fa2009-05-11 20:53:28 +00001485 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001486 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001487 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001488 }
1489
danielk19770202b292004-06-09 09:55:16 +00001490 return pColl;
1491}
1492
1493
drh8e2ca022002-06-17 17:07:19 +00001494/*
drh3f7d4e42004-07-24 14:35:58 +00001495** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001496**
1497** The schema cookie is used to determine when the schema for the
1498** database changes. After each schema change, the cookie value
1499** changes. When a process first reads the schema it records the
1500** cookie. Thereafter, whenever it goes to access the database,
1501** it checks the cookie to make sure the schema has not changed
1502** since it was last read.
1503**
1504** This plan is not completely bullet-proof. It is possible for
1505** the schema to change multiple times and for the cookie to be
1506** set back to prior value. But schema changes are infrequent
1507** and the probability of hitting the same cookie value is only
1508** 1 chance in 2^32. So we're safe enough.
1509*/
drh9cbf3422008-01-17 16:22:13 +00001510void sqlite3ChangeCookie(Parse *pParse, int iDb){
1511 int r1 = sqlite3GetTempReg(pParse);
1512 sqlite3 *db = pParse->db;
1513 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001514 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001515 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001516 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001517 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001518}
1519
1520/*
drh969fa7c2002-02-18 18:30:32 +00001521** Measure the number of characters needed to output the given
1522** identifier. The number returned includes any quotes used
1523** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001524**
1525** The estimate is conservative. It might be larger that what is
1526** really needed.
drh969fa7c2002-02-18 18:30:32 +00001527*/
1528static int identLength(const char *z){
1529 int n;
drh17f71932002-02-21 12:01:27 +00001530 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001531 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001532 }
drh234c39d2004-07-24 03:30:47 +00001533 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001534}
1535
1536/*
danielk19771b870de2009-03-14 08:37:23 +00001537** The first parameter is a pointer to an output buffer. The second
1538** parameter is a pointer to an integer that contains the offset at
1539** which to write into the output buffer. This function copies the
1540** nul-terminated string pointed to by the third parameter, zSignedIdent,
1541** to the specified offset in the buffer and updates *pIdx to refer
1542** to the first byte after the last byte written before returning.
1543**
1544** If the string zSignedIdent consists entirely of alpha-numeric
1545** characters, does not begin with a digit and is not an SQL keyword,
1546** then it is copied to the output buffer exactly as it is. Otherwise,
1547** it is quoted using double-quotes.
1548*/
drhc4a64fa2009-05-11 20:53:28 +00001549static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001550 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001551 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001552 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001553
drh17f71932002-02-21 12:01:27 +00001554 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001555 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001556 }
drhc7407522014-01-10 20:38:12 +00001557 needQuote = sqlite3Isdigit(zIdent[0])
1558 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1559 || zIdent[j]!=0
1560 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001561
drh234c39d2004-07-24 03:30:47 +00001562 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001563 for(j=0; zIdent[j]; j++){
1564 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001565 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001566 }
drh234c39d2004-07-24 03:30:47 +00001567 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001568 z[i] = 0;
1569 *pIdx = i;
1570}
1571
1572/*
1573** Generate a CREATE TABLE statement appropriate for the given
1574** table. Memory to hold the text of the statement is obtained
1575** from sqliteMalloc() and must be freed by the calling function.
1576*/
drh1d34fde2009-02-03 15:50:33 +00001577static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001578 int i, k, n;
1579 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001580 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001581 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001582 n = 0;
drh234c39d2004-07-24 03:30:47 +00001583 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001584 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001585 }
1586 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001587 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001588 zSep = "";
1589 zSep2 = ",";
1590 zEnd = ")";
1591 }else{
1592 zSep = "\n ";
1593 zSep2 = ",\n ";
1594 zEnd = "\n)";
1595 }
drhe0bc4042002-06-25 01:09:11 +00001596 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001597 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001598 if( zStmt==0 ){
1599 db->mallocFailed = 1;
1600 return 0;
1601 }
drhbdb339f2009-02-02 18:03:21 +00001602 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001603 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001604 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001605 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001606 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001607 static const char * const azType[] = {
drh05883a32015-06-02 15:32:08 +00001608 /* SQLITE_AFF_BLOB */ "",
drh7ea31cc2014-09-18 14:36:00 +00001609 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001610 /* SQLITE_AFF_NUMERIC */ " NUM",
1611 /* SQLITE_AFF_INTEGER */ " INT",
1612 /* SQLITE_AFF_REAL */ " REAL"
1613 };
1614 int len;
1615 const char *zType;
1616
drh5bb3eb92007-05-04 13:15:55 +00001617 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001618 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001619 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001620 identPut(zStmt, &k, pCol->zName);
drh05883a32015-06-02 15:32:08 +00001621 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1622 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1623 testcase( pCol->affinity==SQLITE_AFF_BLOB );
drh7ea31cc2014-09-18 14:36:00 +00001624 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001625 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1626 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1627 testcase( pCol->affinity==SQLITE_AFF_REAL );
1628
drh05883a32015-06-02 15:32:08 +00001629 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
drhc4a64fa2009-05-11 20:53:28 +00001630 len = sqlite3Strlen30(zType);
drh05883a32015-06-02 15:32:08 +00001631 assert( pCol->affinity==SQLITE_AFF_BLOB
drhfdaac672013-10-04 15:30:21 +00001632 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001633 memcpy(&zStmt[k], zType, len);
1634 k += len;
1635 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001636 }
drh5bb3eb92007-05-04 13:15:55 +00001637 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001638 return zStmt;
1639}
1640
1641/*
drh7f9c5db2013-10-23 00:32:58 +00001642** Resize an Index object to hold N columns total. Return SQLITE_OK
1643** on success and SQLITE_NOMEM on an OOM error.
1644*/
1645static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1646 char *zExtra;
1647 int nByte;
1648 if( pIdx->nColumn>=N ) return SQLITE_OK;
1649 assert( pIdx->isResized==0 );
1650 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1651 zExtra = sqlite3DbMallocZero(db, nByte);
1652 if( zExtra==0 ) return SQLITE_NOMEM;
1653 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1654 pIdx->azColl = (char**)zExtra;
1655 zExtra += sizeof(char*)*N;
1656 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1657 pIdx->aiColumn = (i16*)zExtra;
1658 zExtra += sizeof(i16)*N;
1659 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1660 pIdx->aSortOrder = (u8*)zExtra;
1661 pIdx->nColumn = N;
1662 pIdx->isResized = 1;
1663 return SQLITE_OK;
1664}
1665
1666/*
drhfdaac672013-10-04 15:30:21 +00001667** Estimate the total row width for a table.
1668*/
drhe13e9f52013-10-05 19:18:00 +00001669static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001670 unsigned wTable = 0;
1671 const Column *pTabCol;
1672 int i;
1673 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1674 wTable += pTabCol->szEst;
1675 }
1676 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001677 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001678}
1679
1680/*
drhe13e9f52013-10-05 19:18:00 +00001681** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001682*/
drhe13e9f52013-10-05 19:18:00 +00001683static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001684 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001685 int i;
1686 const Column *aCol = pIdx->pTable->aCol;
1687 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001688 i16 x = pIdx->aiColumn[i];
1689 assert( x<pIdx->pTable->nCol );
1690 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001691 }
drhe13e9f52013-10-05 19:18:00 +00001692 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001693}
1694
drh7f9c5db2013-10-23 00:32:58 +00001695/* Return true if value x is found any of the first nCol entries of aiCol[]
1696*/
1697static int hasColumn(const i16 *aiCol, int nCol, int x){
1698 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1699 return 0;
1700}
1701
1702/*
drhc6bd4e42013-11-02 14:37:18 +00001703** This routine runs at the end of parsing a CREATE TABLE statement that
1704** has a WITHOUT ROWID clause. The job of this routine is to convert both
1705** internal schema data structures and the generated VDBE code so that they
1706** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1707** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001708**
drhc6bd4e42013-11-02 14:37:18 +00001709** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1710** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1711** data storage is a covering index btree.
1712** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001713** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001714** identified by the sqlite_master table entry of the table itself.
1715** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1716** schema to the rootpage from the main table.
1717** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1718** (5) Add all table columns to the PRIMARY KEY Index object
1719** so that the PRIMARY KEY is a covering index. The surplus
1720** columns are part of KeyInfo.nXField and are not used for
1721** sorting or lookup or uniqueness checks.
1722** (6) Replace the rowid tail on all automatically generated UNIQUE
1723** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001724*/
1725static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1726 Index *pIdx;
1727 Index *pPk;
1728 int nPk;
1729 int i, j;
1730 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001731 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001732
1733 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001734 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001735 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001736 */
1737 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001738 assert( v );
drh0ff287f2015-09-02 18:40:33 +00001739 sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
drhc6bd4e42013-11-02 14:37:18 +00001740 }
1741
drh7f9c5db2013-10-23 00:32:58 +00001742 /* Locate the PRIMARY KEY index. Or, if this table was originally
1743 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1744 */
1745 if( pTab->iPKey>=0 ){
1746 ExprList *pList;
drh108aa002015-08-24 20:21:20 +00001747 Token ipkToken;
1748 ipkToken.z = pTab->aCol[pTab->iPKey].zName;
1749 ipkToken.n = sqlite3Strlen30(ipkToken.z);
1750 pList = sqlite3ExprListAppend(pParse, 0,
1751 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
drh7f9c5db2013-10-23 00:32:58 +00001752 if( pList==0 ) return;
drh7f9c5db2013-10-23 00:32:58 +00001753 pList->a[0].sortOrder = pParse->iPkSortOrder;
1754 assert( pParse->pNewTable==pTab );
1755 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1756 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001757 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001758 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001759 }else{
1760 pPk = sqlite3PrimaryKeyIndex(pTab);
danc5b73582015-05-26 11:53:14 +00001761
1762 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1763 ** table entry. This is only required if currently generating VDBE
1764 ** code for a CREATE TABLE (not when parsing one as part of reading
1765 ** a database schema). */
1766 if( v ){
1767 assert( db->init.busy==0 );
drh0ff287f2015-09-02 18:40:33 +00001768 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
danc5b73582015-05-26 11:53:14 +00001769 }
1770
drhe385d882014-12-28 22:10:51 +00001771 /*
1772 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1773 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1774 ** code assumes the PRIMARY KEY contains no repeated columns.
1775 */
1776 for(i=j=1; i<pPk->nKeyCol; i++){
1777 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
1778 pPk->nColumn--;
1779 }else{
1780 pPk->aiColumn[j++] = pPk->aiColumn[i];
1781 }
1782 }
1783 pPk->nKeyCol = j;
drh7f9c5db2013-10-23 00:32:58 +00001784 }
drh12826092013-11-05 22:39:17 +00001785 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001786 assert( pPk!=0 );
1787 nPk = pPk->nKeyCol;
1788
drh1ffede82015-01-30 20:59:27 +00001789 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
1790 ** do not enforce this for imposter tables.) */
1791 if( !db->init.imposterTable ){
1792 for(i=0; i<nPk; i++){
1793 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1794 }
1795 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001796 }
1797
drhc6bd4e42013-11-02 14:37:18 +00001798 /* The root page of the PRIMARY KEY is the table root page */
1799 pPk->tnum = pTab->tnum;
1800
drh7f9c5db2013-10-23 00:32:58 +00001801 /* Update the in-memory representation of all UNIQUE indices by converting
1802 ** the final rowid column into one or more columns of the PRIMARY KEY.
1803 */
1804 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1805 int n;
drh48dd1d82014-05-27 18:18:58 +00001806 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001807 for(i=n=0; i<nPk; i++){
1808 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1809 }
drh5a9a37b2013-11-05 17:30:04 +00001810 if( n==0 ){
1811 /* This index is a superset of the primary key */
1812 pIdx->nColumn = pIdx->nKeyCol;
1813 continue;
1814 }
drh7f9c5db2013-10-23 00:32:58 +00001815 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1816 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001817 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001818 pIdx->aiColumn[j] = pPk->aiColumn[i];
1819 pIdx->azColl[j] = pPk->azColl[i];
1820 j++;
1821 }
1822 }
drh00012df2013-11-05 01:59:07 +00001823 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1824 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001825 }
1826
1827 /* Add all table columns to the PRIMARY KEY index
1828 */
1829 if( nPk<pTab->nCol ){
1830 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1831 for(i=0, j=nPk; i<pTab->nCol; i++){
1832 if( !hasColumn(pPk->aiColumn, j, i) ){
1833 assert( j<pPk->nColumn );
1834 pPk->aiColumn[j] = i;
1835 pPk->azColl[j] = "BINARY";
1836 j++;
1837 }
1838 }
1839 assert( pPk->nColumn==j );
1840 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001841 }else{
1842 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001843 }
1844}
1845
drhfdaac672013-10-04 15:30:21 +00001846/*
drh75897232000-05-29 14:26:00 +00001847** This routine is called to report the final ")" that terminates
1848** a CREATE TABLE statement.
1849**
drhf57b3392001-10-08 13:22:32 +00001850** The table structure that other action routines have been building
1851** is added to the internal hash tables, assuming no errors have
1852** occurred.
drh75897232000-05-29 14:26:00 +00001853**
drh1d85d932004-02-14 23:05:52 +00001854** An entry for the table is made in the master table on disk, unless
1855** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001856** it means we are reading the sqlite_master table because we just
1857** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001858** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001859** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001860**
1861** If the pSelect argument is not NULL, it means that this routine
1862** was called to create a table generated from a
1863** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1864** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001865*/
danielk197719a8e7e2005-03-17 05:03:38 +00001866void sqlite3EndTable(
1867 Parse *pParse, /* Parse context */
1868 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001869 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1870 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001871 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1872){
drhfdaac672013-10-04 15:30:21 +00001873 Table *p; /* The new table */
1874 sqlite3 *db = pParse->db; /* The database connection */
1875 int iDb; /* Database in which the table lives */
1876 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001877
drh027616d2015-08-08 22:47:47 +00001878 if( pEnd==0 && pSelect==0 ){
drh5969da42013-10-21 02:14:45 +00001879 return;
danielk1977261919c2005-12-06 12:52:59 +00001880 }
drh834f9972015-08-08 23:23:33 +00001881 assert( !db->mallocFailed );
drh28037572000-08-02 13:47:41 +00001882 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001883 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001884
danielk1977517eb642004-06-07 10:00:31 +00001885 assert( !db->init.busy || !pSelect );
1886
drhc6bd4e42013-11-02 14:37:18 +00001887 /* If the db->init.busy is 1 it means we are reading the SQL off the
1888 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1889 ** So do not write to the disk again. Extract the root page number
1890 ** for the table from the db->init.newTnum field. (The page number
1891 ** should have been put there by the sqliteOpenCb routine.)
1892 */
1893 if( db->init.busy ){
1894 p->tnum = db->init.newTnum;
1895 }
1896
1897 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001898 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001899 if( (p->tabFlags & TF_Autoincrement) ){
1900 sqlite3ErrorMsg(pParse,
1901 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1902 return;
1903 }
drh5969da42013-10-21 02:14:45 +00001904 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001905 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001906 }else{
drhfccda8a2015-05-27 13:06:55 +00001907 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
drh7f9c5db2013-10-23 00:32:58 +00001908 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001909 }
1910 }
1911
drhb9bb7c12006-06-11 23:41:55 +00001912 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001913
drhffe07b22005-11-03 00:41:17 +00001914#ifndef SQLITE_OMIT_CHECK
1915 /* Resolve names in all CHECK constraint expressions.
1916 */
1917 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001918 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001919 }
1920#endif /* !defined(SQLITE_OMIT_CHECK) */
1921
drhe13e9f52013-10-05 19:18:00 +00001922 /* Estimate the average row size for the table and for all implied indices */
1923 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001924 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001925 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001926 }
1927
drhe3c41372001-09-17 20:25:58 +00001928 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001929 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001930 **
drhe0bc4042002-06-25 01:09:11 +00001931 ** If this is a TEMPORARY table, write the entry into the auxiliary
1932 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001933 */
drh1d85d932004-02-14 23:05:52 +00001934 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001935 int n;
drhd8bc7082000-06-07 23:51:50 +00001936 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001937 char *zType; /* "view" or "table" */
1938 char *zType2; /* "VIEW" or "TABLE" */
1939 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001940
danielk19774adee202004-05-08 08:23:19 +00001941 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001942 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001943
drh66a51672008-01-03 00:01:23 +00001944 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001945
drh0fa991b2009-03-21 16:19:26 +00001946 /*
1947 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001948 */
drh4ff6dfa2002-03-03 23:06:00 +00001949 if( p->pSelect==0 ){
1950 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001951 zType = "table";
1952 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001953#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001954 }else{
1955 /* A view */
drh4794f732004-11-05 17:17:50 +00001956 zType = "view";
1957 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001958#endif
drh4ff6dfa2002-03-03 23:06:00 +00001959 }
danielk1977517eb642004-06-07 10:00:31 +00001960
danielk1977517eb642004-06-07 10:00:31 +00001961 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1962 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001963 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001964 **
1965 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1966 ** suitable state to query for the column names and types to be used
1967 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001968 **
1969 ** A shared-cache write-lock is not required to write to the new table,
1970 ** as a schema-lock must have already been obtained to create it. Since
1971 ** a schema-lock excludes all other database users, the write-lock would
1972 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001973 */
1974 if( pSelect ){
drh92632202015-05-20 17:18:29 +00001975 SelectDest dest; /* Where the SELECT should store results */
drh9df25c42015-05-20 15:51:09 +00001976 int regYield; /* Register holding co-routine entry-point */
1977 int addrTop; /* Top of the co-routine */
drh92632202015-05-20 17:18:29 +00001978 int regRec; /* A record to be insert into the new table */
1979 int regRowid; /* Rowid of the next row to insert */
1980 int addrInsLoop; /* Top of the loop for inserting rows */
1981 Table *pSelTab; /* A table that describes the SELECT results */
drh1013c932008-01-06 00:25:21 +00001982
drh9df25c42015-05-20 15:51:09 +00001983 regYield = ++pParse->nMem;
drh92632202015-05-20 17:18:29 +00001984 regRec = ++pParse->nMem;
1985 regRowid = ++pParse->nMem;
danielk19776ab3a2e2009-02-19 14:39:25 +00001986 assert(pParse->nTab==1);
drh0dd5cda2015-06-16 16:39:01 +00001987 sqlite3MayAbort(pParse);
drhb7654112008-01-12 12:48:07 +00001988 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001989 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001990 pParse->nTab = 2;
drh9df25c42015-05-20 15:51:09 +00001991 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1992 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1993 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
drh7d10d5a2008-08-20 16:35:10 +00001994 sqlite3Select(pParse, pSelect, &dest);
drh9df25c42015-05-20 15:51:09 +00001995 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
1996 sqlite3VdbeJumpHere(v, addrTop - 1);
drh92632202015-05-20 17:18:29 +00001997 if( pParse->nErr ) return;
1998 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1999 if( pSelTab==0 ) return;
2000 assert( p->aCol==0 );
2001 p->nCol = pSelTab->nCol;
2002 p->aCol = pSelTab->aCol;
2003 pSelTab->nCol = 0;
2004 pSelTab->aCol = 0;
2005 sqlite3DeleteTable(db, pSelTab);
2006 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2007 VdbeCoverage(v);
2008 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
2009 sqlite3TableAffinity(v, p, 0);
2010 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
2011 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
drh076e85f2015-09-03 13:46:12 +00002012 sqlite3VdbeGoto(v, addrInsLoop);
drh92632202015-05-20 17:18:29 +00002013 sqlite3VdbeJumpHere(v, addrInsLoop);
2014 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00002015 }
drh4794f732004-11-05 17:17:50 +00002016
drh4794f732004-11-05 17:17:50 +00002017 /* Compute the complete text of the CREATE statement */
2018 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00002019 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00002020 }else{
drh8ea30bf2013-10-22 01:18:17 +00002021 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
2022 n = (int)(pEnd2->z - pParse->sNameToken.z);
2023 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00002024 zStmt = sqlite3MPrintf(db,
2025 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2026 );
drh4794f732004-11-05 17:17:50 +00002027 }
2028
2029 /* A slot for the record has already been allocated in the
2030 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00002031 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00002032 */
2033 sqlite3NestedParse(pParse,
2034 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00002035 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
2036 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00002037 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00002038 zType,
2039 p->zName,
2040 p->zName,
drhb7654112008-01-12 12:48:07 +00002041 pParse->regRoot,
2042 zStmt,
2043 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00002044 );
drh633e6d52008-07-28 19:34:53 +00002045 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00002046 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00002047
2048#ifndef SQLITE_OMIT_AUTOINCREMENT
2049 /* Check to see if we need to create an sqlite_sequence table for
2050 ** keeping track of autoincrement keys.
2051 */
drh7d10d5a2008-08-20 16:35:10 +00002052 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00002053 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00002054 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00002055 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00002056 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00002057 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2058 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00002059 );
2060 }
2061 }
2062#endif
drh4794f732004-11-05 17:17:50 +00002063
2064 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00002065 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00002066 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00002067 }
drh17e9e292003-02-01 13:53:28 +00002068
drh2958a4e2004-11-12 03:56:15 +00002069
drh17e9e292003-02-01 13:53:28 +00002070 /* Add the table to the in-memory representation of the database.
2071 */
drh8af73d42009-05-13 22:58:28 +00002072 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00002073 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00002074 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00002075 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00002076 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00002077 if( pOld ){
2078 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00002079 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00002080 return;
drh17e9e292003-02-01 13:53:28 +00002081 }
drh17e9e292003-02-01 13:53:28 +00002082 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00002083 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00002084
2085#ifndef SQLITE_OMIT_ALTERTABLE
2086 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00002087 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00002088 int nName;
drh5969da42013-10-21 02:14:45 +00002089 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00002090 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002091 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002092 }
drh1bd10f82008-12-10 21:19:56 +00002093 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002094 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002095 }
2096#endif
drh17e9e292003-02-01 13:53:28 +00002097 }
drh75897232000-05-29 14:26:00 +00002098}
2099
drhb7f91642004-10-31 02:22:47 +00002100#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002101/*
drha76b5df2002-02-23 02:32:10 +00002102** The parser calls this routine in order to create a new VIEW
2103*/
danielk19774adee202004-05-08 08:23:19 +00002104void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002105 Parse *pParse, /* The parsing context */
2106 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002107 Token *pName1, /* The token that holds the name of the view */
2108 Token *pName2, /* The token that holds the name of the view */
drh8981b902015-08-24 17:42:49 +00002109 ExprList *pCNames, /* Optional list of view column names */
drh6276c1c2002-07-08 22:03:32 +00002110 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002111 int isTemp, /* TRUE for a TEMPORARY view */
2112 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002113){
drha76b5df2002-02-23 02:32:10 +00002114 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002115 int n;
drhb7916a72009-05-27 10:31:29 +00002116 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002117 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002118 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002119 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002120 int iDb;
drh17435752007-08-16 04:30:38 +00002121 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002122
drh7c3d64f2005-06-06 15:32:08 +00002123 if( pParse->nVar>0 ){
2124 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh32498f12015-09-26 11:15:44 +00002125 goto create_view_fail;
drh7c3d64f2005-06-06 15:32:08 +00002126 }
drhfdd48a72006-09-11 23:45:48 +00002127 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002128 p = pParse->pNewTable;
drh8981b902015-08-24 17:42:49 +00002129 if( p==0 || pParse->nErr ) goto create_view_fail;
danielk1977ef2cb632004-05-29 02:37:19 +00002130 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002131 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002132 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
drh8981b902015-08-24 17:42:49 +00002133 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
drh174b6192002-12-03 02:22:52 +00002134
drh4b59ab52002-08-24 18:24:51 +00002135 /* Make a copy of the entire SELECT statement that defines the view.
2136 ** This will force all the Expr.token.z values to be dynamically
2137 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002138 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002139 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002140 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh8981b902015-08-24 17:42:49 +00002141 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2142 if( db->mallocFailed ) goto create_view_fail;
drh4b59ab52002-08-24 18:24:51 +00002143
2144 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2145 ** the end.
2146 */
drha76b5df2002-02-23 02:32:10 +00002147 sEnd = pParse->sLastToken;
drh8981b902015-08-24 17:42:49 +00002148 assert( sEnd.z[0]!=0 );
2149 if( sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002150 sEnd.z += sEnd.n;
2151 }
2152 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002153 n = (int)(sEnd.z - pBegin->z);
drh8981b902015-08-24 17:42:49 +00002154 assert( n>0 );
drhb7916a72009-05-27 10:31:29 +00002155 z = pBegin->z;
drh8981b902015-08-24 17:42:49 +00002156 while( sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002157 sEnd.z = &z[n-1];
2158 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002159
danielk19774adee202004-05-08 08:23:19 +00002160 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002161 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drh8981b902015-08-24 17:42:49 +00002162
2163create_view_fail:
2164 sqlite3SelectDelete(db, pSelect);
2165 sqlite3ExprListDelete(db, pCNames);
drha76b5df2002-02-23 02:32:10 +00002166 return;
drh417be792002-03-03 18:59:40 +00002167}
drhb7f91642004-10-31 02:22:47 +00002168#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002169
danielk1977fe3fcbe22006-06-12 12:08:45 +00002170#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002171/*
2172** The Table structure pTable is really a VIEW. Fill in the names of
2173** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002174** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002175*/
danielk19774adee202004-05-08 08:23:19 +00002176int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002177 Table *pSelTab; /* A fake table from which we get the result set */
2178 Select *pSel; /* Copy of the SELECT that implements the view */
2179 int nErr = 0; /* Number of errors encountered */
2180 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002181 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002182 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh8981b902015-08-24 17:42:49 +00002183 u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */
drh417be792002-03-03 18:59:40 +00002184
2185 assert( pTable );
2186
danielk1977fe3fcbe22006-06-12 12:08:45 +00002187#ifndef SQLITE_OMIT_VIRTUALTABLE
2188 if( sqlite3VtabCallConnect(pParse, pTable) ){
2189 return SQLITE_ERROR;
2190 }
drh4cbdda92006-06-14 19:00:20 +00002191 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002192#endif
2193
2194#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002195 /* A positive nCol means the columns names for this view are
2196 ** already known.
2197 */
2198 if( pTable->nCol>0 ) return 0;
2199
2200 /* A negative nCol is a special marker meaning that we are currently
2201 ** trying to compute the column names. If we enter this routine with
2202 ** a negative nCol, it means two or more views form a loop, like this:
2203 **
2204 ** CREATE VIEW one AS SELECT * FROM two;
2205 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002206 **
drh768578e2009-05-12 00:40:12 +00002207 ** Actually, the error above is now caught prior to reaching this point.
2208 ** But the following test is still important as it does come up
2209 ** in the following:
2210 **
2211 ** CREATE TABLE main.ex1(a);
2212 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2213 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002214 */
2215 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002216 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002217 return 1;
2218 }
drh85c23c62005-08-20 03:03:04 +00002219 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002220
2221 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002222 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2223 ** "*" elements in the results set of the view and will assign cursors
2224 ** to the elements of the FROM clause. But we do not want these changes
2225 ** to be permanent. So the computation is done on a copy of the SELECT
2226 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002227 */
drh9b3187e2005-01-18 14:45:47 +00002228 assert( pTable->pSelect );
drh8981b902015-08-24 17:42:49 +00002229 bEnabledLA = db->lookaside.bEnabled;
2230 if( pTable->pCheck ){
drhd9da78a2009-03-24 15:08:09 +00002231 db->lookaside.bEnabled = 0;
drh8981b902015-08-24 17:42:49 +00002232 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2233 &pTable->nCol, &pTable->aCol);
2234 }else{
2235 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2236 if( pSel ){
2237 n = pParse->nTab;
2238 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2239 pTable->nCol = -1;
2240 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002241#ifndef SQLITE_OMIT_AUTHORIZATION
drh8981b902015-08-24 17:42:49 +00002242 xAuth = db->xAuth;
2243 db->xAuth = 0;
2244 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2245 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002246#else
drh8981b902015-08-24 17:42:49 +00002247 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002248#endif
drh8981b902015-08-24 17:42:49 +00002249 pParse->nTab = n;
2250 if( pSelTab ){
2251 assert( pTable->aCol==0 );
2252 pTable->nCol = pSelTab->nCol;
2253 pTable->aCol = pSelTab->aCol;
2254 pSelTab->nCol = 0;
2255 pSelTab->aCol = 0;
2256 sqlite3DeleteTable(db, pSelTab);
2257 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2258 }else{
2259 pTable->nCol = 0;
2260 nErr++;
2261 }
2262 sqlite3SelectDelete(db, pSel);
2263 } else {
danielk1977261919c2005-12-06 12:52:59 +00002264 nErr++;
2265 }
drh417be792002-03-03 18:59:40 +00002266 }
drh8981b902015-08-24 17:42:49 +00002267 db->lookaside.bEnabled = bEnabledLA;
2268 pTable->pSchema->schemaFlags |= DB_UnresetViews;
drhb7f91642004-10-31 02:22:47 +00002269#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002270 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002271}
2272#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002273
drhb7f91642004-10-31 02:22:47 +00002274#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002275/*
drh8bf8dc92003-05-17 17:35:10 +00002276** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002277*/
drh9bb575f2004-09-06 17:24:11 +00002278static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002279 HashElem *i;
drh21206082011-04-04 18:22:02 +00002280 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002281 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002282 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002283 Table *pTab = sqliteHashData(i);
2284 if( pTab->pSelect ){
drh51be3872015-08-19 02:32:25 +00002285 sqlite3DeleteColumnNames(db, pTab);
dand46def72010-07-24 11:28:28 +00002286 pTab->aCol = 0;
2287 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002288 }
2289 }
drh8bf8dc92003-05-17 17:35:10 +00002290 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002291}
drhb7f91642004-10-31 02:22:47 +00002292#else
2293# define sqliteViewResetAll(A,B)
2294#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002295
drh75897232000-05-29 14:26:00 +00002296/*
danielk1977a0bf2652004-11-04 14:30:04 +00002297** This function is called by the VDBE to adjust the internal schema
2298** used by SQLite when the btree layer moves a table root page. The
2299** root-page of a table or index in database iDb has changed from iFrom
2300** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002301**
2302** Ticket #1728: The symbol table might still contain information
2303** on tables and/or indices that are the process of being deleted.
2304** If you are unlucky, one of those deleted indices or tables might
2305** have the same rootpage number as the real table or index that is
2306** being moved. So we cannot stop searching after the first match
2307** because the first match might be for one of the deleted indices
2308** or tables and not the table/index that is actually being moved.
2309** We must continue looping until all tables and indices with
2310** rootpage==iFrom have been converted to have a rootpage of iTo
2311** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002312*/
2313#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002314void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002315 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002316 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002317 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002318
drhcdf011d2011-04-04 21:25:28 +00002319 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2320 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002321 pHash = &pDb->pSchema->tblHash;
2322 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002323 Table *pTab = sqliteHashData(pElem);
2324 if( pTab->tnum==iFrom ){
2325 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002326 }
2327 }
danielk1977da184232006-01-05 11:34:32 +00002328 pHash = &pDb->pSchema->idxHash;
2329 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002330 Index *pIdx = sqliteHashData(pElem);
2331 if( pIdx->tnum==iFrom ){
2332 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002333 }
2334 }
danielk1977a0bf2652004-11-04 14:30:04 +00002335}
2336#endif
2337
2338/*
2339** Write code to erase the table with root-page iTable from database iDb.
2340** Also write code to modify the sqlite_master table and internal schema
2341** if a root-page of another table is moved by the btree-layer whilst
2342** erasing iTable (this can happen with an auto-vacuum database).
2343*/
drh4e0cff62004-11-05 05:10:28 +00002344static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2345 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002346 int r1 = sqlite3GetTempReg(pParse);
2347 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002348 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002349#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002350 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002351 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002352 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002353 ** reflect this.
2354 **
drh0fa991b2009-03-21 16:19:26 +00002355 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002356 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2357 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002358 */
danielk197763e3e9f2004-11-05 09:19:27 +00002359 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002360 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2361 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002362#endif
drhb7654112008-01-12 12:48:07 +00002363 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002364}
2365
2366/*
2367** Write VDBE code to erase table pTab and all associated indices on disk.
2368** Code to update the sqlite_master tables and internal schema definitions
2369** in case a root-page belonging to another table is moved by the btree layer
2370** is also added (this can happen with an auto-vacuum database).
2371*/
drh4e0cff62004-11-05 05:10:28 +00002372static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002373#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002374 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002375 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2376 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002377 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002378 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002379 }
2380#else
2381 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2382 ** is not defined), then it is important to call OP_Destroy on the
2383 ** table and index root-pages in order, starting with the numerically
2384 ** largest root-page number. This guarantees that none of the root-pages
2385 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2386 ** following were coded:
2387 **
2388 ** OP_Destroy 4 0
2389 ** ...
2390 ** OP_Destroy 5 0
2391 **
2392 ** and root page 5 happened to be the largest root-page number in the
2393 ** database, then root page 5 would be moved to page 4 by the
2394 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2395 ** a free-list page.
2396 */
2397 int iTab = pTab->tnum;
2398 int iDestroyed = 0;
2399
2400 while( 1 ){
2401 Index *pIdx;
2402 int iLargest = 0;
2403
2404 if( iDestroyed==0 || iTab<iDestroyed ){
2405 iLargest = iTab;
2406 }
2407 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2408 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002409 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002410 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2411 iLargest = iIdx;
2412 }
2413 }
danielk1977da184232006-01-05 11:34:32 +00002414 if( iLargest==0 ){
2415 return;
2416 }else{
2417 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002418 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002419 destroyRootPage(pParse, iLargest, iDb);
2420 iDestroyed = iLargest;
2421 }
danielk1977a0bf2652004-11-04 14:30:04 +00002422 }
2423#endif
2424}
2425
2426/*
drh74e7c8f2011-10-21 19:06:32 +00002427** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002428** after a DROP INDEX or DROP TABLE command.
2429*/
2430static void sqlite3ClearStatTables(
2431 Parse *pParse, /* The parsing context */
2432 int iDb, /* The database number */
2433 const char *zType, /* "idx" or "tbl" */
2434 const char *zName /* Name of index or table */
2435){
drha5ae4c32011-08-07 01:31:52 +00002436 int i;
2437 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002438 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002439 char zTab[24];
2440 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2441 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002442 sqlite3NestedParse(pParse,
2443 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002444 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002445 );
2446 }
2447 }
2448}
2449
2450/*
drhfaacf172011-08-12 01:51:45 +00002451** Generate code to drop a table.
2452*/
2453void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2454 Vdbe *v;
2455 sqlite3 *db = pParse->db;
2456 Trigger *pTrigger;
2457 Db *pDb = &db->aDb[iDb];
2458
2459 v = sqlite3GetVdbe(pParse);
2460 assert( v!=0 );
2461 sqlite3BeginWriteOperation(pParse, 1, iDb);
2462
2463#ifndef SQLITE_OMIT_VIRTUALTABLE
2464 if( IsVirtual(pTab) ){
2465 sqlite3VdbeAddOp0(v, OP_VBegin);
2466 }
2467#endif
2468
2469 /* Drop all triggers associated with the table being dropped. Code
2470 ** is generated to remove entries from sqlite_master and/or
2471 ** sqlite_temp_master if required.
2472 */
2473 pTrigger = sqlite3TriggerList(pParse, pTab);
2474 while( pTrigger ){
2475 assert( pTrigger->pSchema==pTab->pSchema ||
2476 pTrigger->pSchema==db->aDb[1].pSchema );
2477 sqlite3DropTriggerPtr(pParse, pTrigger);
2478 pTrigger = pTrigger->pNext;
2479 }
2480
2481#ifndef SQLITE_OMIT_AUTOINCREMENT
2482 /* Remove any entries of the sqlite_sequence table associated with
2483 ** the table being dropped. This is done before the table is dropped
2484 ** at the btree level, in case the sqlite_sequence table needs to
2485 ** move as a result of the drop (can happen in auto-vacuum mode).
2486 */
2487 if( pTab->tabFlags & TF_Autoincrement ){
2488 sqlite3NestedParse(pParse,
2489 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2490 pDb->zName, pTab->zName
2491 );
2492 }
2493#endif
2494
2495 /* Drop all SQLITE_MASTER table and index entries that refer to the
2496 ** table. The program name loops through the master table and deletes
2497 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002498 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002499 ** created in the temp database that refers to a table in another
2500 ** database.
2501 */
2502 sqlite3NestedParse(pParse,
2503 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2504 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002505 if( !isView && !IsVirtual(pTab) ){
2506 destroyTable(pParse, pTab);
2507 }
2508
2509 /* Remove the table entry from SQLite's internal schema and modify
2510 ** the schema cookie.
2511 */
2512 if( IsVirtual(pTab) ){
2513 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2514 }
2515 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2516 sqlite3ChangeCookie(pParse, iDb);
2517 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002518}
2519
2520/*
drh75897232000-05-29 14:26:00 +00002521** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002522** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002523*/
drha0733842005-12-29 01:11:36 +00002524void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002525 Table *pTab;
drh75897232000-05-29 14:26:00 +00002526 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002527 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002528 int iDb;
drh75897232000-05-29 14:26:00 +00002529
drh8af73d42009-05-13 22:58:28 +00002530 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002531 goto exit_drop_table;
2532 }
drh8af73d42009-05-13 22:58:28 +00002533 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002534 assert( pName->nSrc==1 );
drh75209962015-04-19 22:31:45 +00002535 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
drha7564662010-02-22 19:32:31 +00002536 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002537 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002538 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002539
drha0733842005-12-29 01:11:36 +00002540 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002541 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002542 goto exit_drop_table;
2543 }
danielk1977da184232006-01-05 11:34:32 +00002544 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002545 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002546
2547 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2548 ** it is initialized.
2549 */
2550 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2551 goto exit_drop_table;
2552 }
drhe5f9c642003-01-13 23:27:31 +00002553#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002554 {
2555 int code;
danielk1977da184232006-01-05 11:34:32 +00002556 const char *zTab = SCHEMA_TABLE(iDb);
2557 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002558 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002559 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002560 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002561 }
drhe5f9c642003-01-13 23:27:31 +00002562 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002563 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002564 code = SQLITE_DROP_TEMP_VIEW;
2565 }else{
2566 code = SQLITE_DROP_VIEW;
2567 }
danielk19774b2688a2006-06-20 11:01:07 +00002568#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002569 }else if( IsVirtual(pTab) ){
2570 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002571 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002572#endif
drhe5f9c642003-01-13 23:27:31 +00002573 }else{
danielk197753c0f742005-03-29 03:10:59 +00002574 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002575 code = SQLITE_DROP_TEMP_TABLE;
2576 }else{
2577 code = SQLITE_DROP_TABLE;
2578 }
2579 }
danielk1977f1a381e2006-06-16 08:01:02 +00002580 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002581 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002582 }
danielk1977a8858102004-05-28 12:11:21 +00002583 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2584 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002585 }
drhe5f9c642003-01-13 23:27:31 +00002586 }
2587#endif
drh08ccfaa2011-10-07 23:52:25 +00002588 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2589 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002590 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002591 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002592 }
danielk1977576ec6b2005-01-21 11:55:25 +00002593
2594#ifndef SQLITE_OMIT_VIEW
2595 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2596 ** on a table.
2597 */
danielk1977a8858102004-05-28 12:11:21 +00002598 if( isView && pTab->pSelect==0 ){
2599 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2600 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002601 }
danielk1977a8858102004-05-28 12:11:21 +00002602 if( !isView && pTab->pSelect ){
2603 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2604 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002605 }
danielk1977576ec6b2005-01-21 11:55:25 +00002606#endif
drh75897232000-05-29 14:26:00 +00002607
drh1ccde152000-06-17 13:12:39 +00002608 /* Generate code to remove the table from the master table
2609 ** on disk.
2610 */
danielk19774adee202004-05-08 08:23:19 +00002611 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002612 if( v ){
drh77658e22007-12-04 16:54:52 +00002613 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002614 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002615 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002616 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002617 }
danielk1977a8858102004-05-28 12:11:21 +00002618
2619exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002620 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002621}
2622
2623/*
drhc2eef3b2002-08-31 18:53:06 +00002624** This routine is called to create a new foreign key on the table
2625** currently under construction. pFromCol determines which columns
2626** in the current table point to the foreign key. If pFromCol==0 then
2627** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002628** the table referred to (a.k.a the "parent" table). pToCol is a list
2629** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002630** information about the conflict resolution algorithms specified
2631** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2632**
2633** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002634** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002635**
2636** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002637** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002638*/
danielk19774adee202004-05-08 08:23:19 +00002639void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002640 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002641 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002642 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002643 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002644 int flags /* Conflict resolution algorithms. */
2645){
danielk197718576932008-08-06 13:47:40 +00002646 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002647#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002648 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002649 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002650 Table *p = pParse->pNewTable;
2651 int nByte;
2652 int i;
2653 int nCol;
2654 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002655
2656 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002657 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002658 if( pFromCol==0 ){
2659 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002660 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002661 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002662 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002663 " should reference only one column of table %T",
2664 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002665 goto fk_end;
2666 }
2667 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002668 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002669 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002670 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002671 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002672 goto fk_end;
2673 }else{
danielk19770202b292004-06-09 09:55:16 +00002674 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002675 }
drhe61922a2009-05-02 13:29:37 +00002676 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002677 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002678 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002679 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002680 }
2681 }
drh633e6d52008-07-28 19:34:53 +00002682 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002683 if( pFKey==0 ){
2684 goto fk_end;
2685 }
drhc2eef3b2002-08-31 18:53:06 +00002686 pFKey->pFrom = p;
2687 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002688 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002689 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002690 memcpy(z, pTo->z, pTo->n);
2691 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002692 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002693 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002694 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002695 if( pFromCol==0 ){
2696 pFKey->aCol[0].iFrom = p->nCol-1;
2697 }else{
2698 for(i=0; i<nCol; i++){
2699 int j;
2700 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002701 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002702 pFKey->aCol[i].iFrom = j;
2703 break;
2704 }
2705 }
2706 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002707 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002708 "unknown column \"%s\" in foreign key definition",
2709 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002710 goto fk_end;
2711 }
2712 }
2713 }
2714 if( pToCol ){
2715 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002716 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002717 pFKey->aCol[i].zCol = z;
2718 memcpy(z, pToCol->a[i].zName, n);
2719 z[n] = 0;
2720 z += n+1;
2721 }
2722 }
2723 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002724 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2725 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002726
drh21206082011-04-04 18:22:02 +00002727 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002728 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002729 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002730 );
danf59c5ca2009-09-22 16:55:38 +00002731 if( pNextTo==pFKey ){
2732 db->mallocFailed = 1;
2733 goto fk_end;
2734 }
dan1da40a32009-09-19 17:00:31 +00002735 if( pNextTo ){
2736 assert( pNextTo->pPrevTo==0 );
2737 pFKey->pNextTo = pNextTo;
2738 pNextTo->pPrevTo = pFKey;
2739 }
2740
drhc2eef3b2002-08-31 18:53:06 +00002741 /* Link the foreign key to the table as the last step.
2742 */
2743 p->pFKey = pFKey;
2744 pFKey = 0;
2745
2746fk_end:
drh633e6d52008-07-28 19:34:53 +00002747 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002748#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002749 sqlite3ExprListDelete(db, pFromCol);
2750 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002751}
2752
2753/*
2754** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2755** clause is seen as part of a foreign key definition. The isDeferred
2756** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2757** The behavior of the most recently created foreign key is adjusted
2758** accordingly.
2759*/
danielk19774adee202004-05-08 08:23:19 +00002760void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002761#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002762 Table *pTab;
2763 FKey *pFKey;
2764 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002765 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002766 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002767#endif
drhc2eef3b2002-08-31 18:53:06 +00002768}
2769
2770/*
drh063336a2004-11-05 20:58:39 +00002771** Generate code that will erase and refill index *pIdx. This is
2772** used to initialize a newly created index or to recompute the
2773** content of an index in response to a REINDEX command.
2774**
2775** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002776** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002777** root page number of the index. If memRootPage is negative, then
2778** the index already exists and must be cleared before being refilled and
2779** the root page number of the index is taken from pIndex->tnum.
2780*/
2781static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2782 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002783 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2784 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002785 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002786 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002787 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002788 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002789 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002790 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002791 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002792 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002793 sqlite3 *db = pParse->db; /* The database connection */
2794 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002795
danielk19771d54df82004-11-23 15:41:16 +00002796#ifndef SQLITE_OMIT_AUTHORIZATION
2797 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002798 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002799 return;
2800 }
2801#endif
2802
danielk1977c00da102006-01-07 13:21:04 +00002803 /* Require a write-lock on the table to perform this operation */
2804 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2805
drh063336a2004-11-05 20:58:39 +00002806 v = sqlite3GetVdbe(pParse);
2807 if( v==0 ) return;
2808 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002809 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002810 }else{
2811 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002812 }
drh2ec2fb22013-11-06 19:59:23 +00002813 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002814
dan689ab892011-08-12 15:02:00 +00002815 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002816 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002817 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002818 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002819
2820 /* Open the table. Loop through all rows of the table, inserting index
2821 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002822 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002823 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002824 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002825
drh1c2c0b72014-01-04 19:27:05 +00002826 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002827 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002828 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002829 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002830 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002831 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2832 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002833 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002834 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2835
drh688852a2014-02-17 22:40:43 +00002836 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002837 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002838 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002839 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
drh076e85f2015-09-03 13:46:12 +00002840 sqlite3VdbeGoto(v, j2);
drhca892a72011-09-03 00:17:51 +00002841 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002842 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002843 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002844 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002845 }else{
2846 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002847 }
drh6cf4a7d2014-10-13 13:00:58 +00002848 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
danb18e60b2015-04-01 16:18:00 +00002849 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
2850 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
drhca892a72011-09-03 00:17:51 +00002851 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002852 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002853 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002854 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002855
drh66a51672008-01-03 00:01:23 +00002856 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2857 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002858 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002859}
2860
2861/*
drh77e57df2013-10-22 14:28:02 +00002862** Allocate heap space to hold an Index object with nCol columns.
2863**
2864** Increase the allocation size to provide an extra nExtra bytes
2865** of 8-byte aligned space after the Index object and return a
2866** pointer to this extra space in *ppExtra.
2867*/
2868Index *sqlite3AllocateIndexObject(
2869 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002870 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002871 int nExtra, /* Number of bytes of extra space to alloc */
2872 char **ppExtra /* Pointer to the "extra" space */
2873){
2874 Index *p; /* Allocated index object */
2875 int nByte; /* Bytes of space for Index object + arrays */
2876
2877 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2878 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002879 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002880 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002881 sizeof(u8)*nCol); /* Index.aSortOrder */
2882 p = sqlite3DbMallocZero(db, nByte + nExtra);
2883 if( p ){
2884 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002885 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2886 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2887 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002888 p->aSortOrder = (u8*)pExtra;
2889 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002890 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002891 *ppExtra = ((char*)p) + nByte;
2892 }
2893 return p;
2894}
2895
2896/*
drh23bf66d2004-12-14 03:34:34 +00002897** Create a new index for an SQL table. pName1.pName2 is the name of the index
2898** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002899** be NULL for a primary key or an index that is created to satisfy a
2900** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002901** as the table to be indexed. pParse->pNewTable is a table that is
2902** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002903**
drh382c0242001-10-06 16:33:02 +00002904** pList is a list of columns to be indexed. pList will be NULL if this
2905** is a primary key or unique-constraint on the most recent column added
2906** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002907**
2908** If the index is created successfully, return a pointer to the new Index
2909** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002910** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002911*/
dan1da40a32009-09-19 17:00:31 +00002912Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002913 Parse *pParse, /* All information about this parse */
2914 Token *pName1, /* First part of index name. May be NULL */
2915 Token *pName2, /* Second part of index name. May be NULL */
2916 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002917 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002918 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002919 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002920 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002921 int sortOrder, /* Sort order of primary key when pList==NULL */
2922 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002923){
dan1da40a32009-09-19 17:00:31 +00002924 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002925 Table *pTab = 0; /* Table to be indexed */
2926 Index *pIndex = 0; /* The index to be created */
2927 char *zName = 0; /* Name of the index */
2928 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002929 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002930 DbFixer sFix; /* For assigning database names to pTable */
2931 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002932 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002933 Db *pDb; /* The specific table containing the indexed database */
2934 int iDb; /* Index of the database that is being written */
2935 Token *pName = 0; /* Unqualified name of the index to create */
2936 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002937 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002938 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002939 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002940 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002941
drh7088d502015-04-18 17:43:29 +00002942 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
drhd3001712009-05-12 17:46:53 +00002943 goto exit_create_index;
2944 }
2945 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002946 goto exit_create_index;
2947 }
drhdaffd0e2001-04-11 14:28:42 +00002948
drh75897232000-05-29 14:26:00 +00002949 /*
2950 ** Find the table that is to be indexed. Return early if not found.
2951 */
danielk1977cbb18d22004-05-28 11:37:27 +00002952 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002953
2954 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002955 ** to search for the table. 'Fix' the table name to this db
2956 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002957 */
2958 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002959 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002960 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002961 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002962
danielk197753c0f742005-03-29 03:10:59 +00002963#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002964 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002965 ** is a temp table. If so, set the database to 1. Do not do this
2966 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002967 */
danielk1977fe910332007-12-02 11:46:34 +00002968 if( !db->init.busy ){
2969 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002970 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002971 iDb = 1;
2972 }
danielk1977ef2cb632004-05-29 02:37:19 +00002973 }
danielk197753c0f742005-03-29 03:10:59 +00002974#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002975
drhd100f692013-10-03 15:39:44 +00002976 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2977 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002978 /* Because the parser constructs pTblName from a single identifier,
2979 ** sqlite3FixSrcList can never fail. */
2980 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002981 }
dan41fb5cd2012-10-04 19:33:00 +00002982 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002983 assert( db->mallocFailed==0 || pTab==0 );
2984 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002985 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2986 sqlite3ErrorMsg(pParse,
2987 "cannot create a TEMP index on non-TEMP table \"%s\"",
2988 pTab->zName);
2989 goto exit_create_index;
2990 }
drh44156282013-10-23 22:23:03 +00002991 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002992 }else{
drhe3c41372001-09-17 20:25:58 +00002993 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002994 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002995 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002996 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002997 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002998 }
drhfdd6e852005-12-16 01:06:16 +00002999 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00003000
drhd3001712009-05-12 17:46:53 +00003001 assert( pTab!=0 );
3002 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00003003 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00003004 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00003005#if SQLITE_USER_AUTHENTICATION
3006 && sqlite3UserAuthTable(pTab->zName)==0
3007#endif
drh503a6862013-03-01 01:07:17 +00003008 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00003009 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00003010 goto exit_create_index;
3011 }
danielk1977576ec6b2005-01-21 11:55:25 +00003012#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00003013 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00003014 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00003015 goto exit_create_index;
3016 }
danielk1977576ec6b2005-01-21 11:55:25 +00003017#endif
danielk19775ee9d692006-06-21 12:36:25 +00003018#ifndef SQLITE_OMIT_VIRTUALTABLE
3019 if( IsVirtual(pTab) ){
3020 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
3021 goto exit_create_index;
3022 }
3023#endif
drh75897232000-05-29 14:26:00 +00003024
3025 /*
3026 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00003027 ** index or table with the same name.
3028 **
3029 ** Exception: If we are reading the names of permanent indices from the
3030 ** sqlite_master table (because some other process changed the schema) and
3031 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00003032 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00003033 **
3034 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00003035 ** dealing with a primary key or UNIQUE constraint. We have to invent our
3036 ** own name.
drh75897232000-05-29 14:26:00 +00003037 */
danielk1977d8123362004-06-12 09:25:12 +00003038 if( pName ){
drh17435752007-08-16 04:30:38 +00003039 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00003040 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00003041 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00003042 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00003043 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00003044 }
danielk1977d8123362004-06-12 09:25:12 +00003045 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00003046 if( sqlite3FindTable(db, zName, 0)!=0 ){
3047 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3048 goto exit_create_index;
3049 }
3050 }
danielk197759a33f92007-03-17 10:26:59 +00003051 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
3052 if( !ifNotExist ){
3053 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00003054 }else{
3055 assert( !db->init.busy );
3056 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00003057 }
danielk197759a33f92007-03-17 10:26:59 +00003058 goto exit_create_index;
3059 }
danielk1977a21c6b62005-01-24 10:25:59 +00003060 }else{
drhadbca9c2001-09-27 15:11:53 +00003061 int n;
3062 Index *pLoop;
3063 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00003064 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00003065 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00003066 goto exit_create_index;
3067 }
drh75897232000-05-29 14:26:00 +00003068 }
3069
drhe5f9c642003-01-13 23:27:31 +00003070 /* Check for authorization to create an index.
3071 */
3072#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00003073 {
drhfdd6e852005-12-16 01:06:16 +00003074 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00003075 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003076 goto exit_create_index;
3077 }
3078 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00003079 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003080 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003081 goto exit_create_index;
3082 }
drhe5f9c642003-01-13 23:27:31 +00003083 }
3084#endif
3085
drh75897232000-05-29 14:26:00 +00003086 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00003087 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00003088 ** So create a fake list to simulate this.
3089 */
3090 if( pList==0 ){
drh108aa002015-08-24 20:21:20 +00003091 Token prevCol;
3092 prevCol.z = pTab->aCol[pTab->nCol-1].zName;
3093 prevCol.n = sqlite3Strlen30(prevCol.z);
3094 pList = sqlite3ExprListAppend(pParse, 0,
3095 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
drh75897232000-05-29 14:26:00 +00003096 if( pList==0 ) goto exit_create_index;
drhbc622bc2015-08-24 15:39:42 +00003097 assert( pList->nExpr==1 );
3098 sqlite3ExprListSetSortOrder(pList, sortOrder);
drh108aa002015-08-24 20:21:20 +00003099 }else{
3100 sqlite3ExprListCheckLength(pParse, pList, "index");
drh75897232000-05-29 14:26:00 +00003101 }
3102
danielk1977b3bf5562006-01-10 17:58:23 +00003103 /* Figure out how many bytes of space are required to store explicitly
3104 ** specified collation sequence names.
3105 */
3106 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003107 Expr *pExpr = pList->a[i].pExpr;
drh7d3d9da2015-09-01 00:42:52 +00003108 assert( pExpr!=0 );
3109 if( pExpr->op==TK_COLLATE ){
dan911ce412013-05-15 15:16:50 +00003110 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003111 }
3112 }
3113
drh75897232000-05-29 14:26:00 +00003114 /*
3115 ** Allocate the index structure.
3116 */
drhea678832008-12-10 19:26:22 +00003117 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003118 nExtraCol = pPk ? pPk->nKeyCol : 1;
3119 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003120 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003121 if( db->mallocFailed ){
3122 goto exit_create_index;
3123 }
dancfc9df72014-04-25 15:01:01 +00003124 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003125 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003126 pIndex->zName = zExtra;
3127 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003128 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003129 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003130 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003131 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003132 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003133 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003134 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003135 if( pPIWhere ){
3136 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3137 pIndex->pPartIdxWhere = pPIWhere;
3138 pPIWhere = 0;
3139 }
drh21206082011-04-04 18:22:02 +00003140 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003141
drhfdd6e852005-12-16 01:06:16 +00003142 /* Check to see if we should honor DESC requests on index columns
3143 */
danielk1977da184232006-01-05 11:34:32 +00003144 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003145 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003146 }else{
3147 sortOrderMask = 0; /* Ignore DESC */
3148 }
3149
drh1f9ca2c2015-08-25 16:57:52 +00003150 /* Analyze the list of expressions that form the terms of the index and
3151 ** report any errors. In the common case where the expression is exactly
3152 ** a table column, store that column in aiColumn[]. For general expressions,
drh4b92f982015-09-29 17:20:14 +00003153 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
drhd3001712009-05-12 17:46:53 +00003154 **
drh1f9ca2c2015-08-25 16:57:52 +00003155 ** TODO: Issue a warning if two or more columns of the index are identical.
3156 ** TODO: Issue a warning if the table primary key is used as part of the
3157 ** index key.
drh75897232000-05-29 14:26:00 +00003158 */
drhfdd6e852005-12-16 01:06:16 +00003159 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
drh1f9ca2c2015-08-25 16:57:52 +00003160 Expr *pCExpr; /* The i-th index expression */
3161 int requestedSortOrder; /* ASC or DESC on the i-th expression */
drha34001c2007-02-02 12:44:37 +00003162 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003163
drhedb04ed2015-09-04 12:54:01 +00003164 sqlite3StringToId(pListItem->pExpr);
drha514b8e2015-08-25 00:27:06 +00003165 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3166 if( pParse->nErr ) goto exit_create_index;
drh108aa002015-08-24 20:21:20 +00003167 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
drha514b8e2015-08-25 00:27:06 +00003168 if( pCExpr->op!=TK_COLUMN ){
drh1f9ca2c2015-08-25 16:57:52 +00003169 if( pTab==pParse->pNewTable ){
3170 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3171 "UNIQUE constraints");
3172 goto exit_create_index;
3173 }
3174 if( pIndex->aColExpr==0 ){
drh84926532015-08-31 19:38:42 +00003175 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
3176 pIndex->aColExpr = pCopy;
3177 if( !db->mallocFailed ){
3178 assert( pCopy!=0 );
3179 pListItem = &pCopy->a[i];
3180 }
drh1f9ca2c2015-08-25 16:57:52 +00003181 }
drh4b92f982015-09-29 17:20:14 +00003182 j = XN_EXPR;
3183 pIndex->aiColumn[i] = XN_EXPR;
drh84926532015-08-31 19:38:42 +00003184 pIndex->uniqNotNull = 0;
drh1f9ca2c2015-08-25 16:57:52 +00003185 }else{
3186 j = pCExpr->iColumn;
3187 assert( j<=0x7fff );
3188 if( j<0 ){
3189 j = pTab->iPKey;
3190 }else if( pTab->aCol[j].notNull==0 ){
3191 pIndex->uniqNotNull = 0;
3192 }
3193 pIndex->aiColumn[i] = (i16)j;
drh108aa002015-08-24 20:21:20 +00003194 }
drha514b8e2015-08-25 00:27:06 +00003195 zColl = 0;
drh108aa002015-08-24 20:21:20 +00003196 if( pListItem->pExpr->op==TK_COLLATE ){
drhd3001712009-05-12 17:46:53 +00003197 int nColl;
dan911ce412013-05-15 15:16:50 +00003198 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003199 nColl = sqlite3Strlen30(zColl) + 1;
3200 assert( nExtra>=nColl );
3201 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003202 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003203 zExtra += nColl;
3204 nExtra -= nColl;
drha514b8e2015-08-25 00:27:06 +00003205 }else if( j>=0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003206 zColl = pTab->aCol[j].zColl;
danielk19770202b292004-06-09 09:55:16 +00003207 }
drha514b8e2015-08-25 00:27:06 +00003208 if( !zColl ) zColl = "BINARY";
drhb7f24de2009-05-13 17:35:23 +00003209 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003210 goto exit_create_index;
3211 }
danielk1977b3bf5562006-01-10 17:58:23 +00003212 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003213 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003214 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00003215 }
drh1f9ca2c2015-08-25 16:57:52 +00003216
3217 /* Append the table key to the end of the index. For WITHOUT ROWID
3218 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
3219 ** normal tables (when pPk==0) this will be the rowid.
3220 */
drh44156282013-10-23 22:23:03 +00003221 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003222 for(j=0; j<pPk->nKeyCol; j++){
3223 int x = pPk->aiColumn[j];
drh1f9ca2c2015-08-25 16:57:52 +00003224 assert( x>=0 );
drh7913e412013-11-01 20:30:36 +00003225 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3226 pIndex->nColumn--;
3227 }else{
3228 pIndex->aiColumn[i] = x;
3229 pIndex->azColl[i] = pPk->azColl[j];
3230 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3231 i++;
3232 }
drh44156282013-10-23 22:23:03 +00003233 }
drh7913e412013-11-01 20:30:36 +00003234 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003235 }else{
drh4b92f982015-09-29 17:20:14 +00003236 pIndex->aiColumn[i] = XN_ROWID;
drh44156282013-10-23 22:23:03 +00003237 pIndex->azColl[i] = "BINARY";
3238 }
drh51147ba2005-07-23 22:59:55 +00003239 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003240 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003241
danielk1977d8123362004-06-12 09:25:12 +00003242 if( pTab==pParse->pNewTable ){
3243 /* This routine has been called to create an automatic index as a
3244 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3245 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3246 ** i.e. one of:
3247 **
3248 ** CREATE TABLE t(x PRIMARY KEY, y);
3249 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3250 **
3251 ** Either way, check to see if the table already has such an index. If
3252 ** so, don't bother creating this one. This only applies to
3253 ** automatically created indices. Users can do as they wish with
3254 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003255 **
3256 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3257 ** (and thus suppressing the second one) even if they have different
3258 ** sort orders.
3259 **
3260 ** If there are different collating sequences or if the columns of
3261 ** the constraint occur in different orders, then the constraints are
3262 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003263 */
3264 Index *pIdx;
3265 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3266 int k;
drh5f1d1d92014-07-31 22:59:04 +00003267 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003268 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003269 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003270
drhbbbdc832013-10-22 18:01:40 +00003271 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3272 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003273 const char *z1;
3274 const char *z2;
drh1f9ca2c2015-08-25 16:57:52 +00003275 assert( pIdx->aiColumn[k]>=0 );
danielk1977d8123362004-06-12 09:25:12 +00003276 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003277 z1 = pIdx->azColl[k];
3278 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003279 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003280 }
drhbbbdc832013-10-22 18:01:40 +00003281 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003282 if( pIdx->onError!=pIndex->onError ){
3283 /* This constraint creates the same index as a previous
3284 ** constraint specified somewhere in the CREATE TABLE statement.
3285 ** However the ON CONFLICT clauses are different. If both this
3286 ** constraint and the previous equivalent constraint have explicit
3287 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003288 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003289 */
3290 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3291 sqlite3ErrorMsg(pParse,
3292 "conflicting ON CONFLICT clauses specified", 0);
3293 }
3294 if( pIdx->onError==OE_Default ){
3295 pIdx->onError = pIndex->onError;
3296 }
3297 }
drhf0636852015-03-21 02:58:20 +00003298 pRet = pIdx;
danielk1977d8123362004-06-12 09:25:12 +00003299 goto exit_create_index;
3300 }
3301 }
3302 }
3303
drh75897232000-05-29 14:26:00 +00003304 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003305 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003306 */
drh7d3d9da2015-09-01 00:42:52 +00003307 assert( pParse->nErr==0 );
drh234c39d2004-07-24 03:30:47 +00003308 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003309 Index *p;
drh21206082011-04-04 18:22:02 +00003310 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003311 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003312 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003313 if( p ){
3314 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003315 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003316 goto exit_create_index;
3317 }
drh5e00f6c2001-09-13 13:46:56 +00003318 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003319 if( pTblName!=0 ){
3320 pIndex->tnum = db->init.newTnum;
3321 }
drhd78eeee2001-09-13 16:18:53 +00003322 }
3323
drh58383402013-11-04 17:00:50 +00003324 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3325 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3326 ** emit code to allocate the index rootpage on disk and make an entry for
3327 ** the index in the sqlite_master table and populate the index with
3328 ** content. But, do not do this if we are simply reading the sqlite_master
3329 ** table to parse the schema, or if this index is the PRIMARY KEY index
3330 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003331 **
drh58383402013-11-04 17:00:50 +00003332 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3333 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003334 ** has just been created, it contains no data and the index initialization
3335 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003336 */
drh7d3d9da2015-09-01 00:42:52 +00003337 else if( HasRowid(pTab) || pTblName!=0 ){
drhadbca9c2001-09-27 15:11:53 +00003338 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003339 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003340 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003341
danielk19774adee202004-05-08 08:23:19 +00003342 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003343 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003344
drhaee128d2005-02-14 20:48:18 +00003345 sqlite3BeginWriteOperation(pParse, 1, iDb);
danc5b73582015-05-26 11:53:14 +00003346
3347 /* Create the rootpage for the index using CreateIndex. But before
3348 ** doing so, code a Noop instruction and store its address in
3349 ** Index.tnum. This is required in case this index is actually a
3350 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3351 ** that case the convertToWithoutRowidTable() routine will replace
3352 ** the Noop with a Goto to jump over the VDBE code generated below. */
3353 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
drhb7654112008-01-12 12:48:07 +00003354 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003355
3356 /* Gather the complete text of the CREATE INDEX statement into
3357 ** the zStmt variable
3358 */
drhd3001712009-05-12 17:46:53 +00003359 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003360 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003361 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003362 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003363 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003364 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003365 }else{
3366 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003367 /* zStmt = sqlite3MPrintf(""); */
3368 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003369 }
drh063336a2004-11-05 20:58:39 +00003370
3371 /* Add an entry in sqlite_master for this index
3372 */
3373 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003374 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003375 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3376 pIndex->zName,
3377 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003378 iMem,
drh063336a2004-11-05 20:58:39 +00003379 zStmt
3380 );
drh633e6d52008-07-28 19:34:53 +00003381 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003382
danielk1977a21c6b62005-01-24 10:25:59 +00003383 /* Fill the index with data and reparse the schema. Code an OP_Expire
3384 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003385 */
danielk1977cbb18d22004-05-28 11:37:27 +00003386 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003387 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003388 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003389 sqlite3VdbeAddParseSchemaOp(v, iDb,
3390 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003391 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003392 }
danc5b73582015-05-26 11:53:14 +00003393
3394 sqlite3VdbeJumpHere(v, pIndex->tnum);
drh75897232000-05-29 14:26:00 +00003395 }
3396
danielk1977d8123362004-06-12 09:25:12 +00003397 /* When adding an index to the list of indices for a table, make
3398 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003399 ** OE_Ignore. This is necessary for the correct constraint check
3400 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3401 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003402 */
drh234c39d2004-07-24 03:30:47 +00003403 if( db->init.busy || pTblName==0 ){
3404 if( onError!=OE_Replace || pTab->pIndex==0
3405 || pTab->pIndex->onError==OE_Replace){
3406 pIndex->pNext = pTab->pIndex;
3407 pTab->pIndex = pIndex;
3408 }else{
3409 Index *pOther = pTab->pIndex;
3410 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3411 pOther = pOther->pNext;
3412 }
3413 pIndex->pNext = pOther->pNext;
3414 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003415 }
dan1da40a32009-09-19 17:00:31 +00003416 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003417 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003418 }
danielk1977d8123362004-06-12 09:25:12 +00003419
drh75897232000-05-29 14:26:00 +00003420 /* Clean up before exiting */
3421exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003422 if( pIndex ) freeIndex(db, pIndex);
3423 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003424 sqlite3ExprListDelete(db, pList);
3425 sqlite3SrcListDelete(db, pTblName);
3426 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003427 return pRet;
drh75897232000-05-29 14:26:00 +00003428}
3429
3430/*
drh51147ba2005-07-23 22:59:55 +00003431** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003432** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003433**
peter.d.reid60ec9142014-09-06 16:39:46 +00003434** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003435** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3436** number of rows in the table that match any particular value of the
3437** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003438** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003439** of the index. And so forth. It must always be the case that
3440*
3441** aiRowEst[N]<=aiRowEst[N-1]
3442** aiRowEst[N]>=1
3443**
3444** Apart from that, we have little to go on besides intuition as to
3445** how aiRowEst[] should be initialized. The numbers generated here
3446** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003447*/
3448void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003449 /* 10, 9, 8, 7, 6 */
3450 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003451 LogEst *a = pIdx->aiRowLogEst;
3452 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003453 int i;
dancfc9df72014-04-25 15:01:01 +00003454
dan264d2b92014-04-29 19:01:57 +00003455 /* Set the first entry (number of rows in the index) to the estimated
3456 ** number of rows in the table. Or 10, if the estimated number of rows
3457 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003458 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003459 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3460
3461 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3462 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003463 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003464 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3465 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003466 }
dan264d2b92014-04-29 19:01:57 +00003467
3468 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003469 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003470}
3471
3472/*
drh74e24cd2002-01-09 03:19:59 +00003473** This routine will drop an existing named index. This routine
3474** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003475*/
drh4d91a702006-01-04 15:54:36 +00003476void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003477 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003478 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003479 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003480 int iDb;
drh75897232000-05-29 14:26:00 +00003481
drh8af73d42009-05-13 22:58:28 +00003482 assert( pParse->nErr==0 ); /* Never called with prior errors */
3483 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003484 goto exit_drop_index;
3485 }
drhd24cc422003-03-27 12:51:24 +00003486 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003487 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3488 goto exit_drop_index;
3489 }
danielk19774adee202004-05-08 08:23:19 +00003490 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003491 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003492 if( !ifExists ){
3493 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003494 }else{
3495 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003496 }
drha6ecd332004-06-10 00:29:09 +00003497 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003498 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003499 }
drh48dd1d82014-05-27 18:18:58 +00003500 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003501 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003502 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003503 goto exit_drop_index;
3504 }
danielk1977da184232006-01-05 11:34:32 +00003505 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003506#ifndef SQLITE_OMIT_AUTHORIZATION
3507 {
3508 int code = SQLITE_DROP_INDEX;
3509 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003510 const char *zDb = db->aDb[iDb].zName;
3511 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003512 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003513 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003514 }
danielk1977da184232006-01-05 11:34:32 +00003515 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003516 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003517 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003518 }
drhed6c8672003-01-12 18:02:16 +00003519 }
drhe5f9c642003-01-13 23:27:31 +00003520#endif
drh75897232000-05-29 14:26:00 +00003521
3522 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003523 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003524 if( v ){
drh77658e22007-12-04 16:54:52 +00003525 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003526 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003527 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003528 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003529 );
drha5ae4c32011-08-07 01:31:52 +00003530 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003531 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003532 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003533 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003534 }
3535
drhd24cc422003-03-27 12:51:24 +00003536exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003537 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003538}
3539
3540/*
dan9ace1122012-03-29 07:51:45 +00003541** pArray is a pointer to an array of objects. Each object in the
3542** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3543** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003544**
dan9ace1122012-03-29 07:51:45 +00003545** When this function is called, *pnEntry contains the current size of
3546** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3547** in total).
drh13449892005-09-07 21:22:45 +00003548**
dan9ace1122012-03-29 07:51:45 +00003549** If the realloc() is successful (i.e. if no OOM condition occurs), the
3550** space allocated for the new object is zeroed, *pnEntry updated to
3551** reflect the new size of the array and a pointer to the new allocation
3552** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003553**
dan9ace1122012-03-29 07:51:45 +00003554** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3555** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003556*/
drhcf643722007-03-27 13:36:37 +00003557void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003558 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003559 void *pArray, /* Array of objects. Might be reallocated */
3560 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003561 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003562 int *pIdx /* Write the index of a new slot here */
3563){
3564 char *z;
drh6c535152012-02-02 03:38:30 +00003565 int n = *pnEntry;
3566 if( (n & (n-1))==0 ){
3567 int sz = (n==0) ? 1 : 2*n;
3568 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003569 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003570 *pIdx = -1;
3571 return pArray;
drh13449892005-09-07 21:22:45 +00003572 }
drhcf643722007-03-27 13:36:37 +00003573 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003574 }
drhcf643722007-03-27 13:36:37 +00003575 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003576 memset(&z[n * szEntry], 0, szEntry);
3577 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003578 ++*pnEntry;
3579 return pArray;
drh13449892005-09-07 21:22:45 +00003580}
3581
3582/*
drh75897232000-05-29 14:26:00 +00003583** Append a new element to the given IdList. Create a new IdList if
3584** need be.
drhdaffd0e2001-04-11 14:28:42 +00003585**
3586** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003587*/
drh17435752007-08-16 04:30:38 +00003588IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003589 int i;
drh75897232000-05-29 14:26:00 +00003590 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003591 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003592 if( pList==0 ) return 0;
3593 }
drhcf643722007-03-27 13:36:37 +00003594 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003595 db,
drhcf643722007-03-27 13:36:37 +00003596 pList->a,
3597 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003598 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003599 &i
3600 );
drh13449892005-09-07 21:22:45 +00003601 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003602 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003603 return 0;
drh75897232000-05-29 14:26:00 +00003604 }
drh17435752007-08-16 04:30:38 +00003605 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003606 return pList;
3607}
3608
3609/*
drhfe05af82005-07-21 03:14:59 +00003610** Delete an IdList.
3611*/
drh633e6d52008-07-28 19:34:53 +00003612void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003613 int i;
3614 if( pList==0 ) return;
3615 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003616 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003617 }
drh633e6d52008-07-28 19:34:53 +00003618 sqlite3DbFree(db, pList->a);
3619 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003620}
3621
3622/*
3623** Return the index in pList of the identifier named zId. Return -1
3624** if not found.
3625*/
3626int sqlite3IdListIndex(IdList *pList, const char *zName){
3627 int i;
3628 if( pList==0 ) return -1;
3629 for(i=0; i<pList->nId; i++){
3630 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3631 }
3632 return -1;
3633}
3634
3635/*
drha78c22c2008-11-11 18:28:58 +00003636** Expand the space allocated for the given SrcList object by
3637** creating nExtra new slots beginning at iStart. iStart is zero based.
3638** New slots are zeroed.
3639**
3640** For example, suppose a SrcList initially contains two entries: A,B.
3641** To append 3 new entries onto the end, do this:
3642**
3643** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3644**
3645** After the call above it would contain: A, B, nil, nil, nil.
3646** If the iStart argument had been 1 instead of 2, then the result
3647** would have been: A, nil, nil, nil, B. To prepend the new slots,
3648** the iStart value would be 0. The result then would
3649** be: nil, nil, nil, A, B.
3650**
3651** If a memory allocation fails the SrcList is unchanged. The
3652** db->mallocFailed flag will be set to true.
3653*/
3654SrcList *sqlite3SrcListEnlarge(
3655 sqlite3 *db, /* Database connection to notify of OOM errors */
3656 SrcList *pSrc, /* The SrcList to be enlarged */
3657 int nExtra, /* Number of new slots to add to pSrc->a[] */
3658 int iStart /* Index in pSrc->a[] of first new slot */
3659){
3660 int i;
3661
3662 /* Sanity checking on calling parameters */
3663 assert( iStart>=0 );
3664 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003665 assert( pSrc!=0 );
3666 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003667
3668 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003669 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003670 SrcList *pNew;
3671 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003672 int nGot;
drha78c22c2008-11-11 18:28:58 +00003673 pNew = sqlite3DbRealloc(db, pSrc,
3674 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3675 if( pNew==0 ){
3676 assert( db->mallocFailed );
3677 return pSrc;
3678 }
3679 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003680 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003681 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003682 }
3683
3684 /* Move existing slots that come after the newly inserted slots
3685 ** out of the way */
3686 for(i=pSrc->nSrc-1; i>=iStart; i--){
3687 pSrc->a[i+nExtra] = pSrc->a[i];
3688 }
drh6d1626e2014-03-05 15:52:43 +00003689 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003690
3691 /* Zero the newly allocated slots */
3692 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3693 for(i=iStart; i<iStart+nExtra; i++){
3694 pSrc->a[i].iCursor = -1;
3695 }
3696
3697 /* Return a pointer to the enlarged SrcList */
3698 return pSrc;
3699}
3700
3701
3702/*
drhad3cab52002-05-24 02:04:32 +00003703** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003704** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003705**
drha78c22c2008-11-11 18:28:58 +00003706** A SrcList is returned, or NULL if there is an OOM error. The returned
3707** SrcList might be the same as the SrcList that was input or it might be
3708** a new one. If an OOM error does occurs, then the prior value of pList
3709** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003710**
3711** If pDatabase is not null, it means that the table has an optional
3712** database name prefix. Like this: "database.table". The pDatabase
3713** points to the table name and the pTable points to the database name.
3714** The SrcList.a[].zName field is filled with the table name which might
3715** come from pTable (if pDatabase is NULL) or from pDatabase.
3716** SrcList.a[].zDatabase is filled with the database name from pTable,
3717** or with NULL if no database is specified.
3718**
3719** In other words, if call like this:
3720**
drh17435752007-08-16 04:30:38 +00003721** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003722**
3723** Then B is a table name and the database name is unspecified. If called
3724** like this:
3725**
drh17435752007-08-16 04:30:38 +00003726** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003727**
drhd3001712009-05-12 17:46:53 +00003728** Then C is the table name and B is the database name. If C is defined
3729** then so is B. In other words, we never have a case where:
3730**
3731** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003732**
3733** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3734** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003735*/
drh17435752007-08-16 04:30:38 +00003736SrcList *sqlite3SrcListAppend(
3737 sqlite3 *db, /* Connection to notify of malloc failures */
3738 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3739 Token *pTable, /* Table to append */
3740 Token *pDatabase /* Database of the table */
3741){
drha99db3b2004-06-19 14:49:12 +00003742 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003743 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003744 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003745 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003746 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003747 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003748 }
drha78c22c2008-11-11 18:28:58 +00003749 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3750 if( db->mallocFailed ){
3751 sqlite3SrcListDelete(db, pList);
3752 return 0;
drhad3cab52002-05-24 02:04:32 +00003753 }
drha78c22c2008-11-11 18:28:58 +00003754 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003755 if( pDatabase && pDatabase->z==0 ){
3756 pDatabase = 0;
3757 }
drhd3001712009-05-12 17:46:53 +00003758 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003759 Token *pTemp = pDatabase;
3760 pDatabase = pTable;
3761 pTable = pTemp;
3762 }
drh17435752007-08-16 04:30:38 +00003763 pItem->zName = sqlite3NameFromToken(db, pTable);
3764 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003765 return pList;
3766}
3767
3768/*
drhdfe88ec2008-11-03 20:55:06 +00003769** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003770*/
danielk19774adee202004-05-08 08:23:19 +00003771void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003772 int i;
drh9b3187e2005-01-18 14:45:47 +00003773 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003774 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003775 if( pList ){
3776 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3777 if( pItem->iCursor>=0 ) break;
3778 pItem->iCursor = pParse->nTab++;
3779 if( pItem->pSelect ){
3780 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3781 }
drh63eb5f22003-04-29 16:20:44 +00003782 }
3783 }
3784}
3785
3786/*
drhad3cab52002-05-24 02:04:32 +00003787** Delete an entire SrcList including all its substructure.
3788*/
drh633e6d52008-07-28 19:34:53 +00003789void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003790 int i;
drhbe5c89a2004-07-26 00:31:09 +00003791 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003792 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003793 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003794 sqlite3DbFree(db, pItem->zDatabase);
3795 sqlite3DbFree(db, pItem->zName);
3796 sqlite3DbFree(db, pItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00003797 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
3798 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
dan1feeaed2010-07-23 15:41:47 +00003799 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003800 sqlite3SelectDelete(db, pItem->pSelect);
3801 sqlite3ExprDelete(db, pItem->pOn);
3802 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003803 }
drh633e6d52008-07-28 19:34:53 +00003804 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003805}
3806
drh982cef72000-05-30 16:27:03 +00003807/*
drh61dfc312006-12-16 16:25:15 +00003808** This routine is called by the parser to add a new term to the
3809** end of a growing FROM clause. The "p" parameter is the part of
3810** the FROM clause that has already been constructed. "p" is NULL
3811** if this is the first term of the FROM clause. pTable and pDatabase
3812** are the name of the table and database named in the FROM clause term.
3813** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003814** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003815** alias token. If the term is a subquery, then pSubquery is the
3816** SELECT statement that the subquery encodes. The pTable and
3817** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3818** parameters are the content of the ON and USING clauses.
3819**
3820** Return a new SrcList which encodes is the FROM with the new
3821** term added.
3822*/
3823SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003824 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003825 SrcList *p, /* The left part of the FROM clause already seen */
3826 Token *pTable, /* Name of the table to add to the FROM clause */
3827 Token *pDatabase, /* Name of the database containing pTable */
3828 Token *pAlias, /* The right-hand side of the AS subexpression */
3829 Select *pSubquery, /* A subquery used in place of a table name */
3830 Expr *pOn, /* The ON clause of a join */
3831 IdList *pUsing /* The USING clause of a join */
3832){
3833 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003834 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003835 if( !p && (pOn || pUsing) ){
3836 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3837 (pOn ? "ON" : "USING")
3838 );
3839 goto append_from_error;
3840 }
drh17435752007-08-16 04:30:38 +00003841 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003842 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003843 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003844 }
3845 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003846 assert( pAlias!=0 );
3847 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003848 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003849 }
3850 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003851 pItem->pOn = pOn;
3852 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003853 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003854
3855 append_from_error:
3856 assert( p==0 );
3857 sqlite3ExprDelete(db, pOn);
3858 sqlite3IdListDelete(db, pUsing);
3859 sqlite3SelectDelete(db, pSubquery);
3860 return 0;
drh61dfc312006-12-16 16:25:15 +00003861}
3862
3863/*
danielk1977b1c685b2008-10-06 16:18:39 +00003864** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3865** element of the source-list passed as the second argument.
3866*/
3867void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003868 assert( pIndexedBy!=0 );
3869 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003870 struct SrcList_item *pItem = &p->a[p->nSrc-1];
drh8a48b9c2015-08-19 15:20:00 +00003871 assert( pItem->fg.notIndexed==0 );
3872 assert( pItem->fg.isIndexedBy==0 );
3873 assert( pItem->fg.isTabFunc==0 );
danielk1977b1c685b2008-10-06 16:18:39 +00003874 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3875 /* A "NOT INDEXED" clause was supplied. See parse.y
3876 ** construct "indexed_opt" for details. */
drh8a48b9c2015-08-19 15:20:00 +00003877 pItem->fg.notIndexed = 1;
danielk1977b1c685b2008-10-06 16:18:39 +00003878 }else{
drh8a48b9c2015-08-19 15:20:00 +00003879 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
3880 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
danielk1977b1c685b2008-10-06 16:18:39 +00003881 }
3882 }
3883}
3884
3885/*
drh01d230c2015-08-19 17:11:37 +00003886** Add the list of function arguments to the SrcList entry for a
3887** table-valued-function.
3888*/
3889void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
drhd8b1bfc2015-08-20 23:21:34 +00003890 if( p && pList ){
drh01d230c2015-08-19 17:11:37 +00003891 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3892 assert( pItem->fg.notIndexed==0 );
3893 assert( pItem->fg.isIndexedBy==0 );
3894 assert( pItem->fg.isTabFunc==0 );
3895 pItem->u1.pFuncArg = pList;
3896 pItem->fg.isTabFunc = 1;
drhd8b1bfc2015-08-20 23:21:34 +00003897 }else{
3898 sqlite3ExprListDelete(pParse->db, pList);
drh01d230c2015-08-19 17:11:37 +00003899 }
3900}
3901
3902/*
drh61dfc312006-12-16 16:25:15 +00003903** When building up a FROM clause in the parser, the join operator
3904** is initially attached to the left operand. But the code generator
3905** expects the join operator to be on the right operand. This routine
3906** Shifts all join operators from left to right for an entire FROM
3907** clause.
3908**
3909** Example: Suppose the join is like this:
3910**
3911** A natural cross join B
3912**
3913** The operator is "natural cross join". The A and B operands are stored
3914** in p->a[0] and p->a[1], respectively. The parser initially stores the
3915** operator with A. This routine shifts that operator over to B.
3916*/
3917void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003918 if( p ){
drh61dfc312006-12-16 16:25:15 +00003919 int i;
3920 for(i=p->nSrc-1; i>0; i--){
drh8a48b9c2015-08-19 15:20:00 +00003921 p->a[i].fg.jointype = p->a[i-1].fg.jointype;
drh61dfc312006-12-16 16:25:15 +00003922 }
drh8a48b9c2015-08-19 15:20:00 +00003923 p->a[0].fg.jointype = 0;
drh61dfc312006-12-16 16:25:15 +00003924 }
3925}
3926
3927/*
drhc4a3c772001-04-04 11:48:57 +00003928** Begin a transaction
3929*/
drh684917c2004-10-05 02:41:42 +00003930void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003931 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003932 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003933 int i;
drh5e00f6c2001-09-13 13:46:56 +00003934
drhd3001712009-05-12 17:46:53 +00003935 assert( pParse!=0 );
3936 db = pParse->db;
3937 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003938/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003939 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3940 return;
3941 }
danielk19771d850a72004-05-31 08:26:49 +00003942 v = sqlite3GetVdbe(pParse);
3943 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003944 if( type!=TK_DEFERRED ){
3945 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003946 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003947 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003948 }
3949 }
drh66a51672008-01-03 00:01:23 +00003950 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003951}
3952
3953/*
3954** Commit a transaction
3955*/
danielk19774adee202004-05-08 08:23:19 +00003956void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003957 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003958
drhd3001712009-05-12 17:46:53 +00003959 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003960 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003961 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3962 return;
3963 }
danielk19771d850a72004-05-31 08:26:49 +00003964 v = sqlite3GetVdbe(pParse);
3965 if( v ){
drh66a51672008-01-03 00:01:23 +00003966 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003967 }
drhc4a3c772001-04-04 11:48:57 +00003968}
3969
3970/*
3971** Rollback a transaction
3972*/
danielk19774adee202004-05-08 08:23:19 +00003973void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003974 Vdbe *v;
3975
drhd3001712009-05-12 17:46:53 +00003976 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003977 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003978 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3979 return;
3980 }
danielk19774adee202004-05-08 08:23:19 +00003981 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003982 if( v ){
drh66a51672008-01-03 00:01:23 +00003983 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003984 }
drhc4a3c772001-04-04 11:48:57 +00003985}
drhf57b14a2001-09-14 18:54:08 +00003986
3987/*
danielk1977fd7f0452008-12-17 17:30:26 +00003988** This function is called by the parser when it parses a command to create,
3989** release or rollback an SQL savepoint.
3990*/
3991void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003992 char *zName = sqlite3NameFromToken(pParse->db, pName);
3993 if( zName ){
3994 Vdbe *v = sqlite3GetVdbe(pParse);
3995#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003996 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003997 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3998#endif
3999 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
4000 sqlite3DbFree(pParse->db, zName);
4001 return;
4002 }
4003 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00004004 }
4005}
4006
4007/*
drhdc3ff9c2004-08-18 02:10:15 +00004008** Make sure the TEMP database is open and available for use. Return
4009** the number of errors. Leave any error messages in the pParse structure.
4010*/
danielk1977ddfb2f02006-02-17 12:25:14 +00004011int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00004012 sqlite3 *db = pParse->db;
4013 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00004014 int rc;
drh10a76c92010-01-26 01:25:26 +00004015 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00004016 static const int flags =
4017 SQLITE_OPEN_READWRITE |
4018 SQLITE_OPEN_CREATE |
4019 SQLITE_OPEN_EXCLUSIVE |
4020 SQLITE_OPEN_DELETEONCLOSE |
4021 SQLITE_OPEN_TEMP_DB;
4022
dan3a6d8ae2011-04-23 15:54:54 +00004023 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00004024 if( rc!=SQLITE_OK ){
4025 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4026 "file for storing temporary tables");
4027 pParse->rc = rc;
4028 return 1;
4029 }
drh10a76c92010-01-26 01:25:26 +00004030 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00004031 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00004032 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
4033 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00004034 return 1;
drh10a76c92010-01-26 01:25:26 +00004035 }
drhdc3ff9c2004-08-18 02:10:15 +00004036 }
4037 return 0;
4038}
4039
4040/*
drhaceb31b2014-02-08 01:40:27 +00004041** Record the fact that the schema cookie will need to be verified
4042** for database iDb. The code to actually verify the schema cookie
4043** will occur at the end of the top-level VDBE and will be generated
4044** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00004045*/
danielk19774adee202004-05-08 08:23:19 +00004046void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004047 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00004048 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00004049
drhaceb31b2014-02-08 01:40:27 +00004050 assert( iDb>=0 && iDb<db->nDb );
4051 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
4052 assert( iDb<SQLITE_MAX_ATTACHED+2 );
4053 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00004054 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4055 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00004056 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
4057 if( !OMIT_TEMPDB && iDb==1 ){
4058 sqlite3OpenTempDatabase(pToplevel);
4059 }
drh001bbcb2003-03-19 03:14:00 +00004060 }
drh001bbcb2003-03-19 03:14:00 +00004061}
4062
4063/*
dan57966752011-04-09 17:32:58 +00004064** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4065** attached database. Otherwise, invoke it for the database named zDb only.
4066*/
4067void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4068 sqlite3 *db = pParse->db;
4069 int i;
4070 for(i=0; i<db->nDb; i++){
4071 Db *pDb = &db->aDb[i];
4072 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
4073 sqlite3CodeVerifySchema(pParse, i);
4074 }
4075 }
4076}
4077
4078/*
drh1c928532002-01-31 15:54:21 +00004079** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00004080** might change the database.
4081**
4082** This routine starts a new transaction if we are not already within
4083** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00004084** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00004085** be set for operations that might fail (due to a constraint) part of
4086** the way through and which will need to undo some writes without having to
4087** rollback the whole transaction. For operations where all constraints
4088** can be checked before any changes are made to the database, it is never
4089** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00004090*/
drh7f0f12e2004-05-21 13:39:50 +00004091void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004092 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00004093 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00004094 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00004095 pToplevel->isMultiWrite |= setStatement;
4096}
4097
drhff738bc2009-09-24 00:09:58 +00004098/*
4099** Indicate that the statement currently under construction might write
4100** more than one entry (example: deleting one row then inserting another,
4101** inserting multiple rows in a table, or inserting a row and index entries.)
4102** If an abort occurs after some of these writes have completed, then it will
4103** be necessary to undo the completed writes.
4104*/
4105void sqlite3MultiWrite(Parse *pParse){
4106 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4107 pToplevel->isMultiWrite = 1;
4108}
4109
dane0af83a2009-09-08 19:15:01 +00004110/*
drhff738bc2009-09-24 00:09:58 +00004111** The code generator calls this routine if is discovers that it is
4112** possible to abort a statement prior to completion. In order to
4113** perform this abort without corrupting the database, we need to make
4114** sure that the statement is protected by a statement transaction.
4115**
4116** Technically, we only need to set the mayAbort flag if the
4117** isMultiWrite flag was previously set. There is a time dependency
4118** such that the abort must occur after the multiwrite. This makes
4119** some statements involving the REPLACE conflict resolution algorithm
4120** go a little faster. But taking advantage of this time dependency
4121** makes it more difficult to prove that the code is correct (in
4122** particular, it prevents us from writing an effective
4123** implementation of sqlite3AssertMayAbort()) and so we have chosen
4124** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00004125*/
4126void sqlite3MayAbort(Parse *pParse){
4127 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4128 pToplevel->mayAbort = 1;
4129}
4130
4131/*
4132** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4133** error. The onError parameter determines which (if any) of the statement
4134** and/or current transaction is rolled back.
4135*/
drhd91c1a12013-02-09 13:58:25 +00004136void sqlite3HaltConstraint(
4137 Parse *pParse, /* Parsing context */
4138 int errCode, /* extended error code */
4139 int onError, /* Constraint type */
4140 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00004141 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4142 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00004143){
dane0af83a2009-09-08 19:15:01 +00004144 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00004145 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00004146 if( onError==OE_Abort ){
4147 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00004148 }
drhd91c1a12013-02-09 13:58:25 +00004149 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00004150 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4151}
4152
4153/*
4154** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4155*/
4156void sqlite3UniqueConstraint(
4157 Parse *pParse, /* Parsing context */
4158 int onError, /* Constraint type */
4159 Index *pIdx /* The index that triggers the constraint */
4160){
4161 char *zErr;
4162 int j;
4163 StrAccum errMsg;
4164 Table *pTab = pIdx->pTable;
4165
drhc0490572015-05-02 11:45:53 +00004166 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
drh8b576422015-08-31 23:09:42 +00004167 if( pIdx->aColExpr ){
4168 sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
4169 }else{
4170 for(j=0; j<pIdx->nKeyCol; j++){
4171 char *zCol;
4172 assert( pIdx->aiColumn[j]>=0 );
4173 zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4174 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
4175 sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
4176 }
drhf9c8ce32013-11-05 13:33:55 +00004177 }
4178 zErr = sqlite3StrAccumFinish(&errMsg);
4179 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004180 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4181 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004182 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004183}
4184
4185
4186/*
4187** Code an OP_Halt due to non-unique rowid.
4188*/
4189void sqlite3RowidConstraint(
4190 Parse *pParse, /* Parsing context */
4191 int onError, /* Conflict resolution algorithm */
4192 Table *pTab /* The table with the non-unique rowid */
4193){
4194 char *zMsg;
4195 int rc;
4196 if( pTab->iPKey>=0 ){
4197 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4198 pTab->aCol[pTab->iPKey].zName);
4199 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4200 }else{
4201 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4202 rc = SQLITE_CONSTRAINT_ROWID;
4203 }
4204 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4205 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004206}
4207
drh4343fea2004-11-05 23:46:15 +00004208/*
4209** Check to see if pIndex uses the collating sequence pColl. Return
4210** true if it does and false if it does not.
4211*/
4212#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004213static int collationMatch(const char *zColl, Index *pIndex){
4214 int i;
drh04491712009-05-13 17:21:13 +00004215 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004216 for(i=0; i<pIndex->nColumn; i++){
4217 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004218 assert( z!=0 || pIndex->aiColumn[i]<0 );
4219 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004220 return 1;
4221 }
drh4343fea2004-11-05 23:46:15 +00004222 }
4223 return 0;
4224}
4225#endif
4226
4227/*
4228** Recompute all indices of pTab that use the collating sequence pColl.
4229** If pColl==0 then recompute all indices of pTab.
4230*/
4231#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004232static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004233 Index *pIndex; /* An index associated with pTab */
4234
4235 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004236 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004237 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4238 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004239 sqlite3RefillIndex(pParse, pIndex, -1);
4240 }
4241 }
4242}
4243#endif
4244
4245/*
4246** Recompute all indices of all tables in all databases where the
4247** indices use the collating sequence pColl. If pColl==0 then recompute
4248** all indices everywhere.
4249*/
4250#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004251static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004252 Db *pDb; /* A single database */
4253 int iDb; /* The database index number */
4254 sqlite3 *db = pParse->db; /* The database connection */
4255 HashElem *k; /* For looping over tables in pDb */
4256 Table *pTab; /* A table in the database */
4257
drh21206082011-04-04 18:22:02 +00004258 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004259 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004260 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004261 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004262 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004263 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004264 }
4265 }
4266}
4267#endif
4268
4269/*
drheee46cf2004-11-06 00:02:48 +00004270** Generate code for the REINDEX command.
4271**
4272** REINDEX -- 1
4273** REINDEX <collation> -- 2
4274** REINDEX ?<database>.?<tablename> -- 3
4275** REINDEX ?<database>.?<indexname> -- 4
4276**
4277** Form 1 causes all indices in all attached databases to be rebuilt.
4278** Form 2 rebuilds all indices in all databases that use the named
4279** collating function. Forms 3 and 4 rebuild the named index or all
4280** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004281*/
4282#ifndef SQLITE_OMIT_REINDEX
4283void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4284 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4285 char *z; /* Name of a table or index */
4286 const char *zDb; /* Name of the database */
4287 Table *pTab; /* A table in the database */
4288 Index *pIndex; /* An index associated with pTab */
4289 int iDb; /* The database index number */
4290 sqlite3 *db = pParse->db; /* The database connection */
4291 Token *pObjName; /* Name of the table or index to be reindexed */
4292
danielk197733a5edc2005-01-27 00:22:02 +00004293 /* Read the database schema. If an error occurs, leave an error message
4294 ** and code in pParse and return NULL. */
4295 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004296 return;
danielk197733a5edc2005-01-27 00:22:02 +00004297 }
4298
drh8af73d42009-05-13 22:58:28 +00004299 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004300 reindexDatabases(pParse, 0);
4301 return;
drhd3001712009-05-12 17:46:53 +00004302 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004303 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004304 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004305 zColl = sqlite3NameFromToken(pParse->db, pName1);
4306 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004307 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004308 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004309 reindexDatabases(pParse, zColl);
4310 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004311 return;
4312 }
drh633e6d52008-07-28 19:34:53 +00004313 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004314 }
4315 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4316 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004317 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004318 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004319 zDb = db->aDb[iDb].zName;
4320 pTab = sqlite3FindTable(db, z, zDb);
4321 if( pTab ){
4322 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004323 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004324 return;
4325 }
4326 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004327 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004328 if( pIndex ){
4329 sqlite3BeginWriteOperation(pParse, 0, iDb);
4330 sqlite3RefillIndex(pParse, pIndex, -1);
4331 return;
4332 }
4333 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4334}
4335#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004336
4337/*
drh2ec2fb22013-11-06 19:59:23 +00004338** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004339**
drh2ec2fb22013-11-06 19:59:23 +00004340** The KeyInfo structure for an index is cached in the Index object.
4341** So there might be multiple references to the returned pointer. The
4342** caller should not try to modify the KeyInfo object.
4343**
4344** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4345** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004346*/
drh2ec2fb22013-11-06 19:59:23 +00004347KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh18b67f32014-12-12 00:20:37 +00004348 int i;
4349 int nCol = pIdx->nColumn;
4350 int nKey = pIdx->nKeyCol;
4351 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004352 if( pParse->nErr ) return 0;
drh18b67f32014-12-12 00:20:37 +00004353 if( pIdx->uniqNotNull ){
4354 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4355 }else{
4356 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
drh41e13e12013-11-07 14:09:39 +00004357 }
drh18b67f32014-12-12 00:20:37 +00004358 if( pKey ){
4359 assert( sqlite3KeyInfoIsWriteable(pKey) );
4360 for(i=0; i<nCol; i++){
4361 char *zColl = pIdx->azColl[i];
4362 assert( zColl!=0 );
4363 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4364 sqlite3LocateCollSeq(pParse, zColl);
4365 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
drh2ec2fb22013-11-06 19:59:23 +00004366 }
drh18b67f32014-12-12 00:20:37 +00004367 if( pParse->nErr ){
4368 sqlite3KeyInfoUnref(pKey);
4369 pKey = 0;
danielk1977b3bf5562006-01-10 17:58:23 +00004370 }
danielk1977b3bf5562006-01-10 17:58:23 +00004371 }
drh18b67f32014-12-12 00:20:37 +00004372 return pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00004373}
drh8b471862014-01-11 13:22:17 +00004374
4375#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004376/*
4377** This routine is invoked once per CTE by the parser while parsing a
4378** WITH clause.
drh8b471862014-01-11 13:22:17 +00004379*/
dan7d562db2014-01-11 19:19:36 +00004380With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004381 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004382 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004383 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004384 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004385 Select *pQuery /* Query used to initialize the table */
4386){
dan4e9119d2014-01-13 15:12:23 +00004387 sqlite3 *db = pParse->db;
4388 With *pNew;
4389 char *zName;
4390
4391 /* Check that the CTE name is unique within this WITH clause. If
4392 ** not, store an error in the Parse structure. */
4393 zName = sqlite3NameFromToken(pParse->db, pName);
4394 if( zName && pWith ){
4395 int i;
4396 for(i=0; i<pWith->nCte; i++){
4397 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004398 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004399 }
4400 }
4401 }
4402
4403 if( pWith ){
4404 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4405 pNew = sqlite3DbRealloc(db, pWith, nByte);
4406 }else{
4407 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4408 }
4409 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004410 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004411
4412 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004413 sqlite3ExprListDelete(db, pArglist);
4414 sqlite3SelectDelete(db, pQuery);
4415 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004416 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004417 }else{
4418 pNew->a[pNew->nCte].pSelect = pQuery;
4419 pNew->a[pNew->nCte].pCols = pArglist;
4420 pNew->a[pNew->nCte].zName = zName;
drh0576bc52015-08-26 11:40:11 +00004421 pNew->a[pNew->nCte].zCteErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004422 pNew->nCte++;
4423 }
4424
4425 return pNew;
drh8b471862014-01-11 13:22:17 +00004426}
4427
dan7d562db2014-01-11 19:19:36 +00004428/*
4429** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004430*/
dan7d562db2014-01-11 19:19:36 +00004431void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004432 if( pWith ){
4433 int i;
4434 for(i=0; i<pWith->nCte; i++){
4435 struct Cte *pCte = &pWith->a[i];
4436 sqlite3ExprListDelete(db, pCte->pCols);
4437 sqlite3SelectDelete(db, pCte->pSelect);
4438 sqlite3DbFree(db, pCte->zName);
4439 }
4440 sqlite3DbFree(db, pWith);
4441 }
drh8b471862014-01-11 13:22:17 +00004442}
4443#endif /* !defined(SQLITE_OMIT_CTE) */