blob: 7c79fe54007a2948558918246dea4dffcf31510a [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
1052/*
danielk1977c60e9b82005-01-31 12:42:29 +00001053** This macro is used to compare two strings in a case-insensitive manner.
1054** It is slightly faster than calling sqlite3StrICmp() directly, but
1055** produces larger code.
1056**
1057** WARNING: This macro is not compatible with the strcmp() family. It
1058** returns true if the two strings are equal, otherwise false.
1059*/
1060#define STRICMP(x, y) (\
1061sqlite3UpperToLower[*(unsigned char *)(x)]== \
1062sqlite3UpperToLower[*(unsigned char *)(y)] \
1063&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1064
1065/*
drh75897232000-05-29 14:26:00 +00001066** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001067**
1068** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001069** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001070** first to get things going. Then this routine is called for each
1071** column.
drh75897232000-05-29 14:26:00 +00001072*/
danielk19774adee202004-05-08 08:23:19 +00001073void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001074 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001075 int i;
drha99db3b2004-06-19 14:49:12 +00001076 char *z;
drhc9b84a12002-06-20 11:36:48 +00001077 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001078 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001079 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001080#if SQLITE_MAX_COLUMN
1081 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001082 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1083 return;
1084 }
drhbb4957f2008-03-20 14:03:29 +00001085#endif
danielk1977ae74e032008-12-23 11:11:51 +00001086 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001087 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001088 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001089 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001090 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001091 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001092 return;
1093 }
1094 }
drh75897232000-05-29 14:26:00 +00001095 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001096 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001097 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001098 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001099 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001100 return;
1101 }
drh6d4abfb2001-10-22 02:58:08 +00001102 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001103 }
drhc9b84a12002-06-20 11:36:48 +00001104 pCol = &p->aCol[p->nCol];
1105 memset(pCol, 0, sizeof(p->aCol[0]));
1106 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001107
1108 /* If there is no type specified, columns have the default affinity
drh05883a32015-06-02 15:32:08 +00001109 ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
danielk19774f057f92004-06-08 00:02:33 +00001110 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001111 */
drh05883a32015-06-02 15:32:08 +00001112 pCol->affinity = SQLITE_AFF_BLOB;
drhfdaac672013-10-04 15:30:21 +00001113 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001114 p->nCol++;
drh75897232000-05-29 14:26:00 +00001115}
1116
1117/*
drh382c0242001-10-06 16:33:02 +00001118** This routine is called by the parser while in the middle of
1119** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1120** been seen on a column. This routine sets the notNull flag on
1121** the column currently under construction.
1122*/
danielk19774adee202004-05-08 08:23:19 +00001123void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001124 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001125 p = pParse->pNewTable;
1126 if( p==0 || NEVER(p->nCol<1) ) return;
1127 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001128}
1129
1130/*
danielk197752a83fb2005-01-31 12:56:44 +00001131** Scan the column type name zType (length nType) and return the
1132** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001133**
1134** This routine does a case-independent search of zType for the
1135** substrings in the following table. If one of the substrings is
1136** found, the corresponding affinity is returned. If zType contains
1137** more than one of the substrings, entries toward the top of
1138** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001139** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001140**
1141** Substring | Affinity
1142** --------------------------------
1143** 'INT' | SQLITE_AFF_INTEGER
1144** 'CHAR' | SQLITE_AFF_TEXT
1145** 'CLOB' | SQLITE_AFF_TEXT
1146** 'TEXT' | SQLITE_AFF_TEXT
drh05883a32015-06-02 15:32:08 +00001147** 'BLOB' | SQLITE_AFF_BLOB
drh8a512562005-11-14 22:29:05 +00001148** 'REAL' | SQLITE_AFF_REAL
1149** 'FLOA' | SQLITE_AFF_REAL
1150** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001151**
1152** If none of the substrings in the above table are found,
1153** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001154*/
drhfdaac672013-10-04 15:30:21 +00001155char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001156 u32 h = 0;
1157 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001158 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001159
drhfdaac672013-10-04 15:30:21 +00001160 if( zIn==0 ) return aff;
1161 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001162 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001163 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001164 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001165 aff = SQLITE_AFF_TEXT;
1166 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001167 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1168 aff = SQLITE_AFF_TEXT;
1169 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1170 aff = SQLITE_AFF_TEXT;
1171 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001172 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
drh05883a32015-06-02 15:32:08 +00001173 aff = SQLITE_AFF_BLOB;
drhd3037a42013-10-04 18:29:25 +00001174 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001175#ifndef SQLITE_OMIT_FLOATING_POINT
1176 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1177 && aff==SQLITE_AFF_NUMERIC ){
1178 aff = SQLITE_AFF_REAL;
1179 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1180 && aff==SQLITE_AFF_NUMERIC ){
1181 aff = SQLITE_AFF_REAL;
1182 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1183 && aff==SQLITE_AFF_NUMERIC ){
1184 aff = SQLITE_AFF_REAL;
1185#endif
danielk1977201f7162005-02-01 02:13:29 +00001186 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001187 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001188 break;
danielk197752a83fb2005-01-31 12:56:44 +00001189 }
1190 }
drhd3037a42013-10-04 18:29:25 +00001191
1192 /* If pszEst is not NULL, store an estimate of the field size. The
1193 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001194 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001195 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001196 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001197 if( zChar ){
1198 while( zChar[0] ){
1199 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001200 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001201 sqlite3GetInt32(zChar, &v);
1202 v = v/4 + 1;
1203 if( v>255 ) v = 255;
1204 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1205 break;
1206 }
1207 zChar++;
drhfdaac672013-10-04 15:30:21 +00001208 }
drhd3037a42013-10-04 18:29:25 +00001209 }else{
1210 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001211 }
drhfdaac672013-10-04 15:30:21 +00001212 }
1213 }
danielk1977b3dff962005-02-01 01:21:55 +00001214 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001215}
1216
1217/*
drh382c0242001-10-06 16:33:02 +00001218** This routine is called by the parser while in the middle of
1219** parsing a CREATE TABLE statement. The pFirst token is the first
1220** token in the sequence of tokens that describe the type of the
1221** column currently under construction. pLast is the last token
1222** in the sequence. Use this information to construct a string
1223** that contains the typename of the column and store that string
1224** in zType.
1225*/
drh487e2622005-06-25 18:42:14 +00001226void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001227 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001228 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001229
drhc4a64fa2009-05-11 20:53:28 +00001230 p = pParse->pNewTable;
1231 if( p==0 || NEVER(p->nCol<1) ) return;
1232 pCol = &p->aCol[p->nCol-1];
drh5f1d2fa2015-04-19 21:59:19 +00001233 assert( pCol->zType==0 || CORRUPT_DB );
1234 sqlite3DbFree(pParse->db, pCol->zType);
drhc4a64fa2009-05-11 20:53:28 +00001235 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001236 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001237}
1238
1239/*
danielk19777977a172004-11-09 12:44:37 +00001240** The expression is the default value for the most recently added column
1241** of the table currently under construction.
1242**
1243** Default value expressions must be constant. Raise an exception if this
1244** is not the case.
drhd9b02572001-04-15 00:37:09 +00001245**
1246** This routine is called by the parser while in the middle of
1247** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001248*/
drhb7916a72009-05-27 10:31:29 +00001249void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001250 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001251 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001252 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001253 p = pParse->pNewTable;
1254 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001255 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001256 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001257 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1258 pCol->zName);
1259 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001260 /* A copy of pExpr is used instead of the original, as pExpr contains
1261 ** tokens that point to volatile memory. The 'span' of the expression
1262 ** is required by pragma table_info.
1263 */
drh633e6d52008-07-28 19:34:53 +00001264 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001265 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1266 sqlite3DbFree(db, pCol->zDflt);
1267 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001268 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001269 }
danielk19777977a172004-11-09 12:44:37 +00001270 }
drhb7916a72009-05-27 10:31:29 +00001271 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001272}
1273
1274/*
drh4a324312001-12-21 14:30:42 +00001275** Designate the PRIMARY KEY for the table. pList is a list of names
1276** of columns that form the primary key. If pList is NULL, then the
1277** most recently added column of the table is the primary key.
1278**
1279** A table can have at most one primary key. If the table already has
1280** a primary key (and this is the second primary key) then create an
1281** error.
1282**
1283** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001284** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001285** field of the table under construction to be the index of the
1286** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1287** no INTEGER PRIMARY KEY.
1288**
1289** If the key is not an INTEGER PRIMARY KEY, then create a unique
1290** index for the key. No index is created for INTEGER PRIMARY KEYs.
1291*/
drh205f48e2004-11-05 00:43:11 +00001292void sqlite3AddPrimaryKey(
1293 Parse *pParse, /* Parsing context */
1294 ExprList *pList, /* List of field names to be indexed */
1295 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001296 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1297 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001298){
drh4a324312001-12-21 14:30:42 +00001299 Table *pTab = pParse->pNewTable;
1300 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001301 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001302 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001303 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001304 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001305 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001306 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001307 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001308 }
drh7d10d5a2008-08-20 16:35:10 +00001309 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001310 if( pList==0 ){
1311 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001312 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001313 zType = pTab->aCol[iCol].zType;
1314 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001315 }else{
drh8ea30bf2013-10-22 01:18:17 +00001316 nTerm = pList->nExpr;
1317 for(i=0; i<nTerm; i++){
drh108aa002015-08-24 20:21:20 +00001318 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drh7d3d9da2015-09-01 00:42:52 +00001319 assert( pCExpr!=0 );
1320 if( pCExpr->op==TK_ID ){
drh108aa002015-08-24 20:21:20 +00001321 const char *zCName = pCExpr->u.zToken;
1322 for(iCol=0; iCol<pTab->nCol; iCol++){
1323 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1324 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1325 zType = pTab->aCol[iCol].zType;
1326 break;
1327 }
drhd3d39e92004-05-20 22:16:29 +00001328 }
drh78100cc2003-08-23 22:40:53 +00001329 }
drh4a324312001-12-21 14:30:42 +00001330 }
1331 }
drh8ea30bf2013-10-22 01:18:17 +00001332 if( nTerm==1
1333 && zType && sqlite3StrICmp(zType, "INTEGER")==0
drhbc622bc2015-08-24 15:39:42 +00001334 && sortOrder!=SQLITE_SO_DESC
drh8ea30bf2013-10-22 01:18:17 +00001335 ){
drh4a324312001-12-21 14:30:42 +00001336 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001337 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001338 assert( autoInc==0 || autoInc==1 );
1339 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001340 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001341 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001342#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001343 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1344 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001345#endif
drh4a324312001-12-21 14:30:42 +00001346 }else{
dan1da40a32009-09-19 17:00:31 +00001347 Index *p;
drh8a9789b2013-08-01 03:36:59 +00001348 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001349 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001350 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001351 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
dan1da40a32009-09-19 17:00:31 +00001352 }
drhe0194f22003-02-26 13:52:51 +00001353 pList = 0;
drh4a324312001-12-21 14:30:42 +00001354 }
drhe0194f22003-02-26 13:52:51 +00001355
1356primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001357 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001358 return;
drh4a324312001-12-21 14:30:42 +00001359}
1360
1361/*
drhffe07b22005-11-03 00:41:17 +00001362** Add a new CHECK constraint to the table currently under construction.
1363*/
1364void sqlite3AddCheckConstraint(
1365 Parse *pParse, /* Parsing context */
1366 Expr *pCheckExpr /* The check expression */
1367){
1368#ifndef SQLITE_OMIT_CHECK
1369 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001370 sqlite3 *db = pParse->db;
1371 if( pTab && !IN_DECLARE_VTAB
1372 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1373 ){
drh2938f922012-03-07 19:13:29 +00001374 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1375 if( pParse->constraintName.n ){
1376 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1377 }
drh33e619f2009-05-28 01:00:55 +00001378 }else
drhffe07b22005-11-03 00:41:17 +00001379#endif
drh33e619f2009-05-28 01:00:55 +00001380 {
drh2938f922012-03-07 19:13:29 +00001381 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001382 }
drhffe07b22005-11-03 00:41:17 +00001383}
1384
1385/*
drhd3d39e92004-05-20 22:16:29 +00001386** Set the collation function of the most recently parsed table column
1387** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001388*/
danielk197739002502007-11-12 09:50:26 +00001389void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001390 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001391 int i;
danielk197739002502007-11-12 09:50:26 +00001392 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001393 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001394
danielk1977b8cbb872006-06-19 05:33:45 +00001395 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001396 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001397 db = pParse->db;
1398 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001399 if( !zColl ) return;
1400
drhc4a64fa2009-05-11 20:53:28 +00001401 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001402 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001403 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001404 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001405
1406 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1407 ** then an index may have been created on this column before the
1408 ** collation type was added. Correct this if it is the case.
1409 */
1410 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001411 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001412 if( pIdx->aiColumn[0]==i ){
1413 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001414 }
1415 }
danielk197739002502007-11-12 09:50:26 +00001416 }else{
drh633e6d52008-07-28 19:34:53 +00001417 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001418 }
danielk19777cedc8d2004-06-10 10:50:08 +00001419}
1420
danielk1977466be562004-06-10 02:16:01 +00001421/*
1422** This function returns the collation sequence for database native text
1423** encoding identified by the string zName, length nName.
1424**
1425** If the requested collation sequence is not available, or not available
1426** in the database native encoding, the collation factory is invoked to
1427** request it. If the collation factory does not supply such a sequence,
1428** and the sequence is available in another text encoding, then that is
1429** returned instead.
1430**
1431** If no versions of the requested collations sequence are available, or
1432** another error occurs, NULL is returned and an error message written into
1433** pParse.
drha34001c2007-02-02 12:44:37 +00001434**
1435** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1436** invokes the collation factory if the named collation cannot be found
1437** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001438**
1439** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001440*/
drhc4a64fa2009-05-11 20:53:28 +00001441CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001442 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001443 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001444 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001445 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001446
drhc4a64fa2009-05-11 20:53:28 +00001447 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001448 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001449 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001450 }
1451
danielk19770202b292004-06-09 09:55:16 +00001452 return pColl;
1453}
1454
1455
drh8e2ca022002-06-17 17:07:19 +00001456/*
drh3f7d4e42004-07-24 14:35:58 +00001457** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001458**
1459** The schema cookie is used to determine when the schema for the
1460** database changes. After each schema change, the cookie value
1461** changes. When a process first reads the schema it records the
1462** cookie. Thereafter, whenever it goes to access the database,
1463** it checks the cookie to make sure the schema has not changed
1464** since it was last read.
1465**
1466** This plan is not completely bullet-proof. It is possible for
1467** the schema to change multiple times and for the cookie to be
1468** set back to prior value. But schema changes are infrequent
1469** and the probability of hitting the same cookie value is only
1470** 1 chance in 2^32. So we're safe enough.
1471*/
drh9cbf3422008-01-17 16:22:13 +00001472void sqlite3ChangeCookie(Parse *pParse, int iDb){
1473 int r1 = sqlite3GetTempReg(pParse);
1474 sqlite3 *db = pParse->db;
1475 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001476 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001477 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001478 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001479 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001480}
1481
1482/*
drh969fa7c2002-02-18 18:30:32 +00001483** Measure the number of characters needed to output the given
1484** identifier. The number returned includes any quotes used
1485** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001486**
1487** The estimate is conservative. It might be larger that what is
1488** really needed.
drh969fa7c2002-02-18 18:30:32 +00001489*/
1490static int identLength(const char *z){
1491 int n;
drh17f71932002-02-21 12:01:27 +00001492 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001493 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001494 }
drh234c39d2004-07-24 03:30:47 +00001495 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001496}
1497
1498/*
danielk19771b870de2009-03-14 08:37:23 +00001499** The first parameter is a pointer to an output buffer. The second
1500** parameter is a pointer to an integer that contains the offset at
1501** which to write into the output buffer. This function copies the
1502** nul-terminated string pointed to by the third parameter, zSignedIdent,
1503** to the specified offset in the buffer and updates *pIdx to refer
1504** to the first byte after the last byte written before returning.
1505**
1506** If the string zSignedIdent consists entirely of alpha-numeric
1507** characters, does not begin with a digit and is not an SQL keyword,
1508** then it is copied to the output buffer exactly as it is. Otherwise,
1509** it is quoted using double-quotes.
1510*/
drhc4a64fa2009-05-11 20:53:28 +00001511static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001512 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001513 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001514 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001515
drh17f71932002-02-21 12:01:27 +00001516 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001517 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001518 }
drhc7407522014-01-10 20:38:12 +00001519 needQuote = sqlite3Isdigit(zIdent[0])
1520 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1521 || zIdent[j]!=0
1522 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001523
drh234c39d2004-07-24 03:30:47 +00001524 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001525 for(j=0; zIdent[j]; j++){
1526 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001527 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001528 }
drh234c39d2004-07-24 03:30:47 +00001529 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001530 z[i] = 0;
1531 *pIdx = i;
1532}
1533
1534/*
1535** Generate a CREATE TABLE statement appropriate for the given
1536** table. Memory to hold the text of the statement is obtained
1537** from sqliteMalloc() and must be freed by the calling function.
1538*/
drh1d34fde2009-02-03 15:50:33 +00001539static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001540 int i, k, n;
1541 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001542 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001543 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001544 n = 0;
drh234c39d2004-07-24 03:30:47 +00001545 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001546 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001547 }
1548 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001549 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001550 zSep = "";
1551 zSep2 = ",";
1552 zEnd = ")";
1553 }else{
1554 zSep = "\n ";
1555 zSep2 = ",\n ";
1556 zEnd = "\n)";
1557 }
drhe0bc4042002-06-25 01:09:11 +00001558 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001559 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001560 if( zStmt==0 ){
1561 db->mallocFailed = 1;
1562 return 0;
1563 }
drhbdb339f2009-02-02 18:03:21 +00001564 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001565 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001566 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001567 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001568 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001569 static const char * const azType[] = {
drh05883a32015-06-02 15:32:08 +00001570 /* SQLITE_AFF_BLOB */ "",
drh7ea31cc2014-09-18 14:36:00 +00001571 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001572 /* SQLITE_AFF_NUMERIC */ " NUM",
1573 /* SQLITE_AFF_INTEGER */ " INT",
1574 /* SQLITE_AFF_REAL */ " REAL"
1575 };
1576 int len;
1577 const char *zType;
1578
drh5bb3eb92007-05-04 13:15:55 +00001579 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001580 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001581 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001582 identPut(zStmt, &k, pCol->zName);
drh05883a32015-06-02 15:32:08 +00001583 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1584 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1585 testcase( pCol->affinity==SQLITE_AFF_BLOB );
drh7ea31cc2014-09-18 14:36:00 +00001586 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001587 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1588 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1589 testcase( pCol->affinity==SQLITE_AFF_REAL );
1590
drh05883a32015-06-02 15:32:08 +00001591 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
drhc4a64fa2009-05-11 20:53:28 +00001592 len = sqlite3Strlen30(zType);
drh05883a32015-06-02 15:32:08 +00001593 assert( pCol->affinity==SQLITE_AFF_BLOB
drhfdaac672013-10-04 15:30:21 +00001594 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001595 memcpy(&zStmt[k], zType, len);
1596 k += len;
1597 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001598 }
drh5bb3eb92007-05-04 13:15:55 +00001599 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001600 return zStmt;
1601}
1602
1603/*
drh7f9c5db2013-10-23 00:32:58 +00001604** Resize an Index object to hold N columns total. Return SQLITE_OK
1605** on success and SQLITE_NOMEM on an OOM error.
1606*/
1607static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1608 char *zExtra;
1609 int nByte;
1610 if( pIdx->nColumn>=N ) return SQLITE_OK;
1611 assert( pIdx->isResized==0 );
1612 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1613 zExtra = sqlite3DbMallocZero(db, nByte);
1614 if( zExtra==0 ) return SQLITE_NOMEM;
1615 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1616 pIdx->azColl = (char**)zExtra;
1617 zExtra += sizeof(char*)*N;
1618 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1619 pIdx->aiColumn = (i16*)zExtra;
1620 zExtra += sizeof(i16)*N;
1621 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1622 pIdx->aSortOrder = (u8*)zExtra;
1623 pIdx->nColumn = N;
1624 pIdx->isResized = 1;
1625 return SQLITE_OK;
1626}
1627
1628/*
drhfdaac672013-10-04 15:30:21 +00001629** Estimate the total row width for a table.
1630*/
drhe13e9f52013-10-05 19:18:00 +00001631static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001632 unsigned wTable = 0;
1633 const Column *pTabCol;
1634 int i;
1635 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1636 wTable += pTabCol->szEst;
1637 }
1638 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001639 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001640}
1641
1642/*
drhe13e9f52013-10-05 19:18:00 +00001643** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001644*/
drhe13e9f52013-10-05 19:18:00 +00001645static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001646 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001647 int i;
1648 const Column *aCol = pIdx->pTable->aCol;
1649 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001650 i16 x = pIdx->aiColumn[i];
1651 assert( x<pIdx->pTable->nCol );
1652 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001653 }
drhe13e9f52013-10-05 19:18:00 +00001654 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001655}
1656
drh7f9c5db2013-10-23 00:32:58 +00001657/* Return true if value x is found any of the first nCol entries of aiCol[]
1658*/
1659static int hasColumn(const i16 *aiCol, int nCol, int x){
1660 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1661 return 0;
1662}
1663
1664/*
drhc6bd4e42013-11-02 14:37:18 +00001665** This routine runs at the end of parsing a CREATE TABLE statement that
1666** has a WITHOUT ROWID clause. The job of this routine is to convert both
1667** internal schema data structures and the generated VDBE code so that they
1668** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1669** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001670**
drhc6bd4e42013-11-02 14:37:18 +00001671** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1672** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1673** data storage is a covering index btree.
1674** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001675** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001676** identified by the sqlite_master table entry of the table itself.
1677** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1678** schema to the rootpage from the main table.
1679** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1680** (5) Add all table columns to the PRIMARY KEY Index object
1681** so that the PRIMARY KEY is a covering index. The surplus
1682** columns are part of KeyInfo.nXField and are not used for
1683** sorting or lookup or uniqueness checks.
1684** (6) Replace the rowid tail on all automatically generated UNIQUE
1685** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001686*/
1687static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1688 Index *pIdx;
1689 Index *pPk;
1690 int nPk;
1691 int i, j;
1692 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001693 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001694
1695 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001696 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001697 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001698 */
1699 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001700 assert( v );
drh0ff287f2015-09-02 18:40:33 +00001701 sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
drhc6bd4e42013-11-02 14:37:18 +00001702 }
1703
drh7f9c5db2013-10-23 00:32:58 +00001704 /* Locate the PRIMARY KEY index. Or, if this table was originally
1705 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1706 */
1707 if( pTab->iPKey>=0 ){
1708 ExprList *pList;
drh108aa002015-08-24 20:21:20 +00001709 Token ipkToken;
1710 ipkToken.z = pTab->aCol[pTab->iPKey].zName;
1711 ipkToken.n = sqlite3Strlen30(ipkToken.z);
1712 pList = sqlite3ExprListAppend(pParse, 0,
1713 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
drh7f9c5db2013-10-23 00:32:58 +00001714 if( pList==0 ) return;
drh7f9c5db2013-10-23 00:32:58 +00001715 pList->a[0].sortOrder = pParse->iPkSortOrder;
1716 assert( pParse->pNewTable==pTab );
1717 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1718 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001719 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001720 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001721 }else{
1722 pPk = sqlite3PrimaryKeyIndex(pTab);
danc5b73582015-05-26 11:53:14 +00001723
1724 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1725 ** table entry. This is only required if currently generating VDBE
1726 ** code for a CREATE TABLE (not when parsing one as part of reading
1727 ** a database schema). */
1728 if( v ){
1729 assert( db->init.busy==0 );
drh0ff287f2015-09-02 18:40:33 +00001730 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
danc5b73582015-05-26 11:53:14 +00001731 }
1732
drhe385d882014-12-28 22:10:51 +00001733 /*
1734 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1735 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1736 ** code assumes the PRIMARY KEY contains no repeated columns.
1737 */
1738 for(i=j=1; i<pPk->nKeyCol; i++){
1739 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
1740 pPk->nColumn--;
1741 }else{
1742 pPk->aiColumn[j++] = pPk->aiColumn[i];
1743 }
1744 }
1745 pPk->nKeyCol = j;
drh7f9c5db2013-10-23 00:32:58 +00001746 }
drh12826092013-11-05 22:39:17 +00001747 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001748 assert( pPk!=0 );
1749 nPk = pPk->nKeyCol;
1750
drh1ffede82015-01-30 20:59:27 +00001751 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
1752 ** do not enforce this for imposter tables.) */
1753 if( !db->init.imposterTable ){
1754 for(i=0; i<nPk; i++){
1755 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1756 }
1757 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001758 }
1759
drhc6bd4e42013-11-02 14:37:18 +00001760 /* The root page of the PRIMARY KEY is the table root page */
1761 pPk->tnum = pTab->tnum;
1762
drh7f9c5db2013-10-23 00:32:58 +00001763 /* Update the in-memory representation of all UNIQUE indices by converting
1764 ** the final rowid column into one or more columns of the PRIMARY KEY.
1765 */
1766 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1767 int n;
drh48dd1d82014-05-27 18:18:58 +00001768 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001769 for(i=n=0; i<nPk; i++){
1770 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1771 }
drh5a9a37b2013-11-05 17:30:04 +00001772 if( n==0 ){
1773 /* This index is a superset of the primary key */
1774 pIdx->nColumn = pIdx->nKeyCol;
1775 continue;
1776 }
drh7f9c5db2013-10-23 00:32:58 +00001777 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1778 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001779 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001780 pIdx->aiColumn[j] = pPk->aiColumn[i];
1781 pIdx->azColl[j] = pPk->azColl[i];
1782 j++;
1783 }
1784 }
drh00012df2013-11-05 01:59:07 +00001785 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1786 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001787 }
1788
1789 /* Add all table columns to the PRIMARY KEY index
1790 */
1791 if( nPk<pTab->nCol ){
1792 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1793 for(i=0, j=nPk; i<pTab->nCol; i++){
1794 if( !hasColumn(pPk->aiColumn, j, i) ){
1795 assert( j<pPk->nColumn );
1796 pPk->aiColumn[j] = i;
1797 pPk->azColl[j] = "BINARY";
1798 j++;
1799 }
1800 }
1801 assert( pPk->nColumn==j );
1802 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001803 }else{
1804 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001805 }
1806}
1807
drhfdaac672013-10-04 15:30:21 +00001808/*
drh75897232000-05-29 14:26:00 +00001809** This routine is called to report the final ")" that terminates
1810** a CREATE TABLE statement.
1811**
drhf57b3392001-10-08 13:22:32 +00001812** The table structure that other action routines have been building
1813** is added to the internal hash tables, assuming no errors have
1814** occurred.
drh75897232000-05-29 14:26:00 +00001815**
drh1d85d932004-02-14 23:05:52 +00001816** An entry for the table is made in the master table on disk, unless
1817** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001818** it means we are reading the sqlite_master table because we just
1819** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001820** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001821** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001822**
1823** If the pSelect argument is not NULL, it means that this routine
1824** was called to create a table generated from a
1825** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1826** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001827*/
danielk197719a8e7e2005-03-17 05:03:38 +00001828void sqlite3EndTable(
1829 Parse *pParse, /* Parse context */
1830 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001831 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1832 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001833 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1834){
drhfdaac672013-10-04 15:30:21 +00001835 Table *p; /* The new table */
1836 sqlite3 *db = pParse->db; /* The database connection */
1837 int iDb; /* Database in which the table lives */
1838 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001839
drh027616d2015-08-08 22:47:47 +00001840 if( pEnd==0 && pSelect==0 ){
drh5969da42013-10-21 02:14:45 +00001841 return;
danielk1977261919c2005-12-06 12:52:59 +00001842 }
drh834f9972015-08-08 23:23:33 +00001843 assert( !db->mallocFailed );
drh28037572000-08-02 13:47:41 +00001844 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001845 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001846
danielk1977517eb642004-06-07 10:00:31 +00001847 assert( !db->init.busy || !pSelect );
1848
drhc6bd4e42013-11-02 14:37:18 +00001849 /* If the db->init.busy is 1 it means we are reading the SQL off the
1850 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1851 ** So do not write to the disk again. Extract the root page number
1852 ** for the table from the db->init.newTnum field. (The page number
1853 ** should have been put there by the sqliteOpenCb routine.)
1854 */
1855 if( db->init.busy ){
1856 p->tnum = db->init.newTnum;
1857 }
1858
1859 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001860 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001861 if( (p->tabFlags & TF_Autoincrement) ){
1862 sqlite3ErrorMsg(pParse,
1863 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1864 return;
1865 }
drh5969da42013-10-21 02:14:45 +00001866 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001867 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001868 }else{
drhfccda8a2015-05-27 13:06:55 +00001869 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
drh7f9c5db2013-10-23 00:32:58 +00001870 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001871 }
1872 }
1873
drhb9bb7c12006-06-11 23:41:55 +00001874 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001875
drhffe07b22005-11-03 00:41:17 +00001876#ifndef SQLITE_OMIT_CHECK
1877 /* Resolve names in all CHECK constraint expressions.
1878 */
1879 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001880 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001881 }
1882#endif /* !defined(SQLITE_OMIT_CHECK) */
1883
drhe13e9f52013-10-05 19:18:00 +00001884 /* Estimate the average row size for the table and for all implied indices */
1885 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001886 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001887 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001888 }
1889
drhe3c41372001-09-17 20:25:58 +00001890 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001891 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001892 **
drhe0bc4042002-06-25 01:09:11 +00001893 ** If this is a TEMPORARY table, write the entry into the auxiliary
1894 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001895 */
drh1d85d932004-02-14 23:05:52 +00001896 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001897 int n;
drhd8bc7082000-06-07 23:51:50 +00001898 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001899 char *zType; /* "view" or "table" */
1900 char *zType2; /* "VIEW" or "TABLE" */
1901 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001902
danielk19774adee202004-05-08 08:23:19 +00001903 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001904 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001905
drh66a51672008-01-03 00:01:23 +00001906 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001907
drh0fa991b2009-03-21 16:19:26 +00001908 /*
1909 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001910 */
drh4ff6dfa2002-03-03 23:06:00 +00001911 if( p->pSelect==0 ){
1912 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001913 zType = "table";
1914 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001915#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001916 }else{
1917 /* A view */
drh4794f732004-11-05 17:17:50 +00001918 zType = "view";
1919 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001920#endif
drh4ff6dfa2002-03-03 23:06:00 +00001921 }
danielk1977517eb642004-06-07 10:00:31 +00001922
danielk1977517eb642004-06-07 10:00:31 +00001923 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1924 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001925 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001926 **
1927 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1928 ** suitable state to query for the column names and types to be used
1929 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001930 **
1931 ** A shared-cache write-lock is not required to write to the new table,
1932 ** as a schema-lock must have already been obtained to create it. Since
1933 ** a schema-lock excludes all other database users, the write-lock would
1934 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001935 */
1936 if( pSelect ){
drh92632202015-05-20 17:18:29 +00001937 SelectDest dest; /* Where the SELECT should store results */
drh9df25c42015-05-20 15:51:09 +00001938 int regYield; /* Register holding co-routine entry-point */
1939 int addrTop; /* Top of the co-routine */
drh92632202015-05-20 17:18:29 +00001940 int regRec; /* A record to be insert into the new table */
1941 int regRowid; /* Rowid of the next row to insert */
1942 int addrInsLoop; /* Top of the loop for inserting rows */
1943 Table *pSelTab; /* A table that describes the SELECT results */
drh1013c932008-01-06 00:25:21 +00001944
drh9df25c42015-05-20 15:51:09 +00001945 regYield = ++pParse->nMem;
drh92632202015-05-20 17:18:29 +00001946 regRec = ++pParse->nMem;
1947 regRowid = ++pParse->nMem;
danielk19776ab3a2e2009-02-19 14:39:25 +00001948 assert(pParse->nTab==1);
drh0dd5cda2015-06-16 16:39:01 +00001949 sqlite3MayAbort(pParse);
drhb7654112008-01-12 12:48:07 +00001950 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001951 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001952 pParse->nTab = 2;
drh9df25c42015-05-20 15:51:09 +00001953 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1954 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1955 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
drh7d10d5a2008-08-20 16:35:10 +00001956 sqlite3Select(pParse, pSelect, &dest);
drh9df25c42015-05-20 15:51:09 +00001957 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
1958 sqlite3VdbeJumpHere(v, addrTop - 1);
drh92632202015-05-20 17:18:29 +00001959 if( pParse->nErr ) return;
1960 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1961 if( pSelTab==0 ) return;
1962 assert( p->aCol==0 );
1963 p->nCol = pSelTab->nCol;
1964 p->aCol = pSelTab->aCol;
1965 pSelTab->nCol = 0;
1966 pSelTab->aCol = 0;
1967 sqlite3DeleteTable(db, pSelTab);
1968 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1969 VdbeCoverage(v);
1970 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
1971 sqlite3TableAffinity(v, p, 0);
1972 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
1973 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
drh076e85f2015-09-03 13:46:12 +00001974 sqlite3VdbeGoto(v, addrInsLoop);
drh92632202015-05-20 17:18:29 +00001975 sqlite3VdbeJumpHere(v, addrInsLoop);
1976 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001977 }
drh4794f732004-11-05 17:17:50 +00001978
drh4794f732004-11-05 17:17:50 +00001979 /* Compute the complete text of the CREATE statement */
1980 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001981 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001982 }else{
drh8ea30bf2013-10-22 01:18:17 +00001983 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1984 n = (int)(pEnd2->z - pParse->sNameToken.z);
1985 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001986 zStmt = sqlite3MPrintf(db,
1987 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1988 );
drh4794f732004-11-05 17:17:50 +00001989 }
1990
1991 /* A slot for the record has already been allocated in the
1992 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001993 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001994 */
1995 sqlite3NestedParse(pParse,
1996 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001997 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1998 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001999 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00002000 zType,
2001 p->zName,
2002 p->zName,
drhb7654112008-01-12 12:48:07 +00002003 pParse->regRoot,
2004 zStmt,
2005 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00002006 );
drh633e6d52008-07-28 19:34:53 +00002007 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00002008 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00002009
2010#ifndef SQLITE_OMIT_AUTOINCREMENT
2011 /* Check to see if we need to create an sqlite_sequence table for
2012 ** keeping track of autoincrement keys.
2013 */
drh7d10d5a2008-08-20 16:35:10 +00002014 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00002015 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00002016 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00002017 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00002018 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00002019 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2020 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00002021 );
2022 }
2023 }
2024#endif
drh4794f732004-11-05 17:17:50 +00002025
2026 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00002027 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00002028 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00002029 }
drh17e9e292003-02-01 13:53:28 +00002030
drh2958a4e2004-11-12 03:56:15 +00002031
drh17e9e292003-02-01 13:53:28 +00002032 /* Add the table to the in-memory representation of the database.
2033 */
drh8af73d42009-05-13 22:58:28 +00002034 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00002035 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00002036 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00002037 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00002038 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00002039 if( pOld ){
2040 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00002041 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00002042 return;
drh17e9e292003-02-01 13:53:28 +00002043 }
drh17e9e292003-02-01 13:53:28 +00002044 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00002045 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00002046
2047#ifndef SQLITE_OMIT_ALTERTABLE
2048 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00002049 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00002050 int nName;
drh5969da42013-10-21 02:14:45 +00002051 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00002052 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002053 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002054 }
drh1bd10f82008-12-10 21:19:56 +00002055 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002056 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002057 }
2058#endif
drh17e9e292003-02-01 13:53:28 +00002059 }
drh75897232000-05-29 14:26:00 +00002060}
2061
drhb7f91642004-10-31 02:22:47 +00002062#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002063/*
drha76b5df2002-02-23 02:32:10 +00002064** The parser calls this routine in order to create a new VIEW
2065*/
danielk19774adee202004-05-08 08:23:19 +00002066void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002067 Parse *pParse, /* The parsing context */
2068 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002069 Token *pName1, /* The token that holds the name of the view */
2070 Token *pName2, /* The token that holds the name of the view */
drh8981b902015-08-24 17:42:49 +00002071 ExprList *pCNames, /* Optional list of view column names */
drh6276c1c2002-07-08 22:03:32 +00002072 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002073 int isTemp, /* TRUE for a TEMPORARY view */
2074 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002075){
drha76b5df2002-02-23 02:32:10 +00002076 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002077 int n;
drhb7916a72009-05-27 10:31:29 +00002078 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002079 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002080 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002081 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002082 int iDb;
drh17435752007-08-16 04:30:38 +00002083 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002084
drh7c3d64f2005-06-06 15:32:08 +00002085 if( pParse->nVar>0 ){
2086 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh32498f12015-09-26 11:15:44 +00002087 goto create_view_fail;
drh7c3d64f2005-06-06 15:32:08 +00002088 }
drhfdd48a72006-09-11 23:45:48 +00002089 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002090 p = pParse->pNewTable;
drh8981b902015-08-24 17:42:49 +00002091 if( p==0 || pParse->nErr ) goto create_view_fail;
danielk1977ef2cb632004-05-29 02:37:19 +00002092 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002093 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002094 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
drh8981b902015-08-24 17:42:49 +00002095 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
drh174b6192002-12-03 02:22:52 +00002096
drh4b59ab52002-08-24 18:24:51 +00002097 /* Make a copy of the entire SELECT statement that defines the view.
2098 ** This will force all the Expr.token.z values to be dynamically
2099 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002100 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002101 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002102 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh8981b902015-08-24 17:42:49 +00002103 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2104 if( db->mallocFailed ) goto create_view_fail;
drh4b59ab52002-08-24 18:24:51 +00002105
2106 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2107 ** the end.
2108 */
drha76b5df2002-02-23 02:32:10 +00002109 sEnd = pParse->sLastToken;
drh8981b902015-08-24 17:42:49 +00002110 assert( sEnd.z[0]!=0 );
2111 if( sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002112 sEnd.z += sEnd.n;
2113 }
2114 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002115 n = (int)(sEnd.z - pBegin->z);
drh8981b902015-08-24 17:42:49 +00002116 assert( n>0 );
drhb7916a72009-05-27 10:31:29 +00002117 z = pBegin->z;
drh8981b902015-08-24 17:42:49 +00002118 while( sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002119 sEnd.z = &z[n-1];
2120 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002121
danielk19774adee202004-05-08 08:23:19 +00002122 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002123 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drh8981b902015-08-24 17:42:49 +00002124
2125create_view_fail:
2126 sqlite3SelectDelete(db, pSelect);
2127 sqlite3ExprListDelete(db, pCNames);
drha76b5df2002-02-23 02:32:10 +00002128 return;
drh417be792002-03-03 18:59:40 +00002129}
drhb7f91642004-10-31 02:22:47 +00002130#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002131
danielk1977fe3fcbe22006-06-12 12:08:45 +00002132#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002133/*
2134** The Table structure pTable is really a VIEW. Fill in the names of
2135** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002136** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002137*/
danielk19774adee202004-05-08 08:23:19 +00002138int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002139 Table *pSelTab; /* A fake table from which we get the result set */
2140 Select *pSel; /* Copy of the SELECT that implements the view */
2141 int nErr = 0; /* Number of errors encountered */
2142 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002143 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002144 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh8981b902015-08-24 17:42:49 +00002145 u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */
drh417be792002-03-03 18:59:40 +00002146
2147 assert( pTable );
2148
danielk1977fe3fcbe22006-06-12 12:08:45 +00002149#ifndef SQLITE_OMIT_VIRTUALTABLE
2150 if( sqlite3VtabCallConnect(pParse, pTable) ){
2151 return SQLITE_ERROR;
2152 }
drh4cbdda92006-06-14 19:00:20 +00002153 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002154#endif
2155
2156#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002157 /* A positive nCol means the columns names for this view are
2158 ** already known.
2159 */
2160 if( pTable->nCol>0 ) return 0;
2161
2162 /* A negative nCol is a special marker meaning that we are currently
2163 ** trying to compute the column names. If we enter this routine with
2164 ** a negative nCol, it means two or more views form a loop, like this:
2165 **
2166 ** CREATE VIEW one AS SELECT * FROM two;
2167 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002168 **
drh768578e2009-05-12 00:40:12 +00002169 ** Actually, the error above is now caught prior to reaching this point.
2170 ** But the following test is still important as it does come up
2171 ** in the following:
2172 **
2173 ** CREATE TABLE main.ex1(a);
2174 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2175 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002176 */
2177 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002178 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002179 return 1;
2180 }
drh85c23c62005-08-20 03:03:04 +00002181 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002182
2183 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002184 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2185 ** "*" elements in the results set of the view and will assign cursors
2186 ** to the elements of the FROM clause. But we do not want these changes
2187 ** to be permanent. So the computation is done on a copy of the SELECT
2188 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002189 */
drh9b3187e2005-01-18 14:45:47 +00002190 assert( pTable->pSelect );
drh8981b902015-08-24 17:42:49 +00002191 bEnabledLA = db->lookaside.bEnabled;
2192 if( pTable->pCheck ){
drhd9da78a2009-03-24 15:08:09 +00002193 db->lookaside.bEnabled = 0;
drh8981b902015-08-24 17:42:49 +00002194 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2195 &pTable->nCol, &pTable->aCol);
2196 }else{
2197 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2198 if( pSel ){
2199 n = pParse->nTab;
2200 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2201 pTable->nCol = -1;
2202 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002203#ifndef SQLITE_OMIT_AUTHORIZATION
drh8981b902015-08-24 17:42:49 +00002204 xAuth = db->xAuth;
2205 db->xAuth = 0;
2206 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2207 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002208#else
drh8981b902015-08-24 17:42:49 +00002209 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002210#endif
drh8981b902015-08-24 17:42:49 +00002211 pParse->nTab = n;
2212 if( pSelTab ){
2213 assert( pTable->aCol==0 );
2214 pTable->nCol = pSelTab->nCol;
2215 pTable->aCol = pSelTab->aCol;
2216 pSelTab->nCol = 0;
2217 pSelTab->aCol = 0;
2218 sqlite3DeleteTable(db, pSelTab);
2219 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2220 }else{
2221 pTable->nCol = 0;
2222 nErr++;
2223 }
2224 sqlite3SelectDelete(db, pSel);
2225 } else {
danielk1977261919c2005-12-06 12:52:59 +00002226 nErr++;
2227 }
drh417be792002-03-03 18:59:40 +00002228 }
drh8981b902015-08-24 17:42:49 +00002229 db->lookaside.bEnabled = bEnabledLA;
2230 pTable->pSchema->schemaFlags |= DB_UnresetViews;
drhb7f91642004-10-31 02:22:47 +00002231#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002232 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002233}
2234#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002235
drhb7f91642004-10-31 02:22:47 +00002236#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002237/*
drh8bf8dc92003-05-17 17:35:10 +00002238** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002239*/
drh9bb575f2004-09-06 17:24:11 +00002240static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002241 HashElem *i;
drh21206082011-04-04 18:22:02 +00002242 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002243 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002244 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002245 Table *pTab = sqliteHashData(i);
2246 if( pTab->pSelect ){
drh51be3872015-08-19 02:32:25 +00002247 sqlite3DeleteColumnNames(db, pTab);
dand46def72010-07-24 11:28:28 +00002248 pTab->aCol = 0;
2249 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002250 }
2251 }
drh8bf8dc92003-05-17 17:35:10 +00002252 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002253}
drhb7f91642004-10-31 02:22:47 +00002254#else
2255# define sqliteViewResetAll(A,B)
2256#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002257
drh75897232000-05-29 14:26:00 +00002258/*
danielk1977a0bf2652004-11-04 14:30:04 +00002259** This function is called by the VDBE to adjust the internal schema
2260** used by SQLite when the btree layer moves a table root page. The
2261** root-page of a table or index in database iDb has changed from iFrom
2262** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002263**
2264** Ticket #1728: The symbol table might still contain information
2265** on tables and/or indices that are the process of being deleted.
2266** If you are unlucky, one of those deleted indices or tables might
2267** have the same rootpage number as the real table or index that is
2268** being moved. So we cannot stop searching after the first match
2269** because the first match might be for one of the deleted indices
2270** or tables and not the table/index that is actually being moved.
2271** We must continue looping until all tables and indices with
2272** rootpage==iFrom have been converted to have a rootpage of iTo
2273** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002274*/
2275#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002276void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002277 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002278 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002279 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002280
drhcdf011d2011-04-04 21:25:28 +00002281 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2282 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002283 pHash = &pDb->pSchema->tblHash;
2284 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002285 Table *pTab = sqliteHashData(pElem);
2286 if( pTab->tnum==iFrom ){
2287 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002288 }
2289 }
danielk1977da184232006-01-05 11:34:32 +00002290 pHash = &pDb->pSchema->idxHash;
2291 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002292 Index *pIdx = sqliteHashData(pElem);
2293 if( pIdx->tnum==iFrom ){
2294 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002295 }
2296 }
danielk1977a0bf2652004-11-04 14:30:04 +00002297}
2298#endif
2299
2300/*
2301** Write code to erase the table with root-page iTable from database iDb.
2302** Also write code to modify the sqlite_master table and internal schema
2303** if a root-page of another table is moved by the btree-layer whilst
2304** erasing iTable (this can happen with an auto-vacuum database).
2305*/
drh4e0cff62004-11-05 05:10:28 +00002306static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2307 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002308 int r1 = sqlite3GetTempReg(pParse);
2309 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002310 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002311#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002312 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002313 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002314 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002315 ** reflect this.
2316 **
drh0fa991b2009-03-21 16:19:26 +00002317 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002318 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2319 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002320 */
danielk197763e3e9f2004-11-05 09:19:27 +00002321 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002322 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2323 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002324#endif
drhb7654112008-01-12 12:48:07 +00002325 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002326}
2327
2328/*
2329** Write VDBE code to erase table pTab and all associated indices on disk.
2330** Code to update the sqlite_master tables and internal schema definitions
2331** in case a root-page belonging to another table is moved by the btree layer
2332** is also added (this can happen with an auto-vacuum database).
2333*/
drh4e0cff62004-11-05 05:10:28 +00002334static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002335#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002336 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002337 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2338 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002339 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002340 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002341 }
2342#else
2343 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2344 ** is not defined), then it is important to call OP_Destroy on the
2345 ** table and index root-pages in order, starting with the numerically
2346 ** largest root-page number. This guarantees that none of the root-pages
2347 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2348 ** following were coded:
2349 **
2350 ** OP_Destroy 4 0
2351 ** ...
2352 ** OP_Destroy 5 0
2353 **
2354 ** and root page 5 happened to be the largest root-page number in the
2355 ** database, then root page 5 would be moved to page 4 by the
2356 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2357 ** a free-list page.
2358 */
2359 int iTab = pTab->tnum;
2360 int iDestroyed = 0;
2361
2362 while( 1 ){
2363 Index *pIdx;
2364 int iLargest = 0;
2365
2366 if( iDestroyed==0 || iTab<iDestroyed ){
2367 iLargest = iTab;
2368 }
2369 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2370 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002371 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002372 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2373 iLargest = iIdx;
2374 }
2375 }
danielk1977da184232006-01-05 11:34:32 +00002376 if( iLargest==0 ){
2377 return;
2378 }else{
2379 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002380 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002381 destroyRootPage(pParse, iLargest, iDb);
2382 iDestroyed = iLargest;
2383 }
danielk1977a0bf2652004-11-04 14:30:04 +00002384 }
2385#endif
2386}
2387
2388/*
drh74e7c8f2011-10-21 19:06:32 +00002389** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002390** after a DROP INDEX or DROP TABLE command.
2391*/
2392static void sqlite3ClearStatTables(
2393 Parse *pParse, /* The parsing context */
2394 int iDb, /* The database number */
2395 const char *zType, /* "idx" or "tbl" */
2396 const char *zName /* Name of index or table */
2397){
drha5ae4c32011-08-07 01:31:52 +00002398 int i;
2399 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002400 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002401 char zTab[24];
2402 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2403 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002404 sqlite3NestedParse(pParse,
2405 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002406 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002407 );
2408 }
2409 }
2410}
2411
2412/*
drhfaacf172011-08-12 01:51:45 +00002413** Generate code to drop a table.
2414*/
2415void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2416 Vdbe *v;
2417 sqlite3 *db = pParse->db;
2418 Trigger *pTrigger;
2419 Db *pDb = &db->aDb[iDb];
2420
2421 v = sqlite3GetVdbe(pParse);
2422 assert( v!=0 );
2423 sqlite3BeginWriteOperation(pParse, 1, iDb);
2424
2425#ifndef SQLITE_OMIT_VIRTUALTABLE
2426 if( IsVirtual(pTab) ){
2427 sqlite3VdbeAddOp0(v, OP_VBegin);
2428 }
2429#endif
2430
2431 /* Drop all triggers associated with the table being dropped. Code
2432 ** is generated to remove entries from sqlite_master and/or
2433 ** sqlite_temp_master if required.
2434 */
2435 pTrigger = sqlite3TriggerList(pParse, pTab);
2436 while( pTrigger ){
2437 assert( pTrigger->pSchema==pTab->pSchema ||
2438 pTrigger->pSchema==db->aDb[1].pSchema );
2439 sqlite3DropTriggerPtr(pParse, pTrigger);
2440 pTrigger = pTrigger->pNext;
2441 }
2442
2443#ifndef SQLITE_OMIT_AUTOINCREMENT
2444 /* Remove any entries of the sqlite_sequence table associated with
2445 ** the table being dropped. This is done before the table is dropped
2446 ** at the btree level, in case the sqlite_sequence table needs to
2447 ** move as a result of the drop (can happen in auto-vacuum mode).
2448 */
2449 if( pTab->tabFlags & TF_Autoincrement ){
2450 sqlite3NestedParse(pParse,
2451 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2452 pDb->zName, pTab->zName
2453 );
2454 }
2455#endif
2456
2457 /* Drop all SQLITE_MASTER table and index entries that refer to the
2458 ** table. The program name loops through the master table and deletes
2459 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002460 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002461 ** created in the temp database that refers to a table in another
2462 ** database.
2463 */
2464 sqlite3NestedParse(pParse,
2465 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2466 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002467 if( !isView && !IsVirtual(pTab) ){
2468 destroyTable(pParse, pTab);
2469 }
2470
2471 /* Remove the table entry from SQLite's internal schema and modify
2472 ** the schema cookie.
2473 */
2474 if( IsVirtual(pTab) ){
2475 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2476 }
2477 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2478 sqlite3ChangeCookie(pParse, iDb);
2479 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002480}
2481
2482/*
drh75897232000-05-29 14:26:00 +00002483** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002484** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002485*/
drha0733842005-12-29 01:11:36 +00002486void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002487 Table *pTab;
drh75897232000-05-29 14:26:00 +00002488 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002489 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002490 int iDb;
drh75897232000-05-29 14:26:00 +00002491
drh8af73d42009-05-13 22:58:28 +00002492 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002493 goto exit_drop_table;
2494 }
drh8af73d42009-05-13 22:58:28 +00002495 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002496 assert( pName->nSrc==1 );
drh75209962015-04-19 22:31:45 +00002497 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
drha7564662010-02-22 19:32:31 +00002498 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002499 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002500 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002501
drha0733842005-12-29 01:11:36 +00002502 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002503 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002504 goto exit_drop_table;
2505 }
danielk1977da184232006-01-05 11:34:32 +00002506 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002507 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002508
2509 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2510 ** it is initialized.
2511 */
2512 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2513 goto exit_drop_table;
2514 }
drhe5f9c642003-01-13 23:27:31 +00002515#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002516 {
2517 int code;
danielk1977da184232006-01-05 11:34:32 +00002518 const char *zTab = SCHEMA_TABLE(iDb);
2519 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002520 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002521 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002522 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002523 }
drhe5f9c642003-01-13 23:27:31 +00002524 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002525 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002526 code = SQLITE_DROP_TEMP_VIEW;
2527 }else{
2528 code = SQLITE_DROP_VIEW;
2529 }
danielk19774b2688a2006-06-20 11:01:07 +00002530#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002531 }else if( IsVirtual(pTab) ){
2532 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002533 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002534#endif
drhe5f9c642003-01-13 23:27:31 +00002535 }else{
danielk197753c0f742005-03-29 03:10:59 +00002536 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002537 code = SQLITE_DROP_TEMP_TABLE;
2538 }else{
2539 code = SQLITE_DROP_TABLE;
2540 }
2541 }
danielk1977f1a381e2006-06-16 08:01:02 +00002542 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002543 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002544 }
danielk1977a8858102004-05-28 12:11:21 +00002545 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2546 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002547 }
drhe5f9c642003-01-13 23:27:31 +00002548 }
2549#endif
drh08ccfaa2011-10-07 23:52:25 +00002550 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2551 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002552 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002553 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002554 }
danielk1977576ec6b2005-01-21 11:55:25 +00002555
2556#ifndef SQLITE_OMIT_VIEW
2557 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2558 ** on a table.
2559 */
danielk1977a8858102004-05-28 12:11:21 +00002560 if( isView && pTab->pSelect==0 ){
2561 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2562 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002563 }
danielk1977a8858102004-05-28 12:11:21 +00002564 if( !isView && pTab->pSelect ){
2565 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2566 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002567 }
danielk1977576ec6b2005-01-21 11:55:25 +00002568#endif
drh75897232000-05-29 14:26:00 +00002569
drh1ccde152000-06-17 13:12:39 +00002570 /* Generate code to remove the table from the master table
2571 ** on disk.
2572 */
danielk19774adee202004-05-08 08:23:19 +00002573 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002574 if( v ){
drh77658e22007-12-04 16:54:52 +00002575 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002576 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002577 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002578 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002579 }
danielk1977a8858102004-05-28 12:11:21 +00002580
2581exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002582 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002583}
2584
2585/*
drhc2eef3b2002-08-31 18:53:06 +00002586** This routine is called to create a new foreign key on the table
2587** currently under construction. pFromCol determines which columns
2588** in the current table point to the foreign key. If pFromCol==0 then
2589** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002590** the table referred to (a.k.a the "parent" table). pToCol is a list
2591** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002592** information about the conflict resolution algorithms specified
2593** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2594**
2595** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002596** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002597**
2598** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002599** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002600*/
danielk19774adee202004-05-08 08:23:19 +00002601void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002602 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002603 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002604 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002605 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002606 int flags /* Conflict resolution algorithms. */
2607){
danielk197718576932008-08-06 13:47:40 +00002608 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002609#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002610 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002611 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002612 Table *p = pParse->pNewTable;
2613 int nByte;
2614 int i;
2615 int nCol;
2616 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002617
2618 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002619 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002620 if( pFromCol==0 ){
2621 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002622 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002623 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002624 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002625 " should reference only one column of table %T",
2626 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002627 goto fk_end;
2628 }
2629 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002630 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002631 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002632 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002633 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002634 goto fk_end;
2635 }else{
danielk19770202b292004-06-09 09:55:16 +00002636 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002637 }
drhe61922a2009-05-02 13:29:37 +00002638 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002639 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002640 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002641 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002642 }
2643 }
drh633e6d52008-07-28 19:34:53 +00002644 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002645 if( pFKey==0 ){
2646 goto fk_end;
2647 }
drhc2eef3b2002-08-31 18:53:06 +00002648 pFKey->pFrom = p;
2649 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002650 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002651 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002652 memcpy(z, pTo->z, pTo->n);
2653 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002654 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002655 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002656 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002657 if( pFromCol==0 ){
2658 pFKey->aCol[0].iFrom = p->nCol-1;
2659 }else{
2660 for(i=0; i<nCol; i++){
2661 int j;
2662 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002663 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002664 pFKey->aCol[i].iFrom = j;
2665 break;
2666 }
2667 }
2668 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002669 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002670 "unknown column \"%s\" in foreign key definition",
2671 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002672 goto fk_end;
2673 }
2674 }
2675 }
2676 if( pToCol ){
2677 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002678 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002679 pFKey->aCol[i].zCol = z;
2680 memcpy(z, pToCol->a[i].zName, n);
2681 z[n] = 0;
2682 z += n+1;
2683 }
2684 }
2685 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002686 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2687 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002688
drh21206082011-04-04 18:22:02 +00002689 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002690 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002691 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002692 );
danf59c5ca2009-09-22 16:55:38 +00002693 if( pNextTo==pFKey ){
2694 db->mallocFailed = 1;
2695 goto fk_end;
2696 }
dan1da40a32009-09-19 17:00:31 +00002697 if( pNextTo ){
2698 assert( pNextTo->pPrevTo==0 );
2699 pFKey->pNextTo = pNextTo;
2700 pNextTo->pPrevTo = pFKey;
2701 }
2702
drhc2eef3b2002-08-31 18:53:06 +00002703 /* Link the foreign key to the table as the last step.
2704 */
2705 p->pFKey = pFKey;
2706 pFKey = 0;
2707
2708fk_end:
drh633e6d52008-07-28 19:34:53 +00002709 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002710#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002711 sqlite3ExprListDelete(db, pFromCol);
2712 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002713}
2714
2715/*
2716** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2717** clause is seen as part of a foreign key definition. The isDeferred
2718** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2719** The behavior of the most recently created foreign key is adjusted
2720** accordingly.
2721*/
danielk19774adee202004-05-08 08:23:19 +00002722void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002723#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002724 Table *pTab;
2725 FKey *pFKey;
2726 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002727 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002728 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002729#endif
drhc2eef3b2002-08-31 18:53:06 +00002730}
2731
2732/*
drh063336a2004-11-05 20:58:39 +00002733** Generate code that will erase and refill index *pIdx. This is
2734** used to initialize a newly created index or to recompute the
2735** content of an index in response to a REINDEX command.
2736**
2737** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002738** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002739** root page number of the index. If memRootPage is negative, then
2740** the index already exists and must be cleared before being refilled and
2741** the root page number of the index is taken from pIndex->tnum.
2742*/
2743static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2744 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002745 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2746 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002747 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002748 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002749 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002750 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002751 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002752 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002753 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002754 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002755 sqlite3 *db = pParse->db; /* The database connection */
2756 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002757
danielk19771d54df82004-11-23 15:41:16 +00002758#ifndef SQLITE_OMIT_AUTHORIZATION
2759 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002760 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002761 return;
2762 }
2763#endif
2764
danielk1977c00da102006-01-07 13:21:04 +00002765 /* Require a write-lock on the table to perform this operation */
2766 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2767
drh063336a2004-11-05 20:58:39 +00002768 v = sqlite3GetVdbe(pParse);
2769 if( v==0 ) return;
2770 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002771 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002772 }else{
2773 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002774 }
drh2ec2fb22013-11-06 19:59:23 +00002775 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002776
dan689ab892011-08-12 15:02:00 +00002777 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002778 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002779 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002780 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002781
2782 /* Open the table. Loop through all rows of the table, inserting index
2783 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002784 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002785 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002786 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002787
drh1c2c0b72014-01-04 19:27:05 +00002788 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002789 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002790 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002791 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002792 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002793 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2794 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002795 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002796 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2797
drh688852a2014-02-17 22:40:43 +00002798 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002799 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002800 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002801 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
drh076e85f2015-09-03 13:46:12 +00002802 sqlite3VdbeGoto(v, j2);
drhca892a72011-09-03 00:17:51 +00002803 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002804 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002805 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002806 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002807 }else{
2808 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002809 }
drh6cf4a7d2014-10-13 13:00:58 +00002810 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
danb18e60b2015-04-01 16:18:00 +00002811 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
2812 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
drhca892a72011-09-03 00:17:51 +00002813 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002814 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002815 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002816 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002817
drh66a51672008-01-03 00:01:23 +00002818 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2819 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002820 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002821}
2822
2823/*
drh77e57df2013-10-22 14:28:02 +00002824** Allocate heap space to hold an Index object with nCol columns.
2825**
2826** Increase the allocation size to provide an extra nExtra bytes
2827** of 8-byte aligned space after the Index object and return a
2828** pointer to this extra space in *ppExtra.
2829*/
2830Index *sqlite3AllocateIndexObject(
2831 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002832 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002833 int nExtra, /* Number of bytes of extra space to alloc */
2834 char **ppExtra /* Pointer to the "extra" space */
2835){
2836 Index *p; /* Allocated index object */
2837 int nByte; /* Bytes of space for Index object + arrays */
2838
2839 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2840 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002841 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002842 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002843 sizeof(u8)*nCol); /* Index.aSortOrder */
2844 p = sqlite3DbMallocZero(db, nByte + nExtra);
2845 if( p ){
2846 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002847 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2848 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2849 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002850 p->aSortOrder = (u8*)pExtra;
2851 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002852 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002853 *ppExtra = ((char*)p) + nByte;
2854 }
2855 return p;
2856}
2857
2858/*
drhedb04ed2015-09-04 12:54:01 +00002859** Backwards Compatibility Hack:
2860**
2861** Historical versions of SQLite accepted strings as column names in
2862** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
2863**
2864** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
2865** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
2866**
2867** This is goofy. But to preserve backwards compatibility we continue to
2868** accept it. This routine does the necessary conversion. It converts
2869** the expression given in its argument from a TK_STRING into a TK_ID
2870** if the expression is just a TK_STRING with an optional COLLATE clause.
2871** If the epxression is anything other than TK_STRING, the expression is
2872** unchanged.
2873*/
2874static void sqlite3StringToId(Expr *p){
2875 if( p->op==TK_STRING ){
2876 p->op = TK_ID;
2877 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
2878 p->pLeft->op = TK_ID;
2879 }
2880}
2881
2882/*
drh23bf66d2004-12-14 03:34:34 +00002883** Create a new index for an SQL table. pName1.pName2 is the name of the index
2884** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002885** be NULL for a primary key or an index that is created to satisfy a
2886** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002887** as the table to be indexed. pParse->pNewTable is a table that is
2888** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002889**
drh382c0242001-10-06 16:33:02 +00002890** pList is a list of columns to be indexed. pList will be NULL if this
2891** is a primary key or unique-constraint on the most recent column added
2892** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002893**
2894** If the index is created successfully, return a pointer to the new Index
2895** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002896** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002897*/
dan1da40a32009-09-19 17:00:31 +00002898Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002899 Parse *pParse, /* All information about this parse */
2900 Token *pName1, /* First part of index name. May be NULL */
2901 Token *pName2, /* Second part of index name. May be NULL */
2902 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002903 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002904 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002905 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002906 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002907 int sortOrder, /* Sort order of primary key when pList==NULL */
2908 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002909){
dan1da40a32009-09-19 17:00:31 +00002910 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002911 Table *pTab = 0; /* Table to be indexed */
2912 Index *pIndex = 0; /* The index to be created */
2913 char *zName = 0; /* Name of the index */
2914 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002915 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002916 DbFixer sFix; /* For assigning database names to pTable */
2917 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002918 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002919 Db *pDb; /* The specific table containing the indexed database */
2920 int iDb; /* Index of the database that is being written */
2921 Token *pName = 0; /* Unqualified name of the index to create */
2922 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002923 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002924 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002925 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002926 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002927
drh7088d502015-04-18 17:43:29 +00002928 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
drhd3001712009-05-12 17:46:53 +00002929 goto exit_create_index;
2930 }
2931 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002932 goto exit_create_index;
2933 }
drhdaffd0e2001-04-11 14:28:42 +00002934
drh75897232000-05-29 14:26:00 +00002935 /*
2936 ** Find the table that is to be indexed. Return early if not found.
2937 */
danielk1977cbb18d22004-05-28 11:37:27 +00002938 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002939
2940 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002941 ** to search for the table. 'Fix' the table name to this db
2942 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002943 */
2944 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002945 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002946 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002947 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002948
danielk197753c0f742005-03-29 03:10:59 +00002949#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002950 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002951 ** is a temp table. If so, set the database to 1. Do not do this
2952 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002953 */
danielk1977fe910332007-12-02 11:46:34 +00002954 if( !db->init.busy ){
2955 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002956 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002957 iDb = 1;
2958 }
danielk1977ef2cb632004-05-29 02:37:19 +00002959 }
danielk197753c0f742005-03-29 03:10:59 +00002960#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002961
drhd100f692013-10-03 15:39:44 +00002962 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2963 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002964 /* Because the parser constructs pTblName from a single identifier,
2965 ** sqlite3FixSrcList can never fail. */
2966 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002967 }
dan41fb5cd2012-10-04 19:33:00 +00002968 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002969 assert( db->mallocFailed==0 || pTab==0 );
2970 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002971 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2972 sqlite3ErrorMsg(pParse,
2973 "cannot create a TEMP index on non-TEMP table \"%s\"",
2974 pTab->zName);
2975 goto exit_create_index;
2976 }
drh44156282013-10-23 22:23:03 +00002977 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002978 }else{
drhe3c41372001-09-17 20:25:58 +00002979 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002980 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002981 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002982 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002983 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002984 }
drhfdd6e852005-12-16 01:06:16 +00002985 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002986
drhd3001712009-05-12 17:46:53 +00002987 assert( pTab!=0 );
2988 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002989 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002990 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002991#if SQLITE_USER_AUTHENTICATION
2992 && sqlite3UserAuthTable(pTab->zName)==0
2993#endif
drh503a6862013-03-01 01:07:17 +00002994 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002995 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002996 goto exit_create_index;
2997 }
danielk1977576ec6b2005-01-21 11:55:25 +00002998#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002999 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00003000 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00003001 goto exit_create_index;
3002 }
danielk1977576ec6b2005-01-21 11:55:25 +00003003#endif
danielk19775ee9d692006-06-21 12:36:25 +00003004#ifndef SQLITE_OMIT_VIRTUALTABLE
3005 if( IsVirtual(pTab) ){
3006 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
3007 goto exit_create_index;
3008 }
3009#endif
drh75897232000-05-29 14:26:00 +00003010
3011 /*
3012 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00003013 ** index or table with the same name.
3014 **
3015 ** Exception: If we are reading the names of permanent indices from the
3016 ** sqlite_master table (because some other process changed the schema) and
3017 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00003018 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00003019 **
3020 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00003021 ** dealing with a primary key or UNIQUE constraint. We have to invent our
3022 ** own name.
drh75897232000-05-29 14:26:00 +00003023 */
danielk1977d8123362004-06-12 09:25:12 +00003024 if( pName ){
drh17435752007-08-16 04:30:38 +00003025 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00003026 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00003027 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00003028 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00003029 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00003030 }
danielk1977d8123362004-06-12 09:25:12 +00003031 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00003032 if( sqlite3FindTable(db, zName, 0)!=0 ){
3033 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3034 goto exit_create_index;
3035 }
3036 }
danielk197759a33f92007-03-17 10:26:59 +00003037 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
3038 if( !ifNotExist ){
3039 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00003040 }else{
3041 assert( !db->init.busy );
3042 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00003043 }
danielk197759a33f92007-03-17 10:26:59 +00003044 goto exit_create_index;
3045 }
danielk1977a21c6b62005-01-24 10:25:59 +00003046 }else{
drhadbca9c2001-09-27 15:11:53 +00003047 int n;
3048 Index *pLoop;
3049 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00003050 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00003051 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00003052 goto exit_create_index;
3053 }
drh75897232000-05-29 14:26:00 +00003054 }
3055
drhe5f9c642003-01-13 23:27:31 +00003056 /* Check for authorization to create an index.
3057 */
3058#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00003059 {
drhfdd6e852005-12-16 01:06:16 +00003060 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00003061 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003062 goto exit_create_index;
3063 }
3064 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00003065 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003066 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003067 goto exit_create_index;
3068 }
drhe5f9c642003-01-13 23:27:31 +00003069 }
3070#endif
3071
drh75897232000-05-29 14:26:00 +00003072 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00003073 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00003074 ** So create a fake list to simulate this.
3075 */
3076 if( pList==0 ){
drh108aa002015-08-24 20:21:20 +00003077 Token prevCol;
3078 prevCol.z = pTab->aCol[pTab->nCol-1].zName;
3079 prevCol.n = sqlite3Strlen30(prevCol.z);
3080 pList = sqlite3ExprListAppend(pParse, 0,
3081 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
drh75897232000-05-29 14:26:00 +00003082 if( pList==0 ) goto exit_create_index;
drhbc622bc2015-08-24 15:39:42 +00003083 assert( pList->nExpr==1 );
3084 sqlite3ExprListSetSortOrder(pList, sortOrder);
drh108aa002015-08-24 20:21:20 +00003085 }else{
3086 sqlite3ExprListCheckLength(pParse, pList, "index");
drh75897232000-05-29 14:26:00 +00003087 }
3088
danielk1977b3bf5562006-01-10 17:58:23 +00003089 /* Figure out how many bytes of space are required to store explicitly
3090 ** specified collation sequence names.
3091 */
3092 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003093 Expr *pExpr = pList->a[i].pExpr;
drh7d3d9da2015-09-01 00:42:52 +00003094 assert( pExpr!=0 );
3095 if( pExpr->op==TK_COLLATE ){
dan911ce412013-05-15 15:16:50 +00003096 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003097 }
3098 }
3099
drh75897232000-05-29 14:26:00 +00003100 /*
3101 ** Allocate the index structure.
3102 */
drhea678832008-12-10 19:26:22 +00003103 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003104 nExtraCol = pPk ? pPk->nKeyCol : 1;
3105 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003106 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003107 if( db->mallocFailed ){
3108 goto exit_create_index;
3109 }
dancfc9df72014-04-25 15:01:01 +00003110 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003111 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003112 pIndex->zName = zExtra;
3113 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003114 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003115 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003116 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003117 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003118 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003119 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003120 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003121 if( pPIWhere ){
3122 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3123 pIndex->pPartIdxWhere = pPIWhere;
3124 pPIWhere = 0;
3125 }
drh21206082011-04-04 18:22:02 +00003126 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003127
drhfdd6e852005-12-16 01:06:16 +00003128 /* Check to see if we should honor DESC requests on index columns
3129 */
danielk1977da184232006-01-05 11:34:32 +00003130 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003131 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003132 }else{
3133 sortOrderMask = 0; /* Ignore DESC */
3134 }
3135
drh1f9ca2c2015-08-25 16:57:52 +00003136 /* Analyze the list of expressions that form the terms of the index and
3137 ** report any errors. In the common case where the expression is exactly
3138 ** a table column, store that column in aiColumn[]. For general expressions,
drh4b92f982015-09-29 17:20:14 +00003139 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
drhd3001712009-05-12 17:46:53 +00003140 **
drh1f9ca2c2015-08-25 16:57:52 +00003141 ** TODO: Issue a warning if two or more columns of the index are identical.
3142 ** TODO: Issue a warning if the table primary key is used as part of the
3143 ** index key.
drh75897232000-05-29 14:26:00 +00003144 */
drhfdd6e852005-12-16 01:06:16 +00003145 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
drh1f9ca2c2015-08-25 16:57:52 +00003146 Expr *pCExpr; /* The i-th index expression */
3147 int requestedSortOrder; /* ASC or DESC on the i-th expression */
drha34001c2007-02-02 12:44:37 +00003148 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003149
drhedb04ed2015-09-04 12:54:01 +00003150 sqlite3StringToId(pListItem->pExpr);
drha514b8e2015-08-25 00:27:06 +00003151 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3152 if( pParse->nErr ) goto exit_create_index;
drh108aa002015-08-24 20:21:20 +00003153 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
drha514b8e2015-08-25 00:27:06 +00003154 if( pCExpr->op!=TK_COLUMN ){
drh1f9ca2c2015-08-25 16:57:52 +00003155 if( pTab==pParse->pNewTable ){
3156 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3157 "UNIQUE constraints");
3158 goto exit_create_index;
3159 }
3160 if( pIndex->aColExpr==0 ){
drh84926532015-08-31 19:38:42 +00003161 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
3162 pIndex->aColExpr = pCopy;
3163 if( !db->mallocFailed ){
3164 assert( pCopy!=0 );
3165 pListItem = &pCopy->a[i];
3166 }
drh1f9ca2c2015-08-25 16:57:52 +00003167 }
drh4b92f982015-09-29 17:20:14 +00003168 j = XN_EXPR;
3169 pIndex->aiColumn[i] = XN_EXPR;
drh84926532015-08-31 19:38:42 +00003170 pIndex->uniqNotNull = 0;
drh1f9ca2c2015-08-25 16:57:52 +00003171 }else{
3172 j = pCExpr->iColumn;
3173 assert( j<=0x7fff );
3174 if( j<0 ){
3175 j = pTab->iPKey;
3176 }else if( pTab->aCol[j].notNull==0 ){
3177 pIndex->uniqNotNull = 0;
3178 }
3179 pIndex->aiColumn[i] = (i16)j;
drh108aa002015-08-24 20:21:20 +00003180 }
drha514b8e2015-08-25 00:27:06 +00003181 zColl = 0;
drh108aa002015-08-24 20:21:20 +00003182 if( pListItem->pExpr->op==TK_COLLATE ){
drhd3001712009-05-12 17:46:53 +00003183 int nColl;
dan911ce412013-05-15 15:16:50 +00003184 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003185 nColl = sqlite3Strlen30(zColl) + 1;
3186 assert( nExtra>=nColl );
3187 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003188 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003189 zExtra += nColl;
3190 nExtra -= nColl;
drha514b8e2015-08-25 00:27:06 +00003191 }else if( j>=0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003192 zColl = pTab->aCol[j].zColl;
danielk19770202b292004-06-09 09:55:16 +00003193 }
drha514b8e2015-08-25 00:27:06 +00003194 if( !zColl ) zColl = "BINARY";
drhb7f24de2009-05-13 17:35:23 +00003195 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003196 goto exit_create_index;
3197 }
danielk1977b3bf5562006-01-10 17:58:23 +00003198 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003199 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003200 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00003201 }
drh1f9ca2c2015-08-25 16:57:52 +00003202
3203 /* Append the table key to the end of the index. For WITHOUT ROWID
3204 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
3205 ** normal tables (when pPk==0) this will be the rowid.
3206 */
drh44156282013-10-23 22:23:03 +00003207 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003208 for(j=0; j<pPk->nKeyCol; j++){
3209 int x = pPk->aiColumn[j];
drh1f9ca2c2015-08-25 16:57:52 +00003210 assert( x>=0 );
drh7913e412013-11-01 20:30:36 +00003211 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3212 pIndex->nColumn--;
3213 }else{
3214 pIndex->aiColumn[i] = x;
3215 pIndex->azColl[i] = pPk->azColl[j];
3216 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3217 i++;
3218 }
drh44156282013-10-23 22:23:03 +00003219 }
drh7913e412013-11-01 20:30:36 +00003220 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003221 }else{
drh4b92f982015-09-29 17:20:14 +00003222 pIndex->aiColumn[i] = XN_ROWID;
drh44156282013-10-23 22:23:03 +00003223 pIndex->azColl[i] = "BINARY";
3224 }
drh51147ba2005-07-23 22:59:55 +00003225 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003226 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003227
danielk1977d8123362004-06-12 09:25:12 +00003228 if( pTab==pParse->pNewTable ){
3229 /* This routine has been called to create an automatic index as a
3230 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3231 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3232 ** i.e. one of:
3233 **
3234 ** CREATE TABLE t(x PRIMARY KEY, y);
3235 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3236 **
3237 ** Either way, check to see if the table already has such an index. If
3238 ** so, don't bother creating this one. This only applies to
3239 ** automatically created indices. Users can do as they wish with
3240 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003241 **
3242 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3243 ** (and thus suppressing the second one) even if they have different
3244 ** sort orders.
3245 **
3246 ** If there are different collating sequences or if the columns of
3247 ** the constraint occur in different orders, then the constraints are
3248 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003249 */
3250 Index *pIdx;
3251 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3252 int k;
drh5f1d1d92014-07-31 22:59:04 +00003253 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003254 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003255 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003256
drhbbbdc832013-10-22 18:01:40 +00003257 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3258 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003259 const char *z1;
3260 const char *z2;
drh1f9ca2c2015-08-25 16:57:52 +00003261 assert( pIdx->aiColumn[k]>=0 );
danielk1977d8123362004-06-12 09:25:12 +00003262 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003263 z1 = pIdx->azColl[k];
3264 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003265 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003266 }
drhbbbdc832013-10-22 18:01:40 +00003267 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003268 if( pIdx->onError!=pIndex->onError ){
3269 /* This constraint creates the same index as a previous
3270 ** constraint specified somewhere in the CREATE TABLE statement.
3271 ** However the ON CONFLICT clauses are different. If both this
3272 ** constraint and the previous equivalent constraint have explicit
3273 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003274 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003275 */
3276 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3277 sqlite3ErrorMsg(pParse,
3278 "conflicting ON CONFLICT clauses specified", 0);
3279 }
3280 if( pIdx->onError==OE_Default ){
3281 pIdx->onError = pIndex->onError;
3282 }
3283 }
drhf0636852015-03-21 02:58:20 +00003284 pRet = pIdx;
danielk1977d8123362004-06-12 09:25:12 +00003285 goto exit_create_index;
3286 }
3287 }
3288 }
3289
drh75897232000-05-29 14:26:00 +00003290 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003291 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003292 */
drh7d3d9da2015-09-01 00:42:52 +00003293 assert( pParse->nErr==0 );
drh234c39d2004-07-24 03:30:47 +00003294 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003295 Index *p;
drh21206082011-04-04 18:22:02 +00003296 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003297 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003298 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003299 if( p ){
3300 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003301 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003302 goto exit_create_index;
3303 }
drh5e00f6c2001-09-13 13:46:56 +00003304 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003305 if( pTblName!=0 ){
3306 pIndex->tnum = db->init.newTnum;
3307 }
drhd78eeee2001-09-13 16:18:53 +00003308 }
3309
drh58383402013-11-04 17:00:50 +00003310 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3311 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3312 ** emit code to allocate the index rootpage on disk and make an entry for
3313 ** the index in the sqlite_master table and populate the index with
3314 ** content. But, do not do this if we are simply reading the sqlite_master
3315 ** table to parse the schema, or if this index is the PRIMARY KEY index
3316 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003317 **
drh58383402013-11-04 17:00:50 +00003318 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3319 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003320 ** has just been created, it contains no data and the index initialization
3321 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003322 */
drh7d3d9da2015-09-01 00:42:52 +00003323 else if( HasRowid(pTab) || pTblName!=0 ){
drhadbca9c2001-09-27 15:11:53 +00003324 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003325 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003326 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003327
danielk19774adee202004-05-08 08:23:19 +00003328 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003329 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003330
drhaee128d2005-02-14 20:48:18 +00003331 sqlite3BeginWriteOperation(pParse, 1, iDb);
danc5b73582015-05-26 11:53:14 +00003332
3333 /* Create the rootpage for the index using CreateIndex. But before
3334 ** doing so, code a Noop instruction and store its address in
3335 ** Index.tnum. This is required in case this index is actually a
3336 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3337 ** that case the convertToWithoutRowidTable() routine will replace
3338 ** the Noop with a Goto to jump over the VDBE code generated below. */
3339 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
drhb7654112008-01-12 12:48:07 +00003340 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003341
3342 /* Gather the complete text of the CREATE INDEX statement into
3343 ** the zStmt variable
3344 */
drhd3001712009-05-12 17:46:53 +00003345 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003346 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003347 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003348 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003349 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003350 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003351 }else{
3352 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003353 /* zStmt = sqlite3MPrintf(""); */
3354 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003355 }
drh063336a2004-11-05 20:58:39 +00003356
3357 /* Add an entry in sqlite_master for this index
3358 */
3359 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003360 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003361 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3362 pIndex->zName,
3363 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003364 iMem,
drh063336a2004-11-05 20:58:39 +00003365 zStmt
3366 );
drh633e6d52008-07-28 19:34:53 +00003367 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003368
danielk1977a21c6b62005-01-24 10:25:59 +00003369 /* Fill the index with data and reparse the schema. Code an OP_Expire
3370 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003371 */
danielk1977cbb18d22004-05-28 11:37:27 +00003372 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003373 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003374 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003375 sqlite3VdbeAddParseSchemaOp(v, iDb,
3376 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003377 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003378 }
danc5b73582015-05-26 11:53:14 +00003379
3380 sqlite3VdbeJumpHere(v, pIndex->tnum);
drh75897232000-05-29 14:26:00 +00003381 }
3382
danielk1977d8123362004-06-12 09:25:12 +00003383 /* When adding an index to the list of indices for a table, make
3384 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003385 ** OE_Ignore. This is necessary for the correct constraint check
3386 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3387 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003388 */
drh234c39d2004-07-24 03:30:47 +00003389 if( db->init.busy || pTblName==0 ){
3390 if( onError!=OE_Replace || pTab->pIndex==0
3391 || pTab->pIndex->onError==OE_Replace){
3392 pIndex->pNext = pTab->pIndex;
3393 pTab->pIndex = pIndex;
3394 }else{
3395 Index *pOther = pTab->pIndex;
3396 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3397 pOther = pOther->pNext;
3398 }
3399 pIndex->pNext = pOther->pNext;
3400 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003401 }
dan1da40a32009-09-19 17:00:31 +00003402 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003403 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003404 }
danielk1977d8123362004-06-12 09:25:12 +00003405
drh75897232000-05-29 14:26:00 +00003406 /* Clean up before exiting */
3407exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003408 if( pIndex ) freeIndex(db, pIndex);
3409 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003410 sqlite3ExprListDelete(db, pList);
3411 sqlite3SrcListDelete(db, pTblName);
3412 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003413 return pRet;
drh75897232000-05-29 14:26:00 +00003414}
3415
3416/*
drh51147ba2005-07-23 22:59:55 +00003417** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003418** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003419**
peter.d.reid60ec9142014-09-06 16:39:46 +00003420** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003421** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3422** number of rows in the table that match any particular value of the
3423** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003424** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003425** of the index. And so forth. It must always be the case that
3426*
3427** aiRowEst[N]<=aiRowEst[N-1]
3428** aiRowEst[N]>=1
3429**
3430** Apart from that, we have little to go on besides intuition as to
3431** how aiRowEst[] should be initialized. The numbers generated here
3432** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003433*/
3434void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003435 /* 10, 9, 8, 7, 6 */
3436 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003437 LogEst *a = pIdx->aiRowLogEst;
3438 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003439 int i;
dancfc9df72014-04-25 15:01:01 +00003440
dan264d2b92014-04-29 19:01:57 +00003441 /* Set the first entry (number of rows in the index) to the estimated
3442 ** number of rows in the table. Or 10, if the estimated number of rows
3443 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003444 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003445 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3446
3447 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3448 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003449 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003450 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3451 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003452 }
dan264d2b92014-04-29 19:01:57 +00003453
3454 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003455 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003456}
3457
3458/*
drh74e24cd2002-01-09 03:19:59 +00003459** This routine will drop an existing named index. This routine
3460** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003461*/
drh4d91a702006-01-04 15:54:36 +00003462void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003463 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003464 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003465 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003466 int iDb;
drh75897232000-05-29 14:26:00 +00003467
drh8af73d42009-05-13 22:58:28 +00003468 assert( pParse->nErr==0 ); /* Never called with prior errors */
3469 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003470 goto exit_drop_index;
3471 }
drhd24cc422003-03-27 12:51:24 +00003472 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003473 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3474 goto exit_drop_index;
3475 }
danielk19774adee202004-05-08 08:23:19 +00003476 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003477 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003478 if( !ifExists ){
3479 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003480 }else{
3481 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003482 }
drha6ecd332004-06-10 00:29:09 +00003483 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003484 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003485 }
drh48dd1d82014-05-27 18:18:58 +00003486 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003487 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003488 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003489 goto exit_drop_index;
3490 }
danielk1977da184232006-01-05 11:34:32 +00003491 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003492#ifndef SQLITE_OMIT_AUTHORIZATION
3493 {
3494 int code = SQLITE_DROP_INDEX;
3495 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003496 const char *zDb = db->aDb[iDb].zName;
3497 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003498 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003499 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003500 }
danielk1977da184232006-01-05 11:34:32 +00003501 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003502 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003503 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003504 }
drhed6c8672003-01-12 18:02:16 +00003505 }
drhe5f9c642003-01-13 23:27:31 +00003506#endif
drh75897232000-05-29 14:26:00 +00003507
3508 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003509 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003510 if( v ){
drh77658e22007-12-04 16:54:52 +00003511 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003512 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003513 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003514 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003515 );
drha5ae4c32011-08-07 01:31:52 +00003516 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003517 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003518 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003519 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003520 }
3521
drhd24cc422003-03-27 12:51:24 +00003522exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003523 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003524}
3525
3526/*
dan9ace1122012-03-29 07:51:45 +00003527** pArray is a pointer to an array of objects. Each object in the
3528** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3529** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003530**
dan9ace1122012-03-29 07:51:45 +00003531** When this function is called, *pnEntry contains the current size of
3532** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3533** in total).
drh13449892005-09-07 21:22:45 +00003534**
dan9ace1122012-03-29 07:51:45 +00003535** If the realloc() is successful (i.e. if no OOM condition occurs), the
3536** space allocated for the new object is zeroed, *pnEntry updated to
3537** reflect the new size of the array and a pointer to the new allocation
3538** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003539**
dan9ace1122012-03-29 07:51:45 +00003540** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3541** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003542*/
drhcf643722007-03-27 13:36:37 +00003543void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003544 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003545 void *pArray, /* Array of objects. Might be reallocated */
3546 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003547 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003548 int *pIdx /* Write the index of a new slot here */
3549){
3550 char *z;
drh6c535152012-02-02 03:38:30 +00003551 int n = *pnEntry;
3552 if( (n & (n-1))==0 ){
3553 int sz = (n==0) ? 1 : 2*n;
3554 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003555 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003556 *pIdx = -1;
3557 return pArray;
drh13449892005-09-07 21:22:45 +00003558 }
drhcf643722007-03-27 13:36:37 +00003559 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003560 }
drhcf643722007-03-27 13:36:37 +00003561 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003562 memset(&z[n * szEntry], 0, szEntry);
3563 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003564 ++*pnEntry;
3565 return pArray;
drh13449892005-09-07 21:22:45 +00003566}
3567
3568/*
drh75897232000-05-29 14:26:00 +00003569** Append a new element to the given IdList. Create a new IdList if
3570** need be.
drhdaffd0e2001-04-11 14:28:42 +00003571**
3572** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003573*/
drh17435752007-08-16 04:30:38 +00003574IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003575 int i;
drh75897232000-05-29 14:26:00 +00003576 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003577 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003578 if( pList==0 ) return 0;
3579 }
drhcf643722007-03-27 13:36:37 +00003580 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003581 db,
drhcf643722007-03-27 13:36:37 +00003582 pList->a,
3583 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003584 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003585 &i
3586 );
drh13449892005-09-07 21:22:45 +00003587 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003588 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003589 return 0;
drh75897232000-05-29 14:26:00 +00003590 }
drh17435752007-08-16 04:30:38 +00003591 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003592 return pList;
3593}
3594
3595/*
drhfe05af82005-07-21 03:14:59 +00003596** Delete an IdList.
3597*/
drh633e6d52008-07-28 19:34:53 +00003598void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003599 int i;
3600 if( pList==0 ) return;
3601 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003602 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003603 }
drh633e6d52008-07-28 19:34:53 +00003604 sqlite3DbFree(db, pList->a);
3605 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003606}
3607
3608/*
3609** Return the index in pList of the identifier named zId. Return -1
3610** if not found.
3611*/
3612int sqlite3IdListIndex(IdList *pList, const char *zName){
3613 int i;
3614 if( pList==0 ) return -1;
3615 for(i=0; i<pList->nId; i++){
3616 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3617 }
3618 return -1;
3619}
3620
3621/*
drha78c22c2008-11-11 18:28:58 +00003622** Expand the space allocated for the given SrcList object by
3623** creating nExtra new slots beginning at iStart. iStart is zero based.
3624** New slots are zeroed.
3625**
3626** For example, suppose a SrcList initially contains two entries: A,B.
3627** To append 3 new entries onto the end, do this:
3628**
3629** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3630**
3631** After the call above it would contain: A, B, nil, nil, nil.
3632** If the iStart argument had been 1 instead of 2, then the result
3633** would have been: A, nil, nil, nil, B. To prepend the new slots,
3634** the iStart value would be 0. The result then would
3635** be: nil, nil, nil, A, B.
3636**
3637** If a memory allocation fails the SrcList is unchanged. The
3638** db->mallocFailed flag will be set to true.
3639*/
3640SrcList *sqlite3SrcListEnlarge(
3641 sqlite3 *db, /* Database connection to notify of OOM errors */
3642 SrcList *pSrc, /* The SrcList to be enlarged */
3643 int nExtra, /* Number of new slots to add to pSrc->a[] */
3644 int iStart /* Index in pSrc->a[] of first new slot */
3645){
3646 int i;
3647
3648 /* Sanity checking on calling parameters */
3649 assert( iStart>=0 );
3650 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003651 assert( pSrc!=0 );
3652 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003653
3654 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003655 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003656 SrcList *pNew;
3657 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003658 int nGot;
drha78c22c2008-11-11 18:28:58 +00003659 pNew = sqlite3DbRealloc(db, pSrc,
3660 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3661 if( pNew==0 ){
3662 assert( db->mallocFailed );
3663 return pSrc;
3664 }
3665 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003666 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003667 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003668 }
3669
3670 /* Move existing slots that come after the newly inserted slots
3671 ** out of the way */
3672 for(i=pSrc->nSrc-1; i>=iStart; i--){
3673 pSrc->a[i+nExtra] = pSrc->a[i];
3674 }
drh6d1626e2014-03-05 15:52:43 +00003675 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003676
3677 /* Zero the newly allocated slots */
3678 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3679 for(i=iStart; i<iStart+nExtra; i++){
3680 pSrc->a[i].iCursor = -1;
3681 }
3682
3683 /* Return a pointer to the enlarged SrcList */
3684 return pSrc;
3685}
3686
3687
3688/*
drhad3cab52002-05-24 02:04:32 +00003689** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003690** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003691**
drha78c22c2008-11-11 18:28:58 +00003692** A SrcList is returned, or NULL if there is an OOM error. The returned
3693** SrcList might be the same as the SrcList that was input or it might be
3694** a new one. If an OOM error does occurs, then the prior value of pList
3695** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003696**
3697** If pDatabase is not null, it means that the table has an optional
3698** database name prefix. Like this: "database.table". The pDatabase
3699** points to the table name and the pTable points to the database name.
3700** The SrcList.a[].zName field is filled with the table name which might
3701** come from pTable (if pDatabase is NULL) or from pDatabase.
3702** SrcList.a[].zDatabase is filled with the database name from pTable,
3703** or with NULL if no database is specified.
3704**
3705** In other words, if call like this:
3706**
drh17435752007-08-16 04:30:38 +00003707** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003708**
3709** Then B is a table name and the database name is unspecified. If called
3710** like this:
3711**
drh17435752007-08-16 04:30:38 +00003712** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003713**
drhd3001712009-05-12 17:46:53 +00003714** Then C is the table name and B is the database name. If C is defined
3715** then so is B. In other words, we never have a case where:
3716**
3717** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003718**
3719** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3720** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003721*/
drh17435752007-08-16 04:30:38 +00003722SrcList *sqlite3SrcListAppend(
3723 sqlite3 *db, /* Connection to notify of malloc failures */
3724 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3725 Token *pTable, /* Table to append */
3726 Token *pDatabase /* Database of the table */
3727){
drha99db3b2004-06-19 14:49:12 +00003728 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003729 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003730 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003731 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003732 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003733 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003734 }
drha78c22c2008-11-11 18:28:58 +00003735 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3736 if( db->mallocFailed ){
3737 sqlite3SrcListDelete(db, pList);
3738 return 0;
drhad3cab52002-05-24 02:04:32 +00003739 }
drha78c22c2008-11-11 18:28:58 +00003740 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003741 if( pDatabase && pDatabase->z==0 ){
3742 pDatabase = 0;
3743 }
drhd3001712009-05-12 17:46:53 +00003744 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003745 Token *pTemp = pDatabase;
3746 pDatabase = pTable;
3747 pTable = pTemp;
3748 }
drh17435752007-08-16 04:30:38 +00003749 pItem->zName = sqlite3NameFromToken(db, pTable);
3750 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003751 return pList;
3752}
3753
3754/*
drhdfe88ec2008-11-03 20:55:06 +00003755** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003756*/
danielk19774adee202004-05-08 08:23:19 +00003757void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003758 int i;
drh9b3187e2005-01-18 14:45:47 +00003759 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003760 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003761 if( pList ){
3762 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3763 if( pItem->iCursor>=0 ) break;
3764 pItem->iCursor = pParse->nTab++;
3765 if( pItem->pSelect ){
3766 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3767 }
drh63eb5f22003-04-29 16:20:44 +00003768 }
3769 }
3770}
3771
3772/*
drhad3cab52002-05-24 02:04:32 +00003773** Delete an entire SrcList including all its substructure.
3774*/
drh633e6d52008-07-28 19:34:53 +00003775void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003776 int i;
drhbe5c89a2004-07-26 00:31:09 +00003777 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003778 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003779 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003780 sqlite3DbFree(db, pItem->zDatabase);
3781 sqlite3DbFree(db, pItem->zName);
3782 sqlite3DbFree(db, pItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00003783 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
3784 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
dan1feeaed2010-07-23 15:41:47 +00003785 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003786 sqlite3SelectDelete(db, pItem->pSelect);
3787 sqlite3ExprDelete(db, pItem->pOn);
3788 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003789 }
drh633e6d52008-07-28 19:34:53 +00003790 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003791}
3792
drh982cef72000-05-30 16:27:03 +00003793/*
drh61dfc312006-12-16 16:25:15 +00003794** This routine is called by the parser to add a new term to the
3795** end of a growing FROM clause. The "p" parameter is the part of
3796** the FROM clause that has already been constructed. "p" is NULL
3797** if this is the first term of the FROM clause. pTable and pDatabase
3798** are the name of the table and database named in the FROM clause term.
3799** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003800** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003801** alias token. If the term is a subquery, then pSubquery is the
3802** SELECT statement that the subquery encodes. The pTable and
3803** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3804** parameters are the content of the ON and USING clauses.
3805**
3806** Return a new SrcList which encodes is the FROM with the new
3807** term added.
3808*/
3809SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003810 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003811 SrcList *p, /* The left part of the FROM clause already seen */
3812 Token *pTable, /* Name of the table to add to the FROM clause */
3813 Token *pDatabase, /* Name of the database containing pTable */
3814 Token *pAlias, /* The right-hand side of the AS subexpression */
3815 Select *pSubquery, /* A subquery used in place of a table name */
3816 Expr *pOn, /* The ON clause of a join */
3817 IdList *pUsing /* The USING clause of a join */
3818){
3819 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003820 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003821 if( !p && (pOn || pUsing) ){
3822 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3823 (pOn ? "ON" : "USING")
3824 );
3825 goto append_from_error;
3826 }
drh17435752007-08-16 04:30:38 +00003827 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003828 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003829 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003830 }
3831 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003832 assert( pAlias!=0 );
3833 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003834 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003835 }
3836 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003837 pItem->pOn = pOn;
3838 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003839 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003840
3841 append_from_error:
3842 assert( p==0 );
3843 sqlite3ExprDelete(db, pOn);
3844 sqlite3IdListDelete(db, pUsing);
3845 sqlite3SelectDelete(db, pSubquery);
3846 return 0;
drh61dfc312006-12-16 16:25:15 +00003847}
3848
3849/*
danielk1977b1c685b2008-10-06 16:18:39 +00003850** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3851** element of the source-list passed as the second argument.
3852*/
3853void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003854 assert( pIndexedBy!=0 );
3855 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003856 struct SrcList_item *pItem = &p->a[p->nSrc-1];
drh8a48b9c2015-08-19 15:20:00 +00003857 assert( pItem->fg.notIndexed==0 );
3858 assert( pItem->fg.isIndexedBy==0 );
3859 assert( pItem->fg.isTabFunc==0 );
danielk1977b1c685b2008-10-06 16:18:39 +00003860 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3861 /* A "NOT INDEXED" clause was supplied. See parse.y
3862 ** construct "indexed_opt" for details. */
drh8a48b9c2015-08-19 15:20:00 +00003863 pItem->fg.notIndexed = 1;
danielk1977b1c685b2008-10-06 16:18:39 +00003864 }else{
drh8a48b9c2015-08-19 15:20:00 +00003865 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
3866 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
danielk1977b1c685b2008-10-06 16:18:39 +00003867 }
3868 }
3869}
3870
3871/*
drh01d230c2015-08-19 17:11:37 +00003872** Add the list of function arguments to the SrcList entry for a
3873** table-valued-function.
3874*/
3875void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
drhd8b1bfc2015-08-20 23:21:34 +00003876 if( p && pList ){
drh01d230c2015-08-19 17:11:37 +00003877 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3878 assert( pItem->fg.notIndexed==0 );
3879 assert( pItem->fg.isIndexedBy==0 );
3880 assert( pItem->fg.isTabFunc==0 );
3881 pItem->u1.pFuncArg = pList;
3882 pItem->fg.isTabFunc = 1;
drhd8b1bfc2015-08-20 23:21:34 +00003883 }else{
3884 sqlite3ExprListDelete(pParse->db, pList);
drh01d230c2015-08-19 17:11:37 +00003885 }
3886}
3887
3888/*
drh61dfc312006-12-16 16:25:15 +00003889** When building up a FROM clause in the parser, the join operator
3890** is initially attached to the left operand. But the code generator
3891** expects the join operator to be on the right operand. This routine
3892** Shifts all join operators from left to right for an entire FROM
3893** clause.
3894**
3895** Example: Suppose the join is like this:
3896**
3897** A natural cross join B
3898**
3899** The operator is "natural cross join". The A and B operands are stored
3900** in p->a[0] and p->a[1], respectively. The parser initially stores the
3901** operator with A. This routine shifts that operator over to B.
3902*/
3903void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003904 if( p ){
drh61dfc312006-12-16 16:25:15 +00003905 int i;
3906 for(i=p->nSrc-1; i>0; i--){
drh8a48b9c2015-08-19 15:20:00 +00003907 p->a[i].fg.jointype = p->a[i-1].fg.jointype;
drh61dfc312006-12-16 16:25:15 +00003908 }
drh8a48b9c2015-08-19 15:20:00 +00003909 p->a[0].fg.jointype = 0;
drh61dfc312006-12-16 16:25:15 +00003910 }
3911}
3912
3913/*
drhc4a3c772001-04-04 11:48:57 +00003914** Begin a transaction
3915*/
drh684917c2004-10-05 02:41:42 +00003916void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003917 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003918 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003919 int i;
drh5e00f6c2001-09-13 13:46:56 +00003920
drhd3001712009-05-12 17:46:53 +00003921 assert( pParse!=0 );
3922 db = pParse->db;
3923 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003924/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003925 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3926 return;
3927 }
danielk19771d850a72004-05-31 08:26:49 +00003928 v = sqlite3GetVdbe(pParse);
3929 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003930 if( type!=TK_DEFERRED ){
3931 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003932 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003933 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003934 }
3935 }
drh66a51672008-01-03 00:01:23 +00003936 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003937}
3938
3939/*
3940** Commit a transaction
3941*/
danielk19774adee202004-05-08 08:23:19 +00003942void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003943 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003944
drhd3001712009-05-12 17:46:53 +00003945 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003946 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003947 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3948 return;
3949 }
danielk19771d850a72004-05-31 08:26:49 +00003950 v = sqlite3GetVdbe(pParse);
3951 if( v ){
drh66a51672008-01-03 00:01:23 +00003952 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003953 }
drhc4a3c772001-04-04 11:48:57 +00003954}
3955
3956/*
3957** Rollback a transaction
3958*/
danielk19774adee202004-05-08 08:23:19 +00003959void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003960 Vdbe *v;
3961
drhd3001712009-05-12 17:46:53 +00003962 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003963 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003964 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3965 return;
3966 }
danielk19774adee202004-05-08 08:23:19 +00003967 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003968 if( v ){
drh66a51672008-01-03 00:01:23 +00003969 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003970 }
drhc4a3c772001-04-04 11:48:57 +00003971}
drhf57b14a2001-09-14 18:54:08 +00003972
3973/*
danielk1977fd7f0452008-12-17 17:30:26 +00003974** This function is called by the parser when it parses a command to create,
3975** release or rollback an SQL savepoint.
3976*/
3977void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003978 char *zName = sqlite3NameFromToken(pParse->db, pName);
3979 if( zName ){
3980 Vdbe *v = sqlite3GetVdbe(pParse);
3981#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003982 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003983 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3984#endif
3985 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3986 sqlite3DbFree(pParse->db, zName);
3987 return;
3988 }
3989 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003990 }
3991}
3992
3993/*
drhdc3ff9c2004-08-18 02:10:15 +00003994** Make sure the TEMP database is open and available for use. Return
3995** the number of errors. Leave any error messages in the pParse structure.
3996*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003997int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003998 sqlite3 *db = pParse->db;
3999 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00004000 int rc;
drh10a76c92010-01-26 01:25:26 +00004001 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00004002 static const int flags =
4003 SQLITE_OPEN_READWRITE |
4004 SQLITE_OPEN_CREATE |
4005 SQLITE_OPEN_EXCLUSIVE |
4006 SQLITE_OPEN_DELETEONCLOSE |
4007 SQLITE_OPEN_TEMP_DB;
4008
dan3a6d8ae2011-04-23 15:54:54 +00004009 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00004010 if( rc!=SQLITE_OK ){
4011 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4012 "file for storing temporary tables");
4013 pParse->rc = rc;
4014 return 1;
4015 }
drh10a76c92010-01-26 01:25:26 +00004016 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00004017 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00004018 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
4019 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00004020 return 1;
drh10a76c92010-01-26 01:25:26 +00004021 }
drhdc3ff9c2004-08-18 02:10:15 +00004022 }
4023 return 0;
4024}
4025
4026/*
drhaceb31b2014-02-08 01:40:27 +00004027** Record the fact that the schema cookie will need to be verified
4028** for database iDb. The code to actually verify the schema cookie
4029** will occur at the end of the top-level VDBE and will be generated
4030** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00004031*/
danielk19774adee202004-05-08 08:23:19 +00004032void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004033 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00004034 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00004035
drhaceb31b2014-02-08 01:40:27 +00004036 assert( iDb>=0 && iDb<db->nDb );
4037 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
4038 assert( iDb<SQLITE_MAX_ATTACHED+2 );
4039 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00004040 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4041 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00004042 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
4043 if( !OMIT_TEMPDB && iDb==1 ){
4044 sqlite3OpenTempDatabase(pToplevel);
4045 }
drh001bbcb2003-03-19 03:14:00 +00004046 }
drh001bbcb2003-03-19 03:14:00 +00004047}
4048
4049/*
dan57966752011-04-09 17:32:58 +00004050** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4051** attached database. Otherwise, invoke it for the database named zDb only.
4052*/
4053void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4054 sqlite3 *db = pParse->db;
4055 int i;
4056 for(i=0; i<db->nDb; i++){
4057 Db *pDb = &db->aDb[i];
4058 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
4059 sqlite3CodeVerifySchema(pParse, i);
4060 }
4061 }
4062}
4063
4064/*
drh1c928532002-01-31 15:54:21 +00004065** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00004066** might change the database.
4067**
4068** This routine starts a new transaction if we are not already within
4069** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00004070** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00004071** be set for operations that might fail (due to a constraint) part of
4072** the way through and which will need to undo some writes without having to
4073** rollback the whole transaction. For operations where all constraints
4074** can be checked before any changes are made to the database, it is never
4075** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00004076*/
drh7f0f12e2004-05-21 13:39:50 +00004077void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004078 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00004079 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00004080 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00004081 pToplevel->isMultiWrite |= setStatement;
4082}
4083
drhff738bc2009-09-24 00:09:58 +00004084/*
4085** Indicate that the statement currently under construction might write
4086** more than one entry (example: deleting one row then inserting another,
4087** inserting multiple rows in a table, or inserting a row and index entries.)
4088** If an abort occurs after some of these writes have completed, then it will
4089** be necessary to undo the completed writes.
4090*/
4091void sqlite3MultiWrite(Parse *pParse){
4092 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4093 pToplevel->isMultiWrite = 1;
4094}
4095
dane0af83a2009-09-08 19:15:01 +00004096/*
drhff738bc2009-09-24 00:09:58 +00004097** The code generator calls this routine if is discovers that it is
4098** possible to abort a statement prior to completion. In order to
4099** perform this abort without corrupting the database, we need to make
4100** sure that the statement is protected by a statement transaction.
4101**
4102** Technically, we only need to set the mayAbort flag if the
4103** isMultiWrite flag was previously set. There is a time dependency
4104** such that the abort must occur after the multiwrite. This makes
4105** some statements involving the REPLACE conflict resolution algorithm
4106** go a little faster. But taking advantage of this time dependency
4107** makes it more difficult to prove that the code is correct (in
4108** particular, it prevents us from writing an effective
4109** implementation of sqlite3AssertMayAbort()) and so we have chosen
4110** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00004111*/
4112void sqlite3MayAbort(Parse *pParse){
4113 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4114 pToplevel->mayAbort = 1;
4115}
4116
4117/*
4118** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4119** error. The onError parameter determines which (if any) of the statement
4120** and/or current transaction is rolled back.
4121*/
drhd91c1a12013-02-09 13:58:25 +00004122void sqlite3HaltConstraint(
4123 Parse *pParse, /* Parsing context */
4124 int errCode, /* extended error code */
4125 int onError, /* Constraint type */
4126 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00004127 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4128 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00004129){
dane0af83a2009-09-08 19:15:01 +00004130 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00004131 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00004132 if( onError==OE_Abort ){
4133 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00004134 }
drhd91c1a12013-02-09 13:58:25 +00004135 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00004136 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4137}
4138
4139/*
4140** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4141*/
4142void sqlite3UniqueConstraint(
4143 Parse *pParse, /* Parsing context */
4144 int onError, /* Constraint type */
4145 Index *pIdx /* The index that triggers the constraint */
4146){
4147 char *zErr;
4148 int j;
4149 StrAccum errMsg;
4150 Table *pTab = pIdx->pTable;
4151
drhc0490572015-05-02 11:45:53 +00004152 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
drh8b576422015-08-31 23:09:42 +00004153 if( pIdx->aColExpr ){
4154 sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
4155 }else{
4156 for(j=0; j<pIdx->nKeyCol; j++){
4157 char *zCol;
4158 assert( pIdx->aiColumn[j]>=0 );
4159 zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4160 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
4161 sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
4162 }
drhf9c8ce32013-11-05 13:33:55 +00004163 }
4164 zErr = sqlite3StrAccumFinish(&errMsg);
4165 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004166 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4167 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004168 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004169}
4170
4171
4172/*
4173** Code an OP_Halt due to non-unique rowid.
4174*/
4175void sqlite3RowidConstraint(
4176 Parse *pParse, /* Parsing context */
4177 int onError, /* Conflict resolution algorithm */
4178 Table *pTab /* The table with the non-unique rowid */
4179){
4180 char *zMsg;
4181 int rc;
4182 if( pTab->iPKey>=0 ){
4183 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4184 pTab->aCol[pTab->iPKey].zName);
4185 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4186 }else{
4187 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4188 rc = SQLITE_CONSTRAINT_ROWID;
4189 }
4190 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4191 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004192}
4193
drh4343fea2004-11-05 23:46:15 +00004194/*
4195** Check to see if pIndex uses the collating sequence pColl. Return
4196** true if it does and false if it does not.
4197*/
4198#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004199static int collationMatch(const char *zColl, Index *pIndex){
4200 int i;
drh04491712009-05-13 17:21:13 +00004201 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004202 for(i=0; i<pIndex->nColumn; i++){
4203 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004204 assert( z!=0 || pIndex->aiColumn[i]<0 );
4205 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004206 return 1;
4207 }
drh4343fea2004-11-05 23:46:15 +00004208 }
4209 return 0;
4210}
4211#endif
4212
4213/*
4214** Recompute all indices of pTab that use the collating sequence pColl.
4215** If pColl==0 then recompute all indices of pTab.
4216*/
4217#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004218static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004219 Index *pIndex; /* An index associated with pTab */
4220
4221 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004222 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004223 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4224 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004225 sqlite3RefillIndex(pParse, pIndex, -1);
4226 }
4227 }
4228}
4229#endif
4230
4231/*
4232** Recompute all indices of all tables in all databases where the
4233** indices use the collating sequence pColl. If pColl==0 then recompute
4234** all indices everywhere.
4235*/
4236#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004237static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004238 Db *pDb; /* A single database */
4239 int iDb; /* The database index number */
4240 sqlite3 *db = pParse->db; /* The database connection */
4241 HashElem *k; /* For looping over tables in pDb */
4242 Table *pTab; /* A table in the database */
4243
drh21206082011-04-04 18:22:02 +00004244 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004245 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004246 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004247 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004248 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004249 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004250 }
4251 }
4252}
4253#endif
4254
4255/*
drheee46cf2004-11-06 00:02:48 +00004256** Generate code for the REINDEX command.
4257**
4258** REINDEX -- 1
4259** REINDEX <collation> -- 2
4260** REINDEX ?<database>.?<tablename> -- 3
4261** REINDEX ?<database>.?<indexname> -- 4
4262**
4263** Form 1 causes all indices in all attached databases to be rebuilt.
4264** Form 2 rebuilds all indices in all databases that use the named
4265** collating function. Forms 3 and 4 rebuild the named index or all
4266** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004267*/
4268#ifndef SQLITE_OMIT_REINDEX
4269void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4270 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4271 char *z; /* Name of a table or index */
4272 const char *zDb; /* Name of the database */
4273 Table *pTab; /* A table in the database */
4274 Index *pIndex; /* An index associated with pTab */
4275 int iDb; /* The database index number */
4276 sqlite3 *db = pParse->db; /* The database connection */
4277 Token *pObjName; /* Name of the table or index to be reindexed */
4278
danielk197733a5edc2005-01-27 00:22:02 +00004279 /* Read the database schema. If an error occurs, leave an error message
4280 ** and code in pParse and return NULL. */
4281 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004282 return;
danielk197733a5edc2005-01-27 00:22:02 +00004283 }
4284
drh8af73d42009-05-13 22:58:28 +00004285 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004286 reindexDatabases(pParse, 0);
4287 return;
drhd3001712009-05-12 17:46:53 +00004288 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004289 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004290 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004291 zColl = sqlite3NameFromToken(pParse->db, pName1);
4292 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004293 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004294 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004295 reindexDatabases(pParse, zColl);
4296 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004297 return;
4298 }
drh633e6d52008-07-28 19:34:53 +00004299 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004300 }
4301 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4302 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004303 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004304 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004305 zDb = db->aDb[iDb].zName;
4306 pTab = sqlite3FindTable(db, z, zDb);
4307 if( pTab ){
4308 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004309 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004310 return;
4311 }
4312 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004313 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004314 if( pIndex ){
4315 sqlite3BeginWriteOperation(pParse, 0, iDb);
4316 sqlite3RefillIndex(pParse, pIndex, -1);
4317 return;
4318 }
4319 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4320}
4321#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004322
4323/*
drh2ec2fb22013-11-06 19:59:23 +00004324** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004325**
drh2ec2fb22013-11-06 19:59:23 +00004326** The KeyInfo structure for an index is cached in the Index object.
4327** So there might be multiple references to the returned pointer. The
4328** caller should not try to modify the KeyInfo object.
4329**
4330** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4331** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004332*/
drh2ec2fb22013-11-06 19:59:23 +00004333KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh18b67f32014-12-12 00:20:37 +00004334 int i;
4335 int nCol = pIdx->nColumn;
4336 int nKey = pIdx->nKeyCol;
4337 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004338 if( pParse->nErr ) return 0;
drh18b67f32014-12-12 00:20:37 +00004339 if( pIdx->uniqNotNull ){
4340 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4341 }else{
4342 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
drh41e13e12013-11-07 14:09:39 +00004343 }
drh18b67f32014-12-12 00:20:37 +00004344 if( pKey ){
4345 assert( sqlite3KeyInfoIsWriteable(pKey) );
4346 for(i=0; i<nCol; i++){
4347 char *zColl = pIdx->azColl[i];
4348 assert( zColl!=0 );
4349 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4350 sqlite3LocateCollSeq(pParse, zColl);
4351 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
drh2ec2fb22013-11-06 19:59:23 +00004352 }
drh18b67f32014-12-12 00:20:37 +00004353 if( pParse->nErr ){
4354 sqlite3KeyInfoUnref(pKey);
4355 pKey = 0;
danielk1977b3bf5562006-01-10 17:58:23 +00004356 }
danielk1977b3bf5562006-01-10 17:58:23 +00004357 }
drh18b67f32014-12-12 00:20:37 +00004358 return pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00004359}
drh8b471862014-01-11 13:22:17 +00004360
4361#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004362/*
4363** This routine is invoked once per CTE by the parser while parsing a
4364** WITH clause.
drh8b471862014-01-11 13:22:17 +00004365*/
dan7d562db2014-01-11 19:19:36 +00004366With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004367 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004368 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004369 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004370 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004371 Select *pQuery /* Query used to initialize the table */
4372){
dan4e9119d2014-01-13 15:12:23 +00004373 sqlite3 *db = pParse->db;
4374 With *pNew;
4375 char *zName;
4376
4377 /* Check that the CTE name is unique within this WITH clause. If
4378 ** not, store an error in the Parse structure. */
4379 zName = sqlite3NameFromToken(pParse->db, pName);
4380 if( zName && pWith ){
4381 int i;
4382 for(i=0; i<pWith->nCte; i++){
4383 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004384 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004385 }
4386 }
4387 }
4388
4389 if( pWith ){
4390 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4391 pNew = sqlite3DbRealloc(db, pWith, nByte);
4392 }else{
4393 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4394 }
4395 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004396 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004397
4398 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004399 sqlite3ExprListDelete(db, pArglist);
4400 sqlite3SelectDelete(db, pQuery);
4401 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004402 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004403 }else{
4404 pNew->a[pNew->nCte].pSelect = pQuery;
4405 pNew->a[pNew->nCte].pCols = pArglist;
4406 pNew->a[pNew->nCte].zName = zName;
drh0576bc52015-08-26 11:40:11 +00004407 pNew->a[pNew->nCte].zCteErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004408 pNew->nCte++;
4409 }
4410
4411 return pNew;
drh8b471862014-01-11 13:22:17 +00004412}
4413
dan7d562db2014-01-11 19:19:36 +00004414/*
4415** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004416*/
dan7d562db2014-01-11 19:19:36 +00004417void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004418 if( pWith ){
4419 int i;
4420 for(i=0; i<pWith->nCte; i++){
4421 struct Cte *pCte = &pWith->a[i];
4422 sqlite3ExprListDelete(db, pCte->pCols);
4423 sqlite3SelectDelete(db, pCte->pSelect);
4424 sqlite3DbFree(db, pCte->zName);
4425 }
4426 sqlite3DbFree(db, pWith);
4427 }
drh8b471862014-01-11 13:22:17 +00004428}
4429#endif /* !defined(SQLITE_OMIT_CTE) */