blob: a46bb585208009f4f0a58d5e6ec72e0adc21253e [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/*
1053** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001054**
1055** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001056** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001057** first to get things going. Then this routine is called for each
1058** column.
drh75897232000-05-29 14:26:00 +00001059*/
danielk19774adee202004-05-08 08:23:19 +00001060void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001061 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001062 int i;
drha99db3b2004-06-19 14:49:12 +00001063 char *z;
drhc9b84a12002-06-20 11:36:48 +00001064 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001065 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001066 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001067#if SQLITE_MAX_COLUMN
1068 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001069 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1070 return;
1071 }
drhbb4957f2008-03-20 14:03:29 +00001072#endif
danielk1977ae74e032008-12-23 11:11:51 +00001073 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001074 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001075 for(i=0; i<p->nCol; i++){
drha6f88ff2015-11-19 13:21:31 +00001076 if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
danielk19774adee202004-05-08 08:23:19 +00001077 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001078 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001079 return;
1080 }
1081 }
drh75897232000-05-29 14:26:00 +00001082 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001083 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001084 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001085 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001086 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001087 return;
1088 }
drh6d4abfb2001-10-22 02:58:08 +00001089 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001090 }
drhc9b84a12002-06-20 11:36:48 +00001091 pCol = &p->aCol[p->nCol];
1092 memset(pCol, 0, sizeof(p->aCol[0]));
1093 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001094
1095 /* If there is no type specified, columns have the default affinity
drh05883a32015-06-02 15:32:08 +00001096 ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
danielk19774f057f92004-06-08 00:02:33 +00001097 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001098 */
drh05883a32015-06-02 15:32:08 +00001099 pCol->affinity = SQLITE_AFF_BLOB;
drhfdaac672013-10-04 15:30:21 +00001100 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001101 p->nCol++;
drh75897232000-05-29 14:26:00 +00001102}
1103
1104/*
drh382c0242001-10-06 16:33:02 +00001105** This routine is called by the parser while in the middle of
1106** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1107** been seen on a column. This routine sets the notNull flag on
1108** the column currently under construction.
1109*/
danielk19774adee202004-05-08 08:23:19 +00001110void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001111 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001112 p = pParse->pNewTable;
1113 if( p==0 || NEVER(p->nCol<1) ) return;
1114 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001115}
1116
1117/*
danielk197752a83fb2005-01-31 12:56:44 +00001118** Scan the column type name zType (length nType) and return the
1119** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001120**
1121** This routine does a case-independent search of zType for the
1122** substrings in the following table. If one of the substrings is
1123** found, the corresponding affinity is returned. If zType contains
1124** more than one of the substrings, entries toward the top of
1125** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001126** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001127**
1128** Substring | Affinity
1129** --------------------------------
1130** 'INT' | SQLITE_AFF_INTEGER
1131** 'CHAR' | SQLITE_AFF_TEXT
1132** 'CLOB' | SQLITE_AFF_TEXT
1133** 'TEXT' | SQLITE_AFF_TEXT
drh05883a32015-06-02 15:32:08 +00001134** 'BLOB' | SQLITE_AFF_BLOB
drh8a512562005-11-14 22:29:05 +00001135** 'REAL' | SQLITE_AFF_REAL
1136** 'FLOA' | SQLITE_AFF_REAL
1137** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001138**
1139** If none of the substrings in the above table are found,
1140** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001141*/
drhfdaac672013-10-04 15:30:21 +00001142char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001143 u32 h = 0;
1144 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001145 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001146
drhfdaac672013-10-04 15:30:21 +00001147 if( zIn==0 ) return aff;
1148 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001149 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001150 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001151 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001152 aff = SQLITE_AFF_TEXT;
1153 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001154 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1155 aff = SQLITE_AFF_TEXT;
1156 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1157 aff = SQLITE_AFF_TEXT;
1158 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001159 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
drh05883a32015-06-02 15:32:08 +00001160 aff = SQLITE_AFF_BLOB;
drhd3037a42013-10-04 18:29:25 +00001161 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001162#ifndef SQLITE_OMIT_FLOATING_POINT
1163 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1164 && aff==SQLITE_AFF_NUMERIC ){
1165 aff = SQLITE_AFF_REAL;
1166 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1167 && aff==SQLITE_AFF_NUMERIC ){
1168 aff = SQLITE_AFF_REAL;
1169 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1170 && aff==SQLITE_AFF_NUMERIC ){
1171 aff = SQLITE_AFF_REAL;
1172#endif
danielk1977201f7162005-02-01 02:13:29 +00001173 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001174 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001175 break;
danielk197752a83fb2005-01-31 12:56:44 +00001176 }
1177 }
drhd3037a42013-10-04 18:29:25 +00001178
1179 /* If pszEst is not NULL, store an estimate of the field size. The
1180 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001181 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001182 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001183 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001184 if( zChar ){
1185 while( zChar[0] ){
1186 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001187 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001188 sqlite3GetInt32(zChar, &v);
1189 v = v/4 + 1;
1190 if( v>255 ) v = 255;
1191 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1192 break;
1193 }
1194 zChar++;
drhfdaac672013-10-04 15:30:21 +00001195 }
drhd3037a42013-10-04 18:29:25 +00001196 }else{
1197 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001198 }
drhfdaac672013-10-04 15:30:21 +00001199 }
1200 }
danielk1977b3dff962005-02-01 01:21:55 +00001201 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001202}
1203
1204/*
drh382c0242001-10-06 16:33:02 +00001205** This routine is called by the parser while in the middle of
1206** parsing a CREATE TABLE statement. The pFirst token is the first
1207** token in the sequence of tokens that describe the type of the
1208** column currently under construction. pLast is the last token
1209** in the sequence. Use this information to construct a string
1210** that contains the typename of the column and store that string
1211** in zType.
1212*/
drh487e2622005-06-25 18:42:14 +00001213void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001214 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001215 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001216
drhc4a64fa2009-05-11 20:53:28 +00001217 p = pParse->pNewTable;
1218 if( p==0 || NEVER(p->nCol<1) ) return;
1219 pCol = &p->aCol[p->nCol-1];
drh5f1d2fa2015-04-19 21:59:19 +00001220 assert( pCol->zType==0 || CORRUPT_DB );
1221 sqlite3DbFree(pParse->db, pCol->zType);
drhc4a64fa2009-05-11 20:53:28 +00001222 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001223 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001224}
1225
1226/*
danielk19777977a172004-11-09 12:44:37 +00001227** The expression is the default value for the most recently added column
1228** of the table currently under construction.
1229**
1230** Default value expressions must be constant. Raise an exception if this
1231** is not the case.
drhd9b02572001-04-15 00:37:09 +00001232**
1233** This routine is called by the parser while in the middle of
1234** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001235*/
drhb7916a72009-05-27 10:31:29 +00001236void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001237 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001238 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001239 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001240 p = pParse->pNewTable;
1241 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001242 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001243 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001244 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1245 pCol->zName);
1246 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001247 /* A copy of pExpr is used instead of the original, as pExpr contains
1248 ** tokens that point to volatile memory. The 'span' of the expression
1249 ** is required by pragma table_info.
1250 */
drh633e6d52008-07-28 19:34:53 +00001251 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001252 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1253 sqlite3DbFree(db, pCol->zDflt);
1254 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001255 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001256 }
danielk19777977a172004-11-09 12:44:37 +00001257 }
drhb7916a72009-05-27 10:31:29 +00001258 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001259}
1260
1261/*
drh153110a2015-11-01 21:19:13 +00001262** Backwards Compatibility Hack:
1263**
1264** Historical versions of SQLite accepted strings as column names in
1265** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1266**
1267** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1268** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1269**
1270** This is goofy. But to preserve backwards compatibility we continue to
1271** accept it. This routine does the necessary conversion. It converts
1272** the expression given in its argument from a TK_STRING into a TK_ID
1273** if the expression is just a TK_STRING with an optional COLLATE clause.
1274** If the epxression is anything other than TK_STRING, the expression is
1275** unchanged.
1276*/
1277static void sqlite3StringToId(Expr *p){
1278 if( p->op==TK_STRING ){
1279 p->op = TK_ID;
1280 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1281 p->pLeft->op = TK_ID;
1282 }
1283}
1284
1285/*
drh4a324312001-12-21 14:30:42 +00001286** Designate the PRIMARY KEY for the table. pList is a list of names
1287** of columns that form the primary key. If pList is NULL, then the
1288** most recently added column of the table is the primary key.
1289**
1290** A table can have at most one primary key. If the table already has
1291** a primary key (and this is the second primary key) then create an
1292** error.
1293**
1294** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001295** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001296** field of the table under construction to be the index of the
1297** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1298** no INTEGER PRIMARY KEY.
1299**
1300** If the key is not an INTEGER PRIMARY KEY, then create a unique
1301** index for the key. No index is created for INTEGER PRIMARY KEYs.
1302*/
drh205f48e2004-11-05 00:43:11 +00001303void sqlite3AddPrimaryKey(
1304 Parse *pParse, /* Parsing context */
1305 ExprList *pList, /* List of field names to be indexed */
1306 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001307 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1308 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001309){
drh4a324312001-12-21 14:30:42 +00001310 Table *pTab = pParse->pNewTable;
1311 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001312 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001313 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001314 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001315 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001316 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001317 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001318 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001319 }
drh7d10d5a2008-08-20 16:35:10 +00001320 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001321 if( pList==0 ){
1322 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001323 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001324 zType = pTab->aCol[iCol].zType;
1325 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001326 }else{
drh8ea30bf2013-10-22 01:18:17 +00001327 nTerm = pList->nExpr;
1328 for(i=0; i<nTerm; i++){
drh108aa002015-08-24 20:21:20 +00001329 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drh7d3d9da2015-09-01 00:42:52 +00001330 assert( pCExpr!=0 );
drh153110a2015-11-01 21:19:13 +00001331 sqlite3StringToId(pCExpr);
drh7d3d9da2015-09-01 00:42:52 +00001332 if( pCExpr->op==TK_ID ){
drh108aa002015-08-24 20:21:20 +00001333 const char *zCName = pCExpr->u.zToken;
1334 for(iCol=0; iCol<pTab->nCol; iCol++){
1335 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1336 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1337 zType = pTab->aCol[iCol].zType;
1338 break;
1339 }
drhd3d39e92004-05-20 22:16:29 +00001340 }
drh78100cc2003-08-23 22:40:53 +00001341 }
drh4a324312001-12-21 14:30:42 +00001342 }
1343 }
drh8ea30bf2013-10-22 01:18:17 +00001344 if( nTerm==1
1345 && zType && sqlite3StrICmp(zType, "INTEGER")==0
drhbc622bc2015-08-24 15:39:42 +00001346 && sortOrder!=SQLITE_SO_DESC
drh8ea30bf2013-10-22 01:18:17 +00001347 ){
drh4a324312001-12-21 14:30:42 +00001348 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001349 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001350 assert( autoInc==0 || autoInc==1 );
1351 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001352 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001353 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001354#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001355 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1356 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001357#endif
drh4a324312001-12-21 14:30:42 +00001358 }else{
dan1da40a32009-09-19 17:00:31 +00001359 Index *p;
drh8a9789b2013-08-01 03:36:59 +00001360 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001361 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001362 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001363 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
dan1da40a32009-09-19 17:00:31 +00001364 }
drhe0194f22003-02-26 13:52:51 +00001365 pList = 0;
drh4a324312001-12-21 14:30:42 +00001366 }
drhe0194f22003-02-26 13:52:51 +00001367
1368primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001369 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001370 return;
drh4a324312001-12-21 14:30:42 +00001371}
1372
1373/*
drhffe07b22005-11-03 00:41:17 +00001374** Add a new CHECK constraint to the table currently under construction.
1375*/
1376void sqlite3AddCheckConstraint(
1377 Parse *pParse, /* Parsing context */
1378 Expr *pCheckExpr /* The check expression */
1379){
1380#ifndef SQLITE_OMIT_CHECK
1381 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001382 sqlite3 *db = pParse->db;
1383 if( pTab && !IN_DECLARE_VTAB
1384 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1385 ){
drh2938f922012-03-07 19:13:29 +00001386 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1387 if( pParse->constraintName.n ){
1388 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1389 }
drh33e619f2009-05-28 01:00:55 +00001390 }else
drhffe07b22005-11-03 00:41:17 +00001391#endif
drh33e619f2009-05-28 01:00:55 +00001392 {
drh2938f922012-03-07 19:13:29 +00001393 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001394 }
drhffe07b22005-11-03 00:41:17 +00001395}
1396
1397/*
drhd3d39e92004-05-20 22:16:29 +00001398** Set the collation function of the most recently parsed table column
1399** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001400*/
danielk197739002502007-11-12 09:50:26 +00001401void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001402 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001403 int i;
danielk197739002502007-11-12 09:50:26 +00001404 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001405 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001406
danielk1977b8cbb872006-06-19 05:33:45 +00001407 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001408 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001409 db = pParse->db;
1410 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001411 if( !zColl ) return;
1412
drhc4a64fa2009-05-11 20:53:28 +00001413 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001414 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001415 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001416 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001417
1418 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1419 ** then an index may have been created on this column before the
1420 ** collation type was added. Correct this if it is the case.
1421 */
1422 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001423 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001424 if( pIdx->aiColumn[0]==i ){
1425 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001426 }
1427 }
danielk197739002502007-11-12 09:50:26 +00001428 }else{
drh633e6d52008-07-28 19:34:53 +00001429 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001430 }
danielk19777cedc8d2004-06-10 10:50:08 +00001431}
1432
danielk1977466be562004-06-10 02:16:01 +00001433/*
1434** This function returns the collation sequence for database native text
1435** encoding identified by the string zName, length nName.
1436**
1437** If the requested collation sequence is not available, or not available
1438** in the database native encoding, the collation factory is invoked to
1439** request it. If the collation factory does not supply such a sequence,
1440** and the sequence is available in another text encoding, then that is
1441** returned instead.
1442**
1443** If no versions of the requested collations sequence are available, or
1444** another error occurs, NULL is returned and an error message written into
1445** pParse.
drha34001c2007-02-02 12:44:37 +00001446**
1447** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1448** invokes the collation factory if the named collation cannot be found
1449** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001450**
1451** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001452*/
drhc4a64fa2009-05-11 20:53:28 +00001453CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001454 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001455 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001456 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001457 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001458
drhc4a64fa2009-05-11 20:53:28 +00001459 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001460 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001461 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001462 }
1463
danielk19770202b292004-06-09 09:55:16 +00001464 return pColl;
1465}
1466
1467
drh8e2ca022002-06-17 17:07:19 +00001468/*
drh3f7d4e42004-07-24 14:35:58 +00001469** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001470**
1471** The schema cookie is used to determine when the schema for the
1472** database changes. After each schema change, the cookie value
1473** changes. When a process first reads the schema it records the
1474** cookie. Thereafter, whenever it goes to access the database,
1475** it checks the cookie to make sure the schema has not changed
1476** since it was last read.
1477**
1478** This plan is not completely bullet-proof. It is possible for
1479** the schema to change multiple times and for the cookie to be
1480** set back to prior value. But schema changes are infrequent
1481** and the probability of hitting the same cookie value is only
1482** 1 chance in 2^32. So we're safe enough.
1483*/
drh9cbf3422008-01-17 16:22:13 +00001484void sqlite3ChangeCookie(Parse *pParse, int iDb){
1485 int r1 = sqlite3GetTempReg(pParse);
1486 sqlite3 *db = pParse->db;
1487 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001488 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001489 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001490 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001491 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001492}
1493
1494/*
drh969fa7c2002-02-18 18:30:32 +00001495** Measure the number of characters needed to output the given
1496** identifier. The number returned includes any quotes used
1497** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001498**
1499** The estimate is conservative. It might be larger that what is
1500** really needed.
drh969fa7c2002-02-18 18:30:32 +00001501*/
1502static int identLength(const char *z){
1503 int n;
drh17f71932002-02-21 12:01:27 +00001504 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001505 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001506 }
drh234c39d2004-07-24 03:30:47 +00001507 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001508}
1509
1510/*
danielk19771b870de2009-03-14 08:37:23 +00001511** The first parameter is a pointer to an output buffer. The second
1512** parameter is a pointer to an integer that contains the offset at
1513** which to write into the output buffer. This function copies the
1514** nul-terminated string pointed to by the third parameter, zSignedIdent,
1515** to the specified offset in the buffer and updates *pIdx to refer
1516** to the first byte after the last byte written before returning.
1517**
1518** If the string zSignedIdent consists entirely of alpha-numeric
1519** characters, does not begin with a digit and is not an SQL keyword,
1520** then it is copied to the output buffer exactly as it is. Otherwise,
1521** it is quoted using double-quotes.
1522*/
drhc4a64fa2009-05-11 20:53:28 +00001523static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001524 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001525 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001526 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001527
drh17f71932002-02-21 12:01:27 +00001528 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001529 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001530 }
drhc7407522014-01-10 20:38:12 +00001531 needQuote = sqlite3Isdigit(zIdent[0])
1532 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1533 || zIdent[j]!=0
1534 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001535
drh234c39d2004-07-24 03:30:47 +00001536 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001537 for(j=0; zIdent[j]; j++){
1538 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001539 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001540 }
drh234c39d2004-07-24 03:30:47 +00001541 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001542 z[i] = 0;
1543 *pIdx = i;
1544}
1545
1546/*
1547** Generate a CREATE TABLE statement appropriate for the given
1548** table. Memory to hold the text of the statement is obtained
1549** from sqliteMalloc() and must be freed by the calling function.
1550*/
drh1d34fde2009-02-03 15:50:33 +00001551static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001552 int i, k, n;
1553 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001554 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001555 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001556 n = 0;
drh234c39d2004-07-24 03:30:47 +00001557 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001558 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001559 }
1560 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001561 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001562 zSep = "";
1563 zSep2 = ",";
1564 zEnd = ")";
1565 }else{
1566 zSep = "\n ";
1567 zSep2 = ",\n ";
1568 zEnd = "\n)";
1569 }
drhe0bc4042002-06-25 01:09:11 +00001570 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001571 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001572 if( zStmt==0 ){
1573 db->mallocFailed = 1;
1574 return 0;
1575 }
drhbdb339f2009-02-02 18:03:21 +00001576 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001577 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001578 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001579 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001580 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001581 static const char * const azType[] = {
drh05883a32015-06-02 15:32:08 +00001582 /* SQLITE_AFF_BLOB */ "",
drh7ea31cc2014-09-18 14:36:00 +00001583 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001584 /* SQLITE_AFF_NUMERIC */ " NUM",
1585 /* SQLITE_AFF_INTEGER */ " INT",
1586 /* SQLITE_AFF_REAL */ " REAL"
1587 };
1588 int len;
1589 const char *zType;
1590
drh5bb3eb92007-05-04 13:15:55 +00001591 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001592 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001593 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001594 identPut(zStmt, &k, pCol->zName);
drh05883a32015-06-02 15:32:08 +00001595 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1596 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1597 testcase( pCol->affinity==SQLITE_AFF_BLOB );
drh7ea31cc2014-09-18 14:36:00 +00001598 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001599 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1600 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1601 testcase( pCol->affinity==SQLITE_AFF_REAL );
1602
drh05883a32015-06-02 15:32:08 +00001603 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
drhc4a64fa2009-05-11 20:53:28 +00001604 len = sqlite3Strlen30(zType);
drh05883a32015-06-02 15:32:08 +00001605 assert( pCol->affinity==SQLITE_AFF_BLOB
drhfdaac672013-10-04 15:30:21 +00001606 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001607 memcpy(&zStmt[k], zType, len);
1608 k += len;
1609 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001610 }
drh5bb3eb92007-05-04 13:15:55 +00001611 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001612 return zStmt;
1613}
1614
1615/*
drh7f9c5db2013-10-23 00:32:58 +00001616** Resize an Index object to hold N columns total. Return SQLITE_OK
1617** on success and SQLITE_NOMEM on an OOM error.
1618*/
1619static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1620 char *zExtra;
1621 int nByte;
1622 if( pIdx->nColumn>=N ) return SQLITE_OK;
1623 assert( pIdx->isResized==0 );
1624 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1625 zExtra = sqlite3DbMallocZero(db, nByte);
1626 if( zExtra==0 ) return SQLITE_NOMEM;
1627 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1628 pIdx->azColl = (char**)zExtra;
1629 zExtra += sizeof(char*)*N;
1630 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1631 pIdx->aiColumn = (i16*)zExtra;
1632 zExtra += sizeof(i16)*N;
1633 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1634 pIdx->aSortOrder = (u8*)zExtra;
1635 pIdx->nColumn = N;
1636 pIdx->isResized = 1;
1637 return SQLITE_OK;
1638}
1639
1640/*
drhfdaac672013-10-04 15:30:21 +00001641** Estimate the total row width for a table.
1642*/
drhe13e9f52013-10-05 19:18:00 +00001643static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001644 unsigned wTable = 0;
1645 const Column *pTabCol;
1646 int i;
1647 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1648 wTable += pTabCol->szEst;
1649 }
1650 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001651 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001652}
1653
1654/*
drhe13e9f52013-10-05 19:18:00 +00001655** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001656*/
drhe13e9f52013-10-05 19:18:00 +00001657static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001658 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001659 int i;
1660 const Column *aCol = pIdx->pTable->aCol;
1661 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001662 i16 x = pIdx->aiColumn[i];
1663 assert( x<pIdx->pTable->nCol );
1664 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001665 }
drhe13e9f52013-10-05 19:18:00 +00001666 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001667}
1668
drh7f9c5db2013-10-23 00:32:58 +00001669/* Return true if value x is found any of the first nCol entries of aiCol[]
1670*/
1671static int hasColumn(const i16 *aiCol, int nCol, int x){
1672 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1673 return 0;
1674}
1675
1676/*
drhc6bd4e42013-11-02 14:37:18 +00001677** This routine runs at the end of parsing a CREATE TABLE statement that
1678** has a WITHOUT ROWID clause. The job of this routine is to convert both
1679** internal schema data structures and the generated VDBE code so that they
1680** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1681** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001682**
drhc6bd4e42013-11-02 14:37:18 +00001683** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1684** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1685** data storage is a covering index btree.
1686** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001687** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001688** identified by the sqlite_master table entry of the table itself.
1689** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1690** schema to the rootpage from the main table.
1691** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1692** (5) Add all table columns to the PRIMARY KEY Index object
1693** so that the PRIMARY KEY is a covering index. The surplus
1694** columns are part of KeyInfo.nXField and are not used for
1695** sorting or lookup or uniqueness checks.
1696** (6) Replace the rowid tail on all automatically generated UNIQUE
1697** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001698*/
1699static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1700 Index *pIdx;
1701 Index *pPk;
1702 int nPk;
1703 int i, j;
1704 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001705 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001706
1707 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001708 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001709 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001710 */
1711 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001712 assert( v );
drh0ff287f2015-09-02 18:40:33 +00001713 sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
drhc6bd4e42013-11-02 14:37:18 +00001714 }
1715
drh7f9c5db2013-10-23 00:32:58 +00001716 /* Locate the PRIMARY KEY index. Or, if this table was originally
1717 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1718 */
1719 if( pTab->iPKey>=0 ){
1720 ExprList *pList;
drh108aa002015-08-24 20:21:20 +00001721 Token ipkToken;
1722 ipkToken.z = pTab->aCol[pTab->iPKey].zName;
1723 ipkToken.n = sqlite3Strlen30(ipkToken.z);
1724 pList = sqlite3ExprListAppend(pParse, 0,
1725 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
drh7f9c5db2013-10-23 00:32:58 +00001726 if( pList==0 ) return;
drh7f9c5db2013-10-23 00:32:58 +00001727 pList->a[0].sortOrder = pParse->iPkSortOrder;
1728 assert( pParse->pNewTable==pTab );
1729 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1730 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001731 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001732 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001733 }else{
1734 pPk = sqlite3PrimaryKeyIndex(pTab);
danc5b73582015-05-26 11:53:14 +00001735
1736 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1737 ** table entry. This is only required if currently generating VDBE
1738 ** code for a CREATE TABLE (not when parsing one as part of reading
1739 ** a database schema). */
1740 if( v ){
1741 assert( db->init.busy==0 );
drh0ff287f2015-09-02 18:40:33 +00001742 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
danc5b73582015-05-26 11:53:14 +00001743 }
1744
drhe385d882014-12-28 22:10:51 +00001745 /*
1746 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1747 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1748 ** code assumes the PRIMARY KEY contains no repeated columns.
1749 */
1750 for(i=j=1; i<pPk->nKeyCol; i++){
1751 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
1752 pPk->nColumn--;
1753 }else{
1754 pPk->aiColumn[j++] = pPk->aiColumn[i];
1755 }
1756 }
1757 pPk->nKeyCol = j;
drh7f9c5db2013-10-23 00:32:58 +00001758 }
drh12826092013-11-05 22:39:17 +00001759 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001760 assert( pPk!=0 );
1761 nPk = pPk->nKeyCol;
1762
drh1ffede82015-01-30 20:59:27 +00001763 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
1764 ** do not enforce this for imposter tables.) */
1765 if( !db->init.imposterTable ){
1766 for(i=0; i<nPk; i++){
1767 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1768 }
1769 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001770 }
1771
drhc6bd4e42013-11-02 14:37:18 +00001772 /* The root page of the PRIMARY KEY is the table root page */
1773 pPk->tnum = pTab->tnum;
1774
drh7f9c5db2013-10-23 00:32:58 +00001775 /* Update the in-memory representation of all UNIQUE indices by converting
1776 ** the final rowid column into one or more columns of the PRIMARY KEY.
1777 */
1778 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1779 int n;
drh48dd1d82014-05-27 18:18:58 +00001780 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001781 for(i=n=0; i<nPk; i++){
1782 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1783 }
drh5a9a37b2013-11-05 17:30:04 +00001784 if( n==0 ){
1785 /* This index is a superset of the primary key */
1786 pIdx->nColumn = pIdx->nKeyCol;
1787 continue;
1788 }
drh7f9c5db2013-10-23 00:32:58 +00001789 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1790 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001791 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001792 pIdx->aiColumn[j] = pPk->aiColumn[i];
1793 pIdx->azColl[j] = pPk->azColl[i];
1794 j++;
1795 }
1796 }
drh00012df2013-11-05 01:59:07 +00001797 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1798 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001799 }
1800
1801 /* Add all table columns to the PRIMARY KEY index
1802 */
1803 if( nPk<pTab->nCol ){
1804 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1805 for(i=0, j=nPk; i<pTab->nCol; i++){
1806 if( !hasColumn(pPk->aiColumn, j, i) ){
1807 assert( j<pPk->nColumn );
1808 pPk->aiColumn[j] = i;
1809 pPk->azColl[j] = "BINARY";
1810 j++;
1811 }
1812 }
1813 assert( pPk->nColumn==j );
1814 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001815 }else{
1816 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001817 }
1818}
1819
drhfdaac672013-10-04 15:30:21 +00001820/*
drh75897232000-05-29 14:26:00 +00001821** This routine is called to report the final ")" that terminates
1822** a CREATE TABLE statement.
1823**
drhf57b3392001-10-08 13:22:32 +00001824** The table structure that other action routines have been building
1825** is added to the internal hash tables, assuming no errors have
1826** occurred.
drh75897232000-05-29 14:26:00 +00001827**
drh1d85d932004-02-14 23:05:52 +00001828** An entry for the table is made in the master table on disk, unless
1829** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001830** it means we are reading the sqlite_master table because we just
1831** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001832** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001833** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001834**
1835** If the pSelect argument is not NULL, it means that this routine
1836** was called to create a table generated from a
1837** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1838** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001839*/
danielk197719a8e7e2005-03-17 05:03:38 +00001840void sqlite3EndTable(
1841 Parse *pParse, /* Parse context */
1842 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001843 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1844 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001845 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1846){
drhfdaac672013-10-04 15:30:21 +00001847 Table *p; /* The new table */
1848 sqlite3 *db = pParse->db; /* The database connection */
1849 int iDb; /* Database in which the table lives */
1850 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001851
drh027616d2015-08-08 22:47:47 +00001852 if( pEnd==0 && pSelect==0 ){
drh5969da42013-10-21 02:14:45 +00001853 return;
danielk1977261919c2005-12-06 12:52:59 +00001854 }
drh834f9972015-08-08 23:23:33 +00001855 assert( !db->mallocFailed );
drh28037572000-08-02 13:47:41 +00001856 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001857 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001858
danielk1977517eb642004-06-07 10:00:31 +00001859 assert( !db->init.busy || !pSelect );
1860
drhc6bd4e42013-11-02 14:37:18 +00001861 /* If the db->init.busy is 1 it means we are reading the SQL off the
1862 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1863 ** So do not write to the disk again. Extract the root page number
1864 ** for the table from the db->init.newTnum field. (The page number
1865 ** should have been put there by the sqliteOpenCb routine.)
1866 */
1867 if( db->init.busy ){
1868 p->tnum = db->init.newTnum;
1869 }
1870
1871 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001872 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001873 if( (p->tabFlags & TF_Autoincrement) ){
1874 sqlite3ErrorMsg(pParse,
1875 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1876 return;
1877 }
drh5969da42013-10-21 02:14:45 +00001878 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001879 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001880 }else{
drhfccda8a2015-05-27 13:06:55 +00001881 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
drh7f9c5db2013-10-23 00:32:58 +00001882 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001883 }
1884 }
1885
drhb9bb7c12006-06-11 23:41:55 +00001886 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001887
drhffe07b22005-11-03 00:41:17 +00001888#ifndef SQLITE_OMIT_CHECK
1889 /* Resolve names in all CHECK constraint expressions.
1890 */
1891 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001892 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001893 }
1894#endif /* !defined(SQLITE_OMIT_CHECK) */
1895
drhe13e9f52013-10-05 19:18:00 +00001896 /* Estimate the average row size for the table and for all implied indices */
1897 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001898 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001899 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001900 }
1901
drhe3c41372001-09-17 20:25:58 +00001902 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001903 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001904 **
drhe0bc4042002-06-25 01:09:11 +00001905 ** If this is a TEMPORARY table, write the entry into the auxiliary
1906 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001907 */
drh1d85d932004-02-14 23:05:52 +00001908 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001909 int n;
drhd8bc7082000-06-07 23:51:50 +00001910 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001911 char *zType; /* "view" or "table" */
1912 char *zType2; /* "VIEW" or "TABLE" */
1913 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001914
danielk19774adee202004-05-08 08:23:19 +00001915 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001916 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001917
drh66a51672008-01-03 00:01:23 +00001918 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001919
drh0fa991b2009-03-21 16:19:26 +00001920 /*
1921 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001922 */
drh4ff6dfa2002-03-03 23:06:00 +00001923 if( p->pSelect==0 ){
1924 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001925 zType = "table";
1926 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001927#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001928 }else{
1929 /* A view */
drh4794f732004-11-05 17:17:50 +00001930 zType = "view";
1931 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001932#endif
drh4ff6dfa2002-03-03 23:06:00 +00001933 }
danielk1977517eb642004-06-07 10:00:31 +00001934
danielk1977517eb642004-06-07 10:00:31 +00001935 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1936 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001937 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001938 **
1939 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1940 ** suitable state to query for the column names and types to be used
1941 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001942 **
1943 ** A shared-cache write-lock is not required to write to the new table,
1944 ** as a schema-lock must have already been obtained to create it. Since
1945 ** a schema-lock excludes all other database users, the write-lock would
1946 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001947 */
1948 if( pSelect ){
drh92632202015-05-20 17:18:29 +00001949 SelectDest dest; /* Where the SELECT should store results */
drh9df25c42015-05-20 15:51:09 +00001950 int regYield; /* Register holding co-routine entry-point */
1951 int addrTop; /* Top of the co-routine */
drh92632202015-05-20 17:18:29 +00001952 int regRec; /* A record to be insert into the new table */
1953 int regRowid; /* Rowid of the next row to insert */
1954 int addrInsLoop; /* Top of the loop for inserting rows */
1955 Table *pSelTab; /* A table that describes the SELECT results */
drh1013c932008-01-06 00:25:21 +00001956
drh9df25c42015-05-20 15:51:09 +00001957 regYield = ++pParse->nMem;
drh92632202015-05-20 17:18:29 +00001958 regRec = ++pParse->nMem;
1959 regRowid = ++pParse->nMem;
danielk19776ab3a2e2009-02-19 14:39:25 +00001960 assert(pParse->nTab==1);
drh0dd5cda2015-06-16 16:39:01 +00001961 sqlite3MayAbort(pParse);
drhb7654112008-01-12 12:48:07 +00001962 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001963 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001964 pParse->nTab = 2;
drh9df25c42015-05-20 15:51:09 +00001965 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1966 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1967 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
drh7d10d5a2008-08-20 16:35:10 +00001968 sqlite3Select(pParse, pSelect, &dest);
drh9df25c42015-05-20 15:51:09 +00001969 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
1970 sqlite3VdbeJumpHere(v, addrTop - 1);
drh92632202015-05-20 17:18:29 +00001971 if( pParse->nErr ) return;
1972 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1973 if( pSelTab==0 ) return;
1974 assert( p->aCol==0 );
1975 p->nCol = pSelTab->nCol;
1976 p->aCol = pSelTab->aCol;
1977 pSelTab->nCol = 0;
1978 pSelTab->aCol = 0;
1979 sqlite3DeleteTable(db, pSelTab);
1980 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1981 VdbeCoverage(v);
1982 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
1983 sqlite3TableAffinity(v, p, 0);
1984 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
1985 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
drh076e85f2015-09-03 13:46:12 +00001986 sqlite3VdbeGoto(v, addrInsLoop);
drh92632202015-05-20 17:18:29 +00001987 sqlite3VdbeJumpHere(v, addrInsLoop);
1988 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001989 }
drh4794f732004-11-05 17:17:50 +00001990
drh4794f732004-11-05 17:17:50 +00001991 /* Compute the complete text of the CREATE statement */
1992 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001993 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001994 }else{
drh8ea30bf2013-10-22 01:18:17 +00001995 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1996 n = (int)(pEnd2->z - pParse->sNameToken.z);
1997 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001998 zStmt = sqlite3MPrintf(db,
1999 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
2000 );
drh4794f732004-11-05 17:17:50 +00002001 }
2002
2003 /* A slot for the record has already been allocated in the
2004 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00002005 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00002006 */
2007 sqlite3NestedParse(pParse,
2008 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00002009 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
2010 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00002011 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00002012 zType,
2013 p->zName,
2014 p->zName,
drhb7654112008-01-12 12:48:07 +00002015 pParse->regRoot,
2016 zStmt,
2017 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00002018 );
drh633e6d52008-07-28 19:34:53 +00002019 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00002020 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00002021
2022#ifndef SQLITE_OMIT_AUTOINCREMENT
2023 /* Check to see if we need to create an sqlite_sequence table for
2024 ** keeping track of autoincrement keys.
2025 */
drh7d10d5a2008-08-20 16:35:10 +00002026 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00002027 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00002028 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00002029 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00002030 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00002031 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2032 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00002033 );
2034 }
2035 }
2036#endif
drh4794f732004-11-05 17:17:50 +00002037
2038 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00002039 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00002040 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00002041 }
drh17e9e292003-02-01 13:53:28 +00002042
drh2958a4e2004-11-12 03:56:15 +00002043
drh17e9e292003-02-01 13:53:28 +00002044 /* Add the table to the in-memory representation of the database.
2045 */
drh8af73d42009-05-13 22:58:28 +00002046 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00002047 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00002048 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00002049 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00002050 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00002051 if( pOld ){
2052 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00002053 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00002054 return;
drh17e9e292003-02-01 13:53:28 +00002055 }
drh17e9e292003-02-01 13:53:28 +00002056 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00002057 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00002058
2059#ifndef SQLITE_OMIT_ALTERTABLE
2060 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00002061 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00002062 int nName;
drh5969da42013-10-21 02:14:45 +00002063 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00002064 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002065 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002066 }
drh1bd10f82008-12-10 21:19:56 +00002067 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002068 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002069 }
2070#endif
drh17e9e292003-02-01 13:53:28 +00002071 }
drh75897232000-05-29 14:26:00 +00002072}
2073
drhb7f91642004-10-31 02:22:47 +00002074#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002075/*
drha76b5df2002-02-23 02:32:10 +00002076** The parser calls this routine in order to create a new VIEW
2077*/
danielk19774adee202004-05-08 08:23:19 +00002078void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002079 Parse *pParse, /* The parsing context */
2080 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002081 Token *pName1, /* The token that holds the name of the view */
2082 Token *pName2, /* The token that holds the name of the view */
drh8981b902015-08-24 17:42:49 +00002083 ExprList *pCNames, /* Optional list of view column names */
drh6276c1c2002-07-08 22:03:32 +00002084 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002085 int isTemp, /* TRUE for a TEMPORARY view */
2086 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002087){
drha76b5df2002-02-23 02:32:10 +00002088 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002089 int n;
drhb7916a72009-05-27 10:31:29 +00002090 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002091 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002092 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002093 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002094 int iDb;
drh17435752007-08-16 04:30:38 +00002095 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002096
drh7c3d64f2005-06-06 15:32:08 +00002097 if( pParse->nVar>0 ){
2098 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh32498f12015-09-26 11:15:44 +00002099 goto create_view_fail;
drh7c3d64f2005-06-06 15:32:08 +00002100 }
drhfdd48a72006-09-11 23:45:48 +00002101 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002102 p = pParse->pNewTable;
drh8981b902015-08-24 17:42:49 +00002103 if( p==0 || pParse->nErr ) goto create_view_fail;
danielk1977ef2cb632004-05-29 02:37:19 +00002104 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002105 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002106 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
drh8981b902015-08-24 17:42:49 +00002107 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
drh174b6192002-12-03 02:22:52 +00002108
drh4b59ab52002-08-24 18:24:51 +00002109 /* Make a copy of the entire SELECT statement that defines the view.
2110 ** This will force all the Expr.token.z values to be dynamically
2111 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002112 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002113 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002114 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh8981b902015-08-24 17:42:49 +00002115 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2116 if( db->mallocFailed ) goto create_view_fail;
drh4b59ab52002-08-24 18:24:51 +00002117
2118 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2119 ** the end.
2120 */
drha76b5df2002-02-23 02:32:10 +00002121 sEnd = pParse->sLastToken;
drh8981b902015-08-24 17:42:49 +00002122 assert( sEnd.z[0]!=0 );
2123 if( sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002124 sEnd.z += sEnd.n;
2125 }
2126 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002127 n = (int)(sEnd.z - pBegin->z);
drh8981b902015-08-24 17:42:49 +00002128 assert( n>0 );
drhb7916a72009-05-27 10:31:29 +00002129 z = pBegin->z;
drh8981b902015-08-24 17:42:49 +00002130 while( sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002131 sEnd.z = &z[n-1];
2132 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002133
danielk19774adee202004-05-08 08:23:19 +00002134 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002135 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drh8981b902015-08-24 17:42:49 +00002136
2137create_view_fail:
2138 sqlite3SelectDelete(db, pSelect);
2139 sqlite3ExprListDelete(db, pCNames);
drha76b5df2002-02-23 02:32:10 +00002140 return;
drh417be792002-03-03 18:59:40 +00002141}
drhb7f91642004-10-31 02:22:47 +00002142#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002143
danielk1977fe3fcbe22006-06-12 12:08:45 +00002144#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002145/*
2146** The Table structure pTable is really a VIEW. Fill in the names of
2147** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002148** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002149*/
danielk19774adee202004-05-08 08:23:19 +00002150int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002151 Table *pSelTab; /* A fake table from which we get the result set */
2152 Select *pSel; /* Copy of the SELECT that implements the view */
2153 int nErr = 0; /* Number of errors encountered */
2154 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002155 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002156 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh8981b902015-08-24 17:42:49 +00002157 u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */
drh417be792002-03-03 18:59:40 +00002158
2159 assert( pTable );
2160
danielk1977fe3fcbe22006-06-12 12:08:45 +00002161#ifndef SQLITE_OMIT_VIRTUALTABLE
2162 if( sqlite3VtabCallConnect(pParse, pTable) ){
2163 return SQLITE_ERROR;
2164 }
drh4cbdda92006-06-14 19:00:20 +00002165 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002166#endif
2167
2168#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002169 /* A positive nCol means the columns names for this view are
2170 ** already known.
2171 */
2172 if( pTable->nCol>0 ) return 0;
2173
2174 /* A negative nCol is a special marker meaning that we are currently
2175 ** trying to compute the column names. If we enter this routine with
2176 ** a negative nCol, it means two or more views form a loop, like this:
2177 **
2178 ** CREATE VIEW one AS SELECT * FROM two;
2179 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002180 **
drh768578e2009-05-12 00:40:12 +00002181 ** Actually, the error above is now caught prior to reaching this point.
2182 ** But the following test is still important as it does come up
2183 ** in the following:
2184 **
2185 ** CREATE TABLE main.ex1(a);
2186 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2187 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002188 */
2189 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002190 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002191 return 1;
2192 }
drh85c23c62005-08-20 03:03:04 +00002193 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002194
2195 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002196 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2197 ** "*" elements in the results set of the view and will assign cursors
2198 ** to the elements of the FROM clause. But we do not want these changes
2199 ** to be permanent. So the computation is done on a copy of the SELECT
2200 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002201 */
drh9b3187e2005-01-18 14:45:47 +00002202 assert( pTable->pSelect );
drh8981b902015-08-24 17:42:49 +00002203 bEnabledLA = db->lookaside.bEnabled;
2204 if( pTable->pCheck ){
drhd9da78a2009-03-24 15:08:09 +00002205 db->lookaside.bEnabled = 0;
drh8981b902015-08-24 17:42:49 +00002206 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2207 &pTable->nCol, &pTable->aCol);
2208 }else{
2209 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2210 if( pSel ){
2211 n = pParse->nTab;
2212 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2213 pTable->nCol = -1;
2214 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002215#ifndef SQLITE_OMIT_AUTHORIZATION
drh8981b902015-08-24 17:42:49 +00002216 xAuth = db->xAuth;
2217 db->xAuth = 0;
2218 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2219 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002220#else
drh8981b902015-08-24 17:42:49 +00002221 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002222#endif
drh8981b902015-08-24 17:42:49 +00002223 pParse->nTab = n;
2224 if( pSelTab ){
2225 assert( pTable->aCol==0 );
2226 pTable->nCol = pSelTab->nCol;
2227 pTable->aCol = pSelTab->aCol;
2228 pSelTab->nCol = 0;
2229 pSelTab->aCol = 0;
2230 sqlite3DeleteTable(db, pSelTab);
2231 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2232 }else{
2233 pTable->nCol = 0;
2234 nErr++;
2235 }
2236 sqlite3SelectDelete(db, pSel);
2237 } else {
danielk1977261919c2005-12-06 12:52:59 +00002238 nErr++;
2239 }
drh417be792002-03-03 18:59:40 +00002240 }
drh8981b902015-08-24 17:42:49 +00002241 db->lookaside.bEnabled = bEnabledLA;
2242 pTable->pSchema->schemaFlags |= DB_UnresetViews;
drhb7f91642004-10-31 02:22:47 +00002243#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002244 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002245}
2246#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002247
drhb7f91642004-10-31 02:22:47 +00002248#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002249/*
drh8bf8dc92003-05-17 17:35:10 +00002250** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002251*/
drh9bb575f2004-09-06 17:24:11 +00002252static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002253 HashElem *i;
drh21206082011-04-04 18:22:02 +00002254 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002255 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002256 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002257 Table *pTab = sqliteHashData(i);
2258 if( pTab->pSelect ){
drh51be3872015-08-19 02:32:25 +00002259 sqlite3DeleteColumnNames(db, pTab);
dand46def72010-07-24 11:28:28 +00002260 pTab->aCol = 0;
2261 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002262 }
2263 }
drh8bf8dc92003-05-17 17:35:10 +00002264 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002265}
drhb7f91642004-10-31 02:22:47 +00002266#else
2267# define sqliteViewResetAll(A,B)
2268#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002269
drh75897232000-05-29 14:26:00 +00002270/*
danielk1977a0bf2652004-11-04 14:30:04 +00002271** This function is called by the VDBE to adjust the internal schema
2272** used by SQLite when the btree layer moves a table root page. The
2273** root-page of a table or index in database iDb has changed from iFrom
2274** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002275**
2276** Ticket #1728: The symbol table might still contain information
2277** on tables and/or indices that are the process of being deleted.
2278** If you are unlucky, one of those deleted indices or tables might
2279** have the same rootpage number as the real table or index that is
2280** being moved. So we cannot stop searching after the first match
2281** because the first match might be for one of the deleted indices
2282** or tables and not the table/index that is actually being moved.
2283** We must continue looping until all tables and indices with
2284** rootpage==iFrom have been converted to have a rootpage of iTo
2285** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002286*/
2287#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002288void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002289 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002290 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002291 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002292
drhcdf011d2011-04-04 21:25:28 +00002293 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2294 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002295 pHash = &pDb->pSchema->tblHash;
2296 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002297 Table *pTab = sqliteHashData(pElem);
2298 if( pTab->tnum==iFrom ){
2299 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002300 }
2301 }
danielk1977da184232006-01-05 11:34:32 +00002302 pHash = &pDb->pSchema->idxHash;
2303 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002304 Index *pIdx = sqliteHashData(pElem);
2305 if( pIdx->tnum==iFrom ){
2306 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002307 }
2308 }
danielk1977a0bf2652004-11-04 14:30:04 +00002309}
2310#endif
2311
2312/*
2313** Write code to erase the table with root-page iTable from database iDb.
2314** Also write code to modify the sqlite_master table and internal schema
2315** if a root-page of another table is moved by the btree-layer whilst
2316** erasing iTable (this can happen with an auto-vacuum database).
2317*/
drh4e0cff62004-11-05 05:10:28 +00002318static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2319 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002320 int r1 = sqlite3GetTempReg(pParse);
2321 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002322 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002323#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002324 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002325 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002326 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002327 ** reflect this.
2328 **
drh0fa991b2009-03-21 16:19:26 +00002329 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002330 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2331 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002332 */
danielk197763e3e9f2004-11-05 09:19:27 +00002333 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002334 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2335 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002336#endif
drhb7654112008-01-12 12:48:07 +00002337 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002338}
2339
2340/*
2341** Write VDBE code to erase table pTab and all associated indices on disk.
2342** Code to update the sqlite_master tables and internal schema definitions
2343** in case a root-page belonging to another table is moved by the btree layer
2344** is also added (this can happen with an auto-vacuum database).
2345*/
drh4e0cff62004-11-05 05:10:28 +00002346static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002347#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002348 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002349 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2350 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002351 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002352 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002353 }
2354#else
2355 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2356 ** is not defined), then it is important to call OP_Destroy on the
2357 ** table and index root-pages in order, starting with the numerically
2358 ** largest root-page number. This guarantees that none of the root-pages
2359 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2360 ** following were coded:
2361 **
2362 ** OP_Destroy 4 0
2363 ** ...
2364 ** OP_Destroy 5 0
2365 **
2366 ** and root page 5 happened to be the largest root-page number in the
2367 ** database, then root page 5 would be moved to page 4 by the
2368 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2369 ** a free-list page.
2370 */
2371 int iTab = pTab->tnum;
2372 int iDestroyed = 0;
2373
2374 while( 1 ){
2375 Index *pIdx;
2376 int iLargest = 0;
2377
2378 if( iDestroyed==0 || iTab<iDestroyed ){
2379 iLargest = iTab;
2380 }
2381 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2382 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002383 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002384 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2385 iLargest = iIdx;
2386 }
2387 }
danielk1977da184232006-01-05 11:34:32 +00002388 if( iLargest==0 ){
2389 return;
2390 }else{
2391 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002392 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002393 destroyRootPage(pParse, iLargest, iDb);
2394 iDestroyed = iLargest;
2395 }
danielk1977a0bf2652004-11-04 14:30:04 +00002396 }
2397#endif
2398}
2399
2400/*
drh74e7c8f2011-10-21 19:06:32 +00002401** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002402** after a DROP INDEX or DROP TABLE command.
2403*/
2404static void sqlite3ClearStatTables(
2405 Parse *pParse, /* The parsing context */
2406 int iDb, /* The database number */
2407 const char *zType, /* "idx" or "tbl" */
2408 const char *zName /* Name of index or table */
2409){
drha5ae4c32011-08-07 01:31:52 +00002410 int i;
2411 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002412 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002413 char zTab[24];
2414 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2415 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002416 sqlite3NestedParse(pParse,
2417 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002418 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002419 );
2420 }
2421 }
2422}
2423
2424/*
drhfaacf172011-08-12 01:51:45 +00002425** Generate code to drop a table.
2426*/
2427void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2428 Vdbe *v;
2429 sqlite3 *db = pParse->db;
2430 Trigger *pTrigger;
2431 Db *pDb = &db->aDb[iDb];
2432
2433 v = sqlite3GetVdbe(pParse);
2434 assert( v!=0 );
2435 sqlite3BeginWriteOperation(pParse, 1, iDb);
2436
2437#ifndef SQLITE_OMIT_VIRTUALTABLE
2438 if( IsVirtual(pTab) ){
2439 sqlite3VdbeAddOp0(v, OP_VBegin);
2440 }
2441#endif
2442
2443 /* Drop all triggers associated with the table being dropped. Code
2444 ** is generated to remove entries from sqlite_master and/or
2445 ** sqlite_temp_master if required.
2446 */
2447 pTrigger = sqlite3TriggerList(pParse, pTab);
2448 while( pTrigger ){
2449 assert( pTrigger->pSchema==pTab->pSchema ||
2450 pTrigger->pSchema==db->aDb[1].pSchema );
2451 sqlite3DropTriggerPtr(pParse, pTrigger);
2452 pTrigger = pTrigger->pNext;
2453 }
2454
2455#ifndef SQLITE_OMIT_AUTOINCREMENT
2456 /* Remove any entries of the sqlite_sequence table associated with
2457 ** the table being dropped. This is done before the table is dropped
2458 ** at the btree level, in case the sqlite_sequence table needs to
2459 ** move as a result of the drop (can happen in auto-vacuum mode).
2460 */
2461 if( pTab->tabFlags & TF_Autoincrement ){
2462 sqlite3NestedParse(pParse,
2463 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2464 pDb->zName, pTab->zName
2465 );
2466 }
2467#endif
2468
2469 /* Drop all SQLITE_MASTER table and index entries that refer to the
2470 ** table. The program name loops through the master table and deletes
2471 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002472 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002473 ** created in the temp database that refers to a table in another
2474 ** database.
2475 */
2476 sqlite3NestedParse(pParse,
2477 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2478 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002479 if( !isView && !IsVirtual(pTab) ){
2480 destroyTable(pParse, pTab);
2481 }
2482
2483 /* Remove the table entry from SQLite's internal schema and modify
2484 ** the schema cookie.
2485 */
2486 if( IsVirtual(pTab) ){
2487 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2488 }
2489 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2490 sqlite3ChangeCookie(pParse, iDb);
2491 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002492}
2493
2494/*
drh75897232000-05-29 14:26:00 +00002495** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002496** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002497*/
drha0733842005-12-29 01:11:36 +00002498void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002499 Table *pTab;
drh75897232000-05-29 14:26:00 +00002500 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002501 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002502 int iDb;
drh75897232000-05-29 14:26:00 +00002503
drh8af73d42009-05-13 22:58:28 +00002504 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002505 goto exit_drop_table;
2506 }
drh8af73d42009-05-13 22:58:28 +00002507 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002508 assert( pName->nSrc==1 );
drh75209962015-04-19 22:31:45 +00002509 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
drha7564662010-02-22 19:32:31 +00002510 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002511 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002512 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002513
drha0733842005-12-29 01:11:36 +00002514 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002515 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002516 goto exit_drop_table;
2517 }
danielk1977da184232006-01-05 11:34:32 +00002518 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002519 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002520
2521 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2522 ** it is initialized.
2523 */
2524 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2525 goto exit_drop_table;
2526 }
drhe5f9c642003-01-13 23:27:31 +00002527#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002528 {
2529 int code;
danielk1977da184232006-01-05 11:34:32 +00002530 const char *zTab = SCHEMA_TABLE(iDb);
2531 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002532 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002533 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002534 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002535 }
drhe5f9c642003-01-13 23:27:31 +00002536 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002537 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002538 code = SQLITE_DROP_TEMP_VIEW;
2539 }else{
2540 code = SQLITE_DROP_VIEW;
2541 }
danielk19774b2688a2006-06-20 11:01:07 +00002542#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002543 }else if( IsVirtual(pTab) ){
2544 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002545 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002546#endif
drhe5f9c642003-01-13 23:27:31 +00002547 }else{
danielk197753c0f742005-03-29 03:10:59 +00002548 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002549 code = SQLITE_DROP_TEMP_TABLE;
2550 }else{
2551 code = SQLITE_DROP_TABLE;
2552 }
2553 }
danielk1977f1a381e2006-06-16 08:01:02 +00002554 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002555 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002556 }
danielk1977a8858102004-05-28 12:11:21 +00002557 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2558 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002559 }
drhe5f9c642003-01-13 23:27:31 +00002560 }
2561#endif
drh08ccfaa2011-10-07 23:52:25 +00002562 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2563 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002564 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002565 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002566 }
danielk1977576ec6b2005-01-21 11:55:25 +00002567
2568#ifndef SQLITE_OMIT_VIEW
2569 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2570 ** on a table.
2571 */
danielk1977a8858102004-05-28 12:11:21 +00002572 if( isView && pTab->pSelect==0 ){
2573 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2574 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002575 }
danielk1977a8858102004-05-28 12:11:21 +00002576 if( !isView && pTab->pSelect ){
2577 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2578 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002579 }
danielk1977576ec6b2005-01-21 11:55:25 +00002580#endif
drh75897232000-05-29 14:26:00 +00002581
drh1ccde152000-06-17 13:12:39 +00002582 /* Generate code to remove the table from the master table
2583 ** on disk.
2584 */
danielk19774adee202004-05-08 08:23:19 +00002585 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002586 if( v ){
drh77658e22007-12-04 16:54:52 +00002587 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002588 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002589 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002590 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002591 }
danielk1977a8858102004-05-28 12:11:21 +00002592
2593exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002594 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002595}
2596
2597/*
drhc2eef3b2002-08-31 18:53:06 +00002598** This routine is called to create a new foreign key on the table
2599** currently under construction. pFromCol determines which columns
2600** in the current table point to the foreign key. If pFromCol==0 then
2601** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002602** the table referred to (a.k.a the "parent" table). pToCol is a list
2603** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002604** information about the conflict resolution algorithms specified
2605** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2606**
2607** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002608** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002609**
2610** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002611** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002612*/
danielk19774adee202004-05-08 08:23:19 +00002613void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002614 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002615 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002616 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002617 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002618 int flags /* Conflict resolution algorithms. */
2619){
danielk197718576932008-08-06 13:47:40 +00002620 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002621#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002622 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002623 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002624 Table *p = pParse->pNewTable;
2625 int nByte;
2626 int i;
2627 int nCol;
2628 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002629
2630 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002631 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002632 if( pFromCol==0 ){
2633 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002634 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002635 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002636 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002637 " should reference only one column of table %T",
2638 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002639 goto fk_end;
2640 }
2641 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002642 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002643 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002644 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002645 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002646 goto fk_end;
2647 }else{
danielk19770202b292004-06-09 09:55:16 +00002648 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002649 }
drhe61922a2009-05-02 13:29:37 +00002650 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002651 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002652 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002653 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002654 }
2655 }
drh633e6d52008-07-28 19:34:53 +00002656 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002657 if( pFKey==0 ){
2658 goto fk_end;
2659 }
drhc2eef3b2002-08-31 18:53:06 +00002660 pFKey->pFrom = p;
2661 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002662 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002663 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002664 memcpy(z, pTo->z, pTo->n);
2665 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002666 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002667 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002668 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002669 if( pFromCol==0 ){
2670 pFKey->aCol[0].iFrom = p->nCol-1;
2671 }else{
2672 for(i=0; i<nCol; i++){
2673 int j;
2674 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002675 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002676 pFKey->aCol[i].iFrom = j;
2677 break;
2678 }
2679 }
2680 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002681 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002682 "unknown column \"%s\" in foreign key definition",
2683 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002684 goto fk_end;
2685 }
2686 }
2687 }
2688 if( pToCol ){
2689 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002690 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002691 pFKey->aCol[i].zCol = z;
2692 memcpy(z, pToCol->a[i].zName, n);
2693 z[n] = 0;
2694 z += n+1;
2695 }
2696 }
2697 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002698 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2699 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002700
drh21206082011-04-04 18:22:02 +00002701 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002702 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002703 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002704 );
danf59c5ca2009-09-22 16:55:38 +00002705 if( pNextTo==pFKey ){
2706 db->mallocFailed = 1;
2707 goto fk_end;
2708 }
dan1da40a32009-09-19 17:00:31 +00002709 if( pNextTo ){
2710 assert( pNextTo->pPrevTo==0 );
2711 pFKey->pNextTo = pNextTo;
2712 pNextTo->pPrevTo = pFKey;
2713 }
2714
drhc2eef3b2002-08-31 18:53:06 +00002715 /* Link the foreign key to the table as the last step.
2716 */
2717 p->pFKey = pFKey;
2718 pFKey = 0;
2719
2720fk_end:
drh633e6d52008-07-28 19:34:53 +00002721 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002722#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002723 sqlite3ExprListDelete(db, pFromCol);
2724 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002725}
2726
2727/*
2728** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2729** clause is seen as part of a foreign key definition. The isDeferred
2730** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2731** The behavior of the most recently created foreign key is adjusted
2732** accordingly.
2733*/
danielk19774adee202004-05-08 08:23:19 +00002734void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002735#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002736 Table *pTab;
2737 FKey *pFKey;
2738 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002739 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002740 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002741#endif
drhc2eef3b2002-08-31 18:53:06 +00002742}
2743
2744/*
drh063336a2004-11-05 20:58:39 +00002745** Generate code that will erase and refill index *pIdx. This is
2746** used to initialize a newly created index or to recompute the
2747** content of an index in response to a REINDEX command.
2748**
2749** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002750** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002751** root page number of the index. If memRootPage is negative, then
2752** the index already exists and must be cleared before being refilled and
2753** the root page number of the index is taken from pIndex->tnum.
2754*/
2755static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2756 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002757 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2758 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002759 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002760 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002761 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002762 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002763 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002764 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002765 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002766 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002767 sqlite3 *db = pParse->db; /* The database connection */
2768 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002769
danielk19771d54df82004-11-23 15:41:16 +00002770#ifndef SQLITE_OMIT_AUTHORIZATION
2771 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002772 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002773 return;
2774 }
2775#endif
2776
danielk1977c00da102006-01-07 13:21:04 +00002777 /* Require a write-lock on the table to perform this operation */
2778 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2779
drh063336a2004-11-05 20:58:39 +00002780 v = sqlite3GetVdbe(pParse);
2781 if( v==0 ) return;
2782 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002783 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002784 }else{
2785 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002786 }
drh2ec2fb22013-11-06 19:59:23 +00002787 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002788
dan689ab892011-08-12 15:02:00 +00002789 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002790 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002791 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002792 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002793
2794 /* Open the table. Loop through all rows of the table, inserting index
2795 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002796 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002797 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002798 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002799
drh1c2c0b72014-01-04 19:27:05 +00002800 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002801 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002802 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002803 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002804 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002805 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2806 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002807 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002808 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2809
drh688852a2014-02-17 22:40:43 +00002810 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002811 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002812 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002813 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
drh076e85f2015-09-03 13:46:12 +00002814 sqlite3VdbeGoto(v, j2);
drhca892a72011-09-03 00:17:51 +00002815 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002816 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002817 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002818 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002819 }else{
2820 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002821 }
drh6cf4a7d2014-10-13 13:00:58 +00002822 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
danb18e60b2015-04-01 16:18:00 +00002823 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
2824 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
drhca892a72011-09-03 00:17:51 +00002825 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002826 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002827 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002828 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002829
drh66a51672008-01-03 00:01:23 +00002830 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2831 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002832 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002833}
2834
2835/*
drh77e57df2013-10-22 14:28:02 +00002836** Allocate heap space to hold an Index object with nCol columns.
2837**
2838** Increase the allocation size to provide an extra nExtra bytes
2839** of 8-byte aligned space after the Index object and return a
2840** pointer to this extra space in *ppExtra.
2841*/
2842Index *sqlite3AllocateIndexObject(
2843 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002844 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002845 int nExtra, /* Number of bytes of extra space to alloc */
2846 char **ppExtra /* Pointer to the "extra" space */
2847){
2848 Index *p; /* Allocated index object */
2849 int nByte; /* Bytes of space for Index object + arrays */
2850
2851 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2852 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002853 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002854 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002855 sizeof(u8)*nCol); /* Index.aSortOrder */
2856 p = sqlite3DbMallocZero(db, nByte + nExtra);
2857 if( p ){
2858 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002859 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2860 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2861 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002862 p->aSortOrder = (u8*)pExtra;
2863 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002864 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002865 *ppExtra = ((char*)p) + nByte;
2866 }
2867 return p;
2868}
2869
2870/*
drh23bf66d2004-12-14 03:34:34 +00002871** Create a new index for an SQL table. pName1.pName2 is the name of the index
2872** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002873** be NULL for a primary key or an index that is created to satisfy a
2874** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002875** as the table to be indexed. pParse->pNewTable is a table that is
2876** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002877**
drh382c0242001-10-06 16:33:02 +00002878** pList is a list of columns to be indexed. pList will be NULL if this
2879** is a primary key or unique-constraint on the most recent column added
2880** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002881**
2882** If the index is created successfully, return a pointer to the new Index
2883** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002884** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002885*/
dan1da40a32009-09-19 17:00:31 +00002886Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002887 Parse *pParse, /* All information about this parse */
2888 Token *pName1, /* First part of index name. May be NULL */
2889 Token *pName2, /* Second part of index name. May be NULL */
2890 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002891 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002892 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002893 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002894 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002895 int sortOrder, /* Sort order of primary key when pList==NULL */
2896 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002897){
dan1da40a32009-09-19 17:00:31 +00002898 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002899 Table *pTab = 0; /* Table to be indexed */
2900 Index *pIndex = 0; /* The index to be created */
2901 char *zName = 0; /* Name of the index */
2902 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002903 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002904 DbFixer sFix; /* For assigning database names to pTable */
2905 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002906 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002907 Db *pDb; /* The specific table containing the indexed database */
2908 int iDb; /* Index of the database that is being written */
2909 Token *pName = 0; /* Unqualified name of the index to create */
2910 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002911 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002912 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002913 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002914 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002915
drh7088d502015-04-18 17:43:29 +00002916 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
drhd3001712009-05-12 17:46:53 +00002917 goto exit_create_index;
2918 }
2919 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002920 goto exit_create_index;
2921 }
drhdaffd0e2001-04-11 14:28:42 +00002922
drh75897232000-05-29 14:26:00 +00002923 /*
2924 ** Find the table that is to be indexed. Return early if not found.
2925 */
danielk1977cbb18d22004-05-28 11:37:27 +00002926 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002927
2928 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002929 ** to search for the table. 'Fix' the table name to this db
2930 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002931 */
2932 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002933 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002934 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002935 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002936
danielk197753c0f742005-03-29 03:10:59 +00002937#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002938 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002939 ** is a temp table. If so, set the database to 1. Do not do this
2940 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002941 */
danielk1977fe910332007-12-02 11:46:34 +00002942 if( !db->init.busy ){
2943 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002944 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002945 iDb = 1;
2946 }
danielk1977ef2cb632004-05-29 02:37:19 +00002947 }
danielk197753c0f742005-03-29 03:10:59 +00002948#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002949
drhd100f692013-10-03 15:39:44 +00002950 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2951 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002952 /* Because the parser constructs pTblName from a single identifier,
2953 ** sqlite3FixSrcList can never fail. */
2954 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002955 }
dan41fb5cd2012-10-04 19:33:00 +00002956 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002957 assert( db->mallocFailed==0 || pTab==0 );
2958 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002959 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2960 sqlite3ErrorMsg(pParse,
2961 "cannot create a TEMP index on non-TEMP table \"%s\"",
2962 pTab->zName);
2963 goto exit_create_index;
2964 }
drh44156282013-10-23 22:23:03 +00002965 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002966 }else{
drhe3c41372001-09-17 20:25:58 +00002967 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002968 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002969 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002970 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002971 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002972 }
drhfdd6e852005-12-16 01:06:16 +00002973 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002974
drhd3001712009-05-12 17:46:53 +00002975 assert( pTab!=0 );
2976 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002977 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002978 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002979#if SQLITE_USER_AUTHENTICATION
2980 && sqlite3UserAuthTable(pTab->zName)==0
2981#endif
drh503a6862013-03-01 01:07:17 +00002982 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002983 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002984 goto exit_create_index;
2985 }
danielk1977576ec6b2005-01-21 11:55:25 +00002986#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002987 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002988 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002989 goto exit_create_index;
2990 }
danielk1977576ec6b2005-01-21 11:55:25 +00002991#endif
danielk19775ee9d692006-06-21 12:36:25 +00002992#ifndef SQLITE_OMIT_VIRTUALTABLE
2993 if( IsVirtual(pTab) ){
2994 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2995 goto exit_create_index;
2996 }
2997#endif
drh75897232000-05-29 14:26:00 +00002998
2999 /*
3000 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00003001 ** index or table with the same name.
3002 **
3003 ** Exception: If we are reading the names of permanent indices from the
3004 ** sqlite_master table (because some other process changed the schema) and
3005 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00003006 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00003007 **
3008 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00003009 ** dealing with a primary key or UNIQUE constraint. We have to invent our
3010 ** own name.
drh75897232000-05-29 14:26:00 +00003011 */
danielk1977d8123362004-06-12 09:25:12 +00003012 if( pName ){
drh17435752007-08-16 04:30:38 +00003013 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00003014 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00003015 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00003016 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00003017 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00003018 }
danielk1977d8123362004-06-12 09:25:12 +00003019 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00003020 if( sqlite3FindTable(db, zName, 0)!=0 ){
3021 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3022 goto exit_create_index;
3023 }
3024 }
danielk197759a33f92007-03-17 10:26:59 +00003025 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
3026 if( !ifNotExist ){
3027 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00003028 }else{
3029 assert( !db->init.busy );
3030 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00003031 }
danielk197759a33f92007-03-17 10:26:59 +00003032 goto exit_create_index;
3033 }
danielk1977a21c6b62005-01-24 10:25:59 +00003034 }else{
drhadbca9c2001-09-27 15:11:53 +00003035 int n;
3036 Index *pLoop;
3037 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00003038 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00003039 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00003040 goto exit_create_index;
3041 }
drh75897232000-05-29 14:26:00 +00003042 }
3043
drhe5f9c642003-01-13 23:27:31 +00003044 /* Check for authorization to create an index.
3045 */
3046#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00003047 {
drhfdd6e852005-12-16 01:06:16 +00003048 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00003049 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003050 goto exit_create_index;
3051 }
3052 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00003053 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003054 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003055 goto exit_create_index;
3056 }
drhe5f9c642003-01-13 23:27:31 +00003057 }
3058#endif
3059
drh75897232000-05-29 14:26:00 +00003060 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00003061 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00003062 ** So create a fake list to simulate this.
3063 */
3064 if( pList==0 ){
drh108aa002015-08-24 20:21:20 +00003065 Token prevCol;
3066 prevCol.z = pTab->aCol[pTab->nCol-1].zName;
3067 prevCol.n = sqlite3Strlen30(prevCol.z);
3068 pList = sqlite3ExprListAppend(pParse, 0,
3069 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
drh75897232000-05-29 14:26:00 +00003070 if( pList==0 ) goto exit_create_index;
drhbc622bc2015-08-24 15:39:42 +00003071 assert( pList->nExpr==1 );
3072 sqlite3ExprListSetSortOrder(pList, sortOrder);
drh108aa002015-08-24 20:21:20 +00003073 }else{
3074 sqlite3ExprListCheckLength(pParse, pList, "index");
drh75897232000-05-29 14:26:00 +00003075 }
3076
danielk1977b3bf5562006-01-10 17:58:23 +00003077 /* Figure out how many bytes of space are required to store explicitly
3078 ** specified collation sequence names.
3079 */
3080 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003081 Expr *pExpr = pList->a[i].pExpr;
drh7d3d9da2015-09-01 00:42:52 +00003082 assert( pExpr!=0 );
3083 if( pExpr->op==TK_COLLATE ){
dan911ce412013-05-15 15:16:50 +00003084 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003085 }
3086 }
3087
drh75897232000-05-29 14:26:00 +00003088 /*
3089 ** Allocate the index structure.
3090 */
drhea678832008-12-10 19:26:22 +00003091 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003092 nExtraCol = pPk ? pPk->nKeyCol : 1;
3093 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003094 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003095 if( db->mallocFailed ){
3096 goto exit_create_index;
3097 }
dancfc9df72014-04-25 15:01:01 +00003098 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003099 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003100 pIndex->zName = zExtra;
3101 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003102 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003103 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003104 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003105 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003106 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003107 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003108 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003109 if( pPIWhere ){
3110 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3111 pIndex->pPartIdxWhere = pPIWhere;
3112 pPIWhere = 0;
3113 }
drh21206082011-04-04 18:22:02 +00003114 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003115
drhfdd6e852005-12-16 01:06:16 +00003116 /* Check to see if we should honor DESC requests on index columns
3117 */
danielk1977da184232006-01-05 11:34:32 +00003118 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003119 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003120 }else{
3121 sortOrderMask = 0; /* Ignore DESC */
3122 }
3123
drh1f9ca2c2015-08-25 16:57:52 +00003124 /* Analyze the list of expressions that form the terms of the index and
3125 ** report any errors. In the common case where the expression is exactly
3126 ** a table column, store that column in aiColumn[]. For general expressions,
drh4b92f982015-09-29 17:20:14 +00003127 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
drhd3001712009-05-12 17:46:53 +00003128 **
drh1f9ca2c2015-08-25 16:57:52 +00003129 ** TODO: Issue a warning if two or more columns of the index are identical.
3130 ** TODO: Issue a warning if the table primary key is used as part of the
3131 ** index key.
drh75897232000-05-29 14:26:00 +00003132 */
drhfdd6e852005-12-16 01:06:16 +00003133 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
drh1f9ca2c2015-08-25 16:57:52 +00003134 Expr *pCExpr; /* The i-th index expression */
3135 int requestedSortOrder; /* ASC or DESC on the i-th expression */
drha34001c2007-02-02 12:44:37 +00003136 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003137
drhedb04ed2015-09-04 12:54:01 +00003138 sqlite3StringToId(pListItem->pExpr);
drha514b8e2015-08-25 00:27:06 +00003139 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
3140 if( pParse->nErr ) goto exit_create_index;
drh108aa002015-08-24 20:21:20 +00003141 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
drha514b8e2015-08-25 00:27:06 +00003142 if( pCExpr->op!=TK_COLUMN ){
drh1f9ca2c2015-08-25 16:57:52 +00003143 if( pTab==pParse->pNewTable ){
3144 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
3145 "UNIQUE constraints");
3146 goto exit_create_index;
3147 }
3148 if( pIndex->aColExpr==0 ){
drh84926532015-08-31 19:38:42 +00003149 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
3150 pIndex->aColExpr = pCopy;
3151 if( !db->mallocFailed ){
3152 assert( pCopy!=0 );
3153 pListItem = &pCopy->a[i];
3154 }
drh1f9ca2c2015-08-25 16:57:52 +00003155 }
drh4b92f982015-09-29 17:20:14 +00003156 j = XN_EXPR;
3157 pIndex->aiColumn[i] = XN_EXPR;
drh84926532015-08-31 19:38:42 +00003158 pIndex->uniqNotNull = 0;
drh1f9ca2c2015-08-25 16:57:52 +00003159 }else{
3160 j = pCExpr->iColumn;
3161 assert( j<=0x7fff );
3162 if( j<0 ){
3163 j = pTab->iPKey;
3164 }else if( pTab->aCol[j].notNull==0 ){
3165 pIndex->uniqNotNull = 0;
3166 }
3167 pIndex->aiColumn[i] = (i16)j;
drh108aa002015-08-24 20:21:20 +00003168 }
drha514b8e2015-08-25 00:27:06 +00003169 zColl = 0;
drh108aa002015-08-24 20:21:20 +00003170 if( pListItem->pExpr->op==TK_COLLATE ){
drhd3001712009-05-12 17:46:53 +00003171 int nColl;
dan911ce412013-05-15 15:16:50 +00003172 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003173 nColl = sqlite3Strlen30(zColl) + 1;
3174 assert( nExtra>=nColl );
3175 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003176 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003177 zExtra += nColl;
3178 nExtra -= nColl;
drha514b8e2015-08-25 00:27:06 +00003179 }else if( j>=0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003180 zColl = pTab->aCol[j].zColl;
danielk19770202b292004-06-09 09:55:16 +00003181 }
drha514b8e2015-08-25 00:27:06 +00003182 if( !zColl ) zColl = "BINARY";
drhb7f24de2009-05-13 17:35:23 +00003183 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003184 goto exit_create_index;
3185 }
danielk1977b3bf5562006-01-10 17:58:23 +00003186 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003187 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003188 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00003189 }
drh1f9ca2c2015-08-25 16:57:52 +00003190
3191 /* Append the table key to the end of the index. For WITHOUT ROWID
3192 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
3193 ** normal tables (when pPk==0) this will be the rowid.
3194 */
drh44156282013-10-23 22:23:03 +00003195 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003196 for(j=0; j<pPk->nKeyCol; j++){
3197 int x = pPk->aiColumn[j];
drh1f9ca2c2015-08-25 16:57:52 +00003198 assert( x>=0 );
drh7913e412013-11-01 20:30:36 +00003199 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3200 pIndex->nColumn--;
3201 }else{
3202 pIndex->aiColumn[i] = x;
3203 pIndex->azColl[i] = pPk->azColl[j];
3204 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3205 i++;
3206 }
drh44156282013-10-23 22:23:03 +00003207 }
drh7913e412013-11-01 20:30:36 +00003208 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003209 }else{
drh4b92f982015-09-29 17:20:14 +00003210 pIndex->aiColumn[i] = XN_ROWID;
drh44156282013-10-23 22:23:03 +00003211 pIndex->azColl[i] = "BINARY";
3212 }
drh51147ba2005-07-23 22:59:55 +00003213 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003214 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003215
danielk1977d8123362004-06-12 09:25:12 +00003216 if( pTab==pParse->pNewTable ){
3217 /* This routine has been called to create an automatic index as a
3218 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3219 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3220 ** i.e. one of:
3221 **
3222 ** CREATE TABLE t(x PRIMARY KEY, y);
3223 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3224 **
3225 ** Either way, check to see if the table already has such an index. If
3226 ** so, don't bother creating this one. This only applies to
3227 ** automatically created indices. Users can do as they wish with
3228 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003229 **
3230 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3231 ** (and thus suppressing the second one) even if they have different
3232 ** sort orders.
3233 **
3234 ** If there are different collating sequences or if the columns of
3235 ** the constraint occur in different orders, then the constraints are
3236 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003237 */
3238 Index *pIdx;
3239 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3240 int k;
drh5f1d1d92014-07-31 22:59:04 +00003241 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003242 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003243 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003244
drhbbbdc832013-10-22 18:01:40 +00003245 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3246 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003247 const char *z1;
3248 const char *z2;
drh1f9ca2c2015-08-25 16:57:52 +00003249 assert( pIdx->aiColumn[k]>=0 );
danielk1977d8123362004-06-12 09:25:12 +00003250 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003251 z1 = pIdx->azColl[k];
3252 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003253 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003254 }
drhbbbdc832013-10-22 18:01:40 +00003255 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003256 if( pIdx->onError!=pIndex->onError ){
3257 /* This constraint creates the same index as a previous
3258 ** constraint specified somewhere in the CREATE TABLE statement.
3259 ** However the ON CONFLICT clauses are different. If both this
3260 ** constraint and the previous equivalent constraint have explicit
3261 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003262 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003263 */
3264 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3265 sqlite3ErrorMsg(pParse,
3266 "conflicting ON CONFLICT clauses specified", 0);
3267 }
3268 if( pIdx->onError==OE_Default ){
3269 pIdx->onError = pIndex->onError;
3270 }
3271 }
drhf0636852015-03-21 02:58:20 +00003272 pRet = pIdx;
danielk1977d8123362004-06-12 09:25:12 +00003273 goto exit_create_index;
3274 }
3275 }
3276 }
3277
drh75897232000-05-29 14:26:00 +00003278 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003279 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003280 */
drh7d3d9da2015-09-01 00:42:52 +00003281 assert( pParse->nErr==0 );
drh234c39d2004-07-24 03:30:47 +00003282 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003283 Index *p;
drh21206082011-04-04 18:22:02 +00003284 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003285 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003286 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003287 if( p ){
3288 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003289 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003290 goto exit_create_index;
3291 }
drh5e00f6c2001-09-13 13:46:56 +00003292 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003293 if( pTblName!=0 ){
3294 pIndex->tnum = db->init.newTnum;
3295 }
drhd78eeee2001-09-13 16:18:53 +00003296 }
3297
drh58383402013-11-04 17:00:50 +00003298 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3299 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3300 ** emit code to allocate the index rootpage on disk and make an entry for
3301 ** the index in the sqlite_master table and populate the index with
3302 ** content. But, do not do this if we are simply reading the sqlite_master
3303 ** table to parse the schema, or if this index is the PRIMARY KEY index
3304 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003305 **
drh58383402013-11-04 17:00:50 +00003306 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3307 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003308 ** has just been created, it contains no data and the index initialization
3309 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003310 */
drh7d3d9da2015-09-01 00:42:52 +00003311 else if( HasRowid(pTab) || pTblName!=0 ){
drhadbca9c2001-09-27 15:11:53 +00003312 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003313 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003314 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003315
danielk19774adee202004-05-08 08:23:19 +00003316 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003317 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003318
drhaee128d2005-02-14 20:48:18 +00003319 sqlite3BeginWriteOperation(pParse, 1, iDb);
danc5b73582015-05-26 11:53:14 +00003320
3321 /* Create the rootpage for the index using CreateIndex. But before
3322 ** doing so, code a Noop instruction and store its address in
3323 ** Index.tnum. This is required in case this index is actually a
3324 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3325 ** that case the convertToWithoutRowidTable() routine will replace
3326 ** the Noop with a Goto to jump over the VDBE code generated below. */
3327 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
drhb7654112008-01-12 12:48:07 +00003328 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003329
3330 /* Gather the complete text of the CREATE INDEX statement into
3331 ** the zStmt variable
3332 */
drhd3001712009-05-12 17:46:53 +00003333 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003334 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003335 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003336 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003337 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003338 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003339 }else{
3340 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003341 /* zStmt = sqlite3MPrintf(""); */
3342 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003343 }
drh063336a2004-11-05 20:58:39 +00003344
3345 /* Add an entry in sqlite_master for this index
3346 */
3347 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003348 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003349 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3350 pIndex->zName,
3351 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003352 iMem,
drh063336a2004-11-05 20:58:39 +00003353 zStmt
3354 );
drh633e6d52008-07-28 19:34:53 +00003355 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003356
danielk1977a21c6b62005-01-24 10:25:59 +00003357 /* Fill the index with data and reparse the schema. Code an OP_Expire
3358 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003359 */
danielk1977cbb18d22004-05-28 11:37:27 +00003360 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003361 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003362 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003363 sqlite3VdbeAddParseSchemaOp(v, iDb,
3364 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003365 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003366 }
danc5b73582015-05-26 11:53:14 +00003367
3368 sqlite3VdbeJumpHere(v, pIndex->tnum);
drh75897232000-05-29 14:26:00 +00003369 }
3370
danielk1977d8123362004-06-12 09:25:12 +00003371 /* When adding an index to the list of indices for a table, make
3372 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003373 ** OE_Ignore. This is necessary for the correct constraint check
3374 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3375 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003376 */
drh234c39d2004-07-24 03:30:47 +00003377 if( db->init.busy || pTblName==0 ){
3378 if( onError!=OE_Replace || pTab->pIndex==0
3379 || pTab->pIndex->onError==OE_Replace){
3380 pIndex->pNext = pTab->pIndex;
3381 pTab->pIndex = pIndex;
3382 }else{
3383 Index *pOther = pTab->pIndex;
3384 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3385 pOther = pOther->pNext;
3386 }
3387 pIndex->pNext = pOther->pNext;
3388 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003389 }
dan1da40a32009-09-19 17:00:31 +00003390 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003391 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003392 }
danielk1977d8123362004-06-12 09:25:12 +00003393
drh75897232000-05-29 14:26:00 +00003394 /* Clean up before exiting */
3395exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003396 if( pIndex ) freeIndex(db, pIndex);
3397 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003398 sqlite3ExprListDelete(db, pList);
3399 sqlite3SrcListDelete(db, pTblName);
3400 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003401 return pRet;
drh75897232000-05-29 14:26:00 +00003402}
3403
3404/*
drh51147ba2005-07-23 22:59:55 +00003405** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003406** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003407**
peter.d.reid60ec9142014-09-06 16:39:46 +00003408** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003409** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3410** number of rows in the table that match any particular value of the
3411** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003412** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003413** of the index. And so forth. It must always be the case that
3414*
3415** aiRowEst[N]<=aiRowEst[N-1]
3416** aiRowEst[N]>=1
3417**
3418** Apart from that, we have little to go on besides intuition as to
3419** how aiRowEst[] should be initialized. The numbers generated here
3420** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003421*/
3422void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003423 /* 10, 9, 8, 7, 6 */
3424 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003425 LogEst *a = pIdx->aiRowLogEst;
3426 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003427 int i;
dancfc9df72014-04-25 15:01:01 +00003428
dan264d2b92014-04-29 19:01:57 +00003429 /* Set the first entry (number of rows in the index) to the estimated
3430 ** number of rows in the table. Or 10, if the estimated number of rows
3431 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003432 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003433 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3434
3435 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3436 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003437 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003438 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3439 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003440 }
dan264d2b92014-04-29 19:01:57 +00003441
3442 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003443 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003444}
3445
3446/*
drh74e24cd2002-01-09 03:19:59 +00003447** This routine will drop an existing named index. This routine
3448** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003449*/
drh4d91a702006-01-04 15:54:36 +00003450void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003451 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003452 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003453 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003454 int iDb;
drh75897232000-05-29 14:26:00 +00003455
drh8af73d42009-05-13 22:58:28 +00003456 assert( pParse->nErr==0 ); /* Never called with prior errors */
3457 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003458 goto exit_drop_index;
3459 }
drhd24cc422003-03-27 12:51:24 +00003460 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003461 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3462 goto exit_drop_index;
3463 }
danielk19774adee202004-05-08 08:23:19 +00003464 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003465 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003466 if( !ifExists ){
3467 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003468 }else{
3469 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003470 }
drha6ecd332004-06-10 00:29:09 +00003471 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003472 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003473 }
drh48dd1d82014-05-27 18:18:58 +00003474 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003475 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003476 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003477 goto exit_drop_index;
3478 }
danielk1977da184232006-01-05 11:34:32 +00003479 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003480#ifndef SQLITE_OMIT_AUTHORIZATION
3481 {
3482 int code = SQLITE_DROP_INDEX;
3483 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003484 const char *zDb = db->aDb[iDb].zName;
3485 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003486 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003487 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003488 }
danielk1977da184232006-01-05 11:34:32 +00003489 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003490 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003491 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003492 }
drhed6c8672003-01-12 18:02:16 +00003493 }
drhe5f9c642003-01-13 23:27:31 +00003494#endif
drh75897232000-05-29 14:26:00 +00003495
3496 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003497 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003498 if( v ){
drh77658e22007-12-04 16:54:52 +00003499 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003500 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003501 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003502 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003503 );
drha5ae4c32011-08-07 01:31:52 +00003504 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003505 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003506 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003507 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003508 }
3509
drhd24cc422003-03-27 12:51:24 +00003510exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003511 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003512}
3513
3514/*
dan9ace1122012-03-29 07:51:45 +00003515** pArray is a pointer to an array of objects. Each object in the
3516** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3517** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003518**
dan9ace1122012-03-29 07:51:45 +00003519** When this function is called, *pnEntry contains the current size of
3520** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3521** in total).
drh13449892005-09-07 21:22:45 +00003522**
dan9ace1122012-03-29 07:51:45 +00003523** If the realloc() is successful (i.e. if no OOM condition occurs), the
3524** space allocated for the new object is zeroed, *pnEntry updated to
3525** reflect the new size of the array and a pointer to the new allocation
3526** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003527**
dan9ace1122012-03-29 07:51:45 +00003528** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3529** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003530*/
drhcf643722007-03-27 13:36:37 +00003531void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003532 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003533 void *pArray, /* Array of objects. Might be reallocated */
3534 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003535 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003536 int *pIdx /* Write the index of a new slot here */
3537){
3538 char *z;
drh6c535152012-02-02 03:38:30 +00003539 int n = *pnEntry;
3540 if( (n & (n-1))==0 ){
3541 int sz = (n==0) ? 1 : 2*n;
3542 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003543 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003544 *pIdx = -1;
3545 return pArray;
drh13449892005-09-07 21:22:45 +00003546 }
drhcf643722007-03-27 13:36:37 +00003547 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003548 }
drhcf643722007-03-27 13:36:37 +00003549 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003550 memset(&z[n * szEntry], 0, szEntry);
3551 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003552 ++*pnEntry;
3553 return pArray;
drh13449892005-09-07 21:22:45 +00003554}
3555
3556/*
drh75897232000-05-29 14:26:00 +00003557** Append a new element to the given IdList. Create a new IdList if
3558** need be.
drhdaffd0e2001-04-11 14:28:42 +00003559**
3560** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003561*/
drh17435752007-08-16 04:30:38 +00003562IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003563 int i;
drh75897232000-05-29 14:26:00 +00003564 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003565 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003566 if( pList==0 ) return 0;
3567 }
drhcf643722007-03-27 13:36:37 +00003568 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003569 db,
drhcf643722007-03-27 13:36:37 +00003570 pList->a,
3571 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003572 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003573 &i
3574 );
drh13449892005-09-07 21:22:45 +00003575 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003576 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003577 return 0;
drh75897232000-05-29 14:26:00 +00003578 }
drh17435752007-08-16 04:30:38 +00003579 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003580 return pList;
3581}
3582
3583/*
drhfe05af82005-07-21 03:14:59 +00003584** Delete an IdList.
3585*/
drh633e6d52008-07-28 19:34:53 +00003586void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003587 int i;
3588 if( pList==0 ) return;
3589 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003590 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003591 }
drh633e6d52008-07-28 19:34:53 +00003592 sqlite3DbFree(db, pList->a);
3593 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003594}
3595
3596/*
3597** Return the index in pList of the identifier named zId. Return -1
3598** if not found.
3599*/
3600int sqlite3IdListIndex(IdList *pList, const char *zName){
3601 int i;
3602 if( pList==0 ) return -1;
3603 for(i=0; i<pList->nId; i++){
3604 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3605 }
3606 return -1;
3607}
3608
3609/*
drha78c22c2008-11-11 18:28:58 +00003610** Expand the space allocated for the given SrcList object by
3611** creating nExtra new slots beginning at iStart. iStart is zero based.
3612** New slots are zeroed.
3613**
3614** For example, suppose a SrcList initially contains two entries: A,B.
3615** To append 3 new entries onto the end, do this:
3616**
3617** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3618**
3619** After the call above it would contain: A, B, nil, nil, nil.
3620** If the iStart argument had been 1 instead of 2, then the result
3621** would have been: A, nil, nil, nil, B. To prepend the new slots,
3622** the iStart value would be 0. The result then would
3623** be: nil, nil, nil, A, B.
3624**
3625** If a memory allocation fails the SrcList is unchanged. The
3626** db->mallocFailed flag will be set to true.
3627*/
3628SrcList *sqlite3SrcListEnlarge(
3629 sqlite3 *db, /* Database connection to notify of OOM errors */
3630 SrcList *pSrc, /* The SrcList to be enlarged */
3631 int nExtra, /* Number of new slots to add to pSrc->a[] */
3632 int iStart /* Index in pSrc->a[] of first new slot */
3633){
3634 int i;
3635
3636 /* Sanity checking on calling parameters */
3637 assert( iStart>=0 );
3638 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003639 assert( pSrc!=0 );
3640 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003641
3642 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003643 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003644 SrcList *pNew;
3645 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003646 int nGot;
drha78c22c2008-11-11 18:28:58 +00003647 pNew = sqlite3DbRealloc(db, pSrc,
3648 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3649 if( pNew==0 ){
3650 assert( db->mallocFailed );
3651 return pSrc;
3652 }
3653 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003654 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003655 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003656 }
3657
3658 /* Move existing slots that come after the newly inserted slots
3659 ** out of the way */
3660 for(i=pSrc->nSrc-1; i>=iStart; i--){
3661 pSrc->a[i+nExtra] = pSrc->a[i];
3662 }
drh6d1626e2014-03-05 15:52:43 +00003663 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003664
3665 /* Zero the newly allocated slots */
3666 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3667 for(i=iStart; i<iStart+nExtra; i++){
3668 pSrc->a[i].iCursor = -1;
3669 }
3670
3671 /* Return a pointer to the enlarged SrcList */
3672 return pSrc;
3673}
3674
3675
3676/*
drhad3cab52002-05-24 02:04:32 +00003677** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003678** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003679**
drha78c22c2008-11-11 18:28:58 +00003680** A SrcList is returned, or NULL if there is an OOM error. The returned
3681** SrcList might be the same as the SrcList that was input or it might be
3682** a new one. If an OOM error does occurs, then the prior value of pList
3683** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003684**
3685** If pDatabase is not null, it means that the table has an optional
3686** database name prefix. Like this: "database.table". The pDatabase
3687** points to the table name and the pTable points to the database name.
3688** The SrcList.a[].zName field is filled with the table name which might
3689** come from pTable (if pDatabase is NULL) or from pDatabase.
3690** SrcList.a[].zDatabase is filled with the database name from pTable,
3691** or with NULL if no database is specified.
3692**
3693** In other words, if call like this:
3694**
drh17435752007-08-16 04:30:38 +00003695** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003696**
3697** Then B is a table name and the database name is unspecified. If called
3698** like this:
3699**
drh17435752007-08-16 04:30:38 +00003700** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003701**
drhd3001712009-05-12 17:46:53 +00003702** Then C is the table name and B is the database name. If C is defined
3703** then so is B. In other words, we never have a case where:
3704**
3705** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003706**
3707** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3708** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003709*/
drh17435752007-08-16 04:30:38 +00003710SrcList *sqlite3SrcListAppend(
3711 sqlite3 *db, /* Connection to notify of malloc failures */
3712 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3713 Token *pTable, /* Table to append */
3714 Token *pDatabase /* Database of the table */
3715){
drha99db3b2004-06-19 14:49:12 +00003716 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003717 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003718 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003719 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003720 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003721 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003722 }
drha78c22c2008-11-11 18:28:58 +00003723 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3724 if( db->mallocFailed ){
3725 sqlite3SrcListDelete(db, pList);
3726 return 0;
drhad3cab52002-05-24 02:04:32 +00003727 }
drha78c22c2008-11-11 18:28:58 +00003728 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003729 if( pDatabase && pDatabase->z==0 ){
3730 pDatabase = 0;
3731 }
drhd3001712009-05-12 17:46:53 +00003732 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003733 Token *pTemp = pDatabase;
3734 pDatabase = pTable;
3735 pTable = pTemp;
3736 }
drh17435752007-08-16 04:30:38 +00003737 pItem->zName = sqlite3NameFromToken(db, pTable);
3738 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003739 return pList;
3740}
3741
3742/*
drhdfe88ec2008-11-03 20:55:06 +00003743** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003744*/
danielk19774adee202004-05-08 08:23:19 +00003745void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003746 int i;
drh9b3187e2005-01-18 14:45:47 +00003747 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003748 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003749 if( pList ){
3750 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3751 if( pItem->iCursor>=0 ) break;
3752 pItem->iCursor = pParse->nTab++;
3753 if( pItem->pSelect ){
3754 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3755 }
drh63eb5f22003-04-29 16:20:44 +00003756 }
3757 }
3758}
3759
3760/*
drhad3cab52002-05-24 02:04:32 +00003761** Delete an entire SrcList including all its substructure.
3762*/
drh633e6d52008-07-28 19:34:53 +00003763void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003764 int i;
drhbe5c89a2004-07-26 00:31:09 +00003765 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003766 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003767 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003768 sqlite3DbFree(db, pItem->zDatabase);
3769 sqlite3DbFree(db, pItem->zName);
3770 sqlite3DbFree(db, pItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00003771 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
3772 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
dan1feeaed2010-07-23 15:41:47 +00003773 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003774 sqlite3SelectDelete(db, pItem->pSelect);
3775 sqlite3ExprDelete(db, pItem->pOn);
3776 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003777 }
drh633e6d52008-07-28 19:34:53 +00003778 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003779}
3780
drh982cef72000-05-30 16:27:03 +00003781/*
drh61dfc312006-12-16 16:25:15 +00003782** This routine is called by the parser to add a new term to the
3783** end of a growing FROM clause. The "p" parameter is the part of
3784** the FROM clause that has already been constructed. "p" is NULL
3785** if this is the first term of the FROM clause. pTable and pDatabase
3786** are the name of the table and database named in the FROM clause term.
3787** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003788** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003789** alias token. If the term is a subquery, then pSubquery is the
3790** SELECT statement that the subquery encodes. The pTable and
3791** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3792** parameters are the content of the ON and USING clauses.
3793**
3794** Return a new SrcList which encodes is the FROM with the new
3795** term added.
3796*/
3797SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003798 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003799 SrcList *p, /* The left part of the FROM clause already seen */
3800 Token *pTable, /* Name of the table to add to the FROM clause */
3801 Token *pDatabase, /* Name of the database containing pTable */
3802 Token *pAlias, /* The right-hand side of the AS subexpression */
3803 Select *pSubquery, /* A subquery used in place of a table name */
3804 Expr *pOn, /* The ON clause of a join */
3805 IdList *pUsing /* The USING clause of a join */
3806){
3807 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003808 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003809 if( !p && (pOn || pUsing) ){
3810 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3811 (pOn ? "ON" : "USING")
3812 );
3813 goto append_from_error;
3814 }
drh17435752007-08-16 04:30:38 +00003815 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003816 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003817 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003818 }
3819 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003820 assert( pAlias!=0 );
3821 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003822 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003823 }
3824 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003825 pItem->pOn = pOn;
3826 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003827 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003828
3829 append_from_error:
3830 assert( p==0 );
3831 sqlite3ExprDelete(db, pOn);
3832 sqlite3IdListDelete(db, pUsing);
3833 sqlite3SelectDelete(db, pSubquery);
3834 return 0;
drh61dfc312006-12-16 16:25:15 +00003835}
3836
3837/*
danielk1977b1c685b2008-10-06 16:18:39 +00003838** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3839** element of the source-list passed as the second argument.
3840*/
3841void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003842 assert( pIndexedBy!=0 );
3843 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003844 struct SrcList_item *pItem = &p->a[p->nSrc-1];
drh8a48b9c2015-08-19 15:20:00 +00003845 assert( pItem->fg.notIndexed==0 );
3846 assert( pItem->fg.isIndexedBy==0 );
3847 assert( pItem->fg.isTabFunc==0 );
danielk1977b1c685b2008-10-06 16:18:39 +00003848 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3849 /* A "NOT INDEXED" clause was supplied. See parse.y
3850 ** construct "indexed_opt" for details. */
drh8a48b9c2015-08-19 15:20:00 +00003851 pItem->fg.notIndexed = 1;
danielk1977b1c685b2008-10-06 16:18:39 +00003852 }else{
drh8a48b9c2015-08-19 15:20:00 +00003853 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
3854 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
danielk1977b1c685b2008-10-06 16:18:39 +00003855 }
3856 }
3857}
3858
3859/*
drh01d230c2015-08-19 17:11:37 +00003860** Add the list of function arguments to the SrcList entry for a
3861** table-valued-function.
3862*/
3863void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
drhd8b1bfc2015-08-20 23:21:34 +00003864 if( p && pList ){
drh01d230c2015-08-19 17:11:37 +00003865 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3866 assert( pItem->fg.notIndexed==0 );
3867 assert( pItem->fg.isIndexedBy==0 );
3868 assert( pItem->fg.isTabFunc==0 );
3869 pItem->u1.pFuncArg = pList;
3870 pItem->fg.isTabFunc = 1;
drhd8b1bfc2015-08-20 23:21:34 +00003871 }else{
3872 sqlite3ExprListDelete(pParse->db, pList);
drh01d230c2015-08-19 17:11:37 +00003873 }
3874}
3875
3876/*
drh61dfc312006-12-16 16:25:15 +00003877** When building up a FROM clause in the parser, the join operator
3878** is initially attached to the left operand. But the code generator
3879** expects the join operator to be on the right operand. This routine
3880** Shifts all join operators from left to right for an entire FROM
3881** clause.
3882**
3883** Example: Suppose the join is like this:
3884**
3885** A natural cross join B
3886**
3887** The operator is "natural cross join". The A and B operands are stored
3888** in p->a[0] and p->a[1], respectively. The parser initially stores the
3889** operator with A. This routine shifts that operator over to B.
3890*/
3891void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003892 if( p ){
drh61dfc312006-12-16 16:25:15 +00003893 int i;
3894 for(i=p->nSrc-1; i>0; i--){
drh8a48b9c2015-08-19 15:20:00 +00003895 p->a[i].fg.jointype = p->a[i-1].fg.jointype;
drh61dfc312006-12-16 16:25:15 +00003896 }
drh8a48b9c2015-08-19 15:20:00 +00003897 p->a[0].fg.jointype = 0;
drh61dfc312006-12-16 16:25:15 +00003898 }
3899}
3900
3901/*
drhc4a3c772001-04-04 11:48:57 +00003902** Begin a transaction
3903*/
drh684917c2004-10-05 02:41:42 +00003904void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003905 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003906 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003907 int i;
drh5e00f6c2001-09-13 13:46:56 +00003908
drhd3001712009-05-12 17:46:53 +00003909 assert( pParse!=0 );
3910 db = pParse->db;
3911 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003912/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003913 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3914 return;
3915 }
danielk19771d850a72004-05-31 08:26:49 +00003916 v = sqlite3GetVdbe(pParse);
3917 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003918 if( type!=TK_DEFERRED ){
3919 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003920 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003921 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003922 }
3923 }
drh66a51672008-01-03 00:01:23 +00003924 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003925}
3926
3927/*
3928** Commit a transaction
3929*/
danielk19774adee202004-05-08 08:23:19 +00003930void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003931 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003932
drhd3001712009-05-12 17:46:53 +00003933 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003934 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003935 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3936 return;
3937 }
danielk19771d850a72004-05-31 08:26:49 +00003938 v = sqlite3GetVdbe(pParse);
3939 if( v ){
drh66a51672008-01-03 00:01:23 +00003940 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003941 }
drhc4a3c772001-04-04 11:48:57 +00003942}
3943
3944/*
3945** Rollback a transaction
3946*/
danielk19774adee202004-05-08 08:23:19 +00003947void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003948 Vdbe *v;
3949
drhd3001712009-05-12 17:46:53 +00003950 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003951 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003952 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3953 return;
3954 }
danielk19774adee202004-05-08 08:23:19 +00003955 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003956 if( v ){
drh66a51672008-01-03 00:01:23 +00003957 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003958 }
drhc4a3c772001-04-04 11:48:57 +00003959}
drhf57b14a2001-09-14 18:54:08 +00003960
3961/*
danielk1977fd7f0452008-12-17 17:30:26 +00003962** This function is called by the parser when it parses a command to create,
3963** release or rollback an SQL savepoint.
3964*/
3965void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003966 char *zName = sqlite3NameFromToken(pParse->db, pName);
3967 if( zName ){
3968 Vdbe *v = sqlite3GetVdbe(pParse);
3969#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003970 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003971 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3972#endif
3973 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3974 sqlite3DbFree(pParse->db, zName);
3975 return;
3976 }
3977 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003978 }
3979}
3980
3981/*
drhdc3ff9c2004-08-18 02:10:15 +00003982** Make sure the TEMP database is open and available for use. Return
3983** the number of errors. Leave any error messages in the pParse structure.
3984*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003985int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003986 sqlite3 *db = pParse->db;
3987 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003988 int rc;
drh10a76c92010-01-26 01:25:26 +00003989 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003990 static const int flags =
3991 SQLITE_OPEN_READWRITE |
3992 SQLITE_OPEN_CREATE |
3993 SQLITE_OPEN_EXCLUSIVE |
3994 SQLITE_OPEN_DELETEONCLOSE |
3995 SQLITE_OPEN_TEMP_DB;
3996
dan3a6d8ae2011-04-23 15:54:54 +00003997 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003998 if( rc!=SQLITE_OK ){
3999 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
4000 "file for storing temporary tables");
4001 pParse->rc = rc;
4002 return 1;
4003 }
drh10a76c92010-01-26 01:25:26 +00004004 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00004005 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00004006 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
4007 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00004008 return 1;
drh10a76c92010-01-26 01:25:26 +00004009 }
drhdc3ff9c2004-08-18 02:10:15 +00004010 }
4011 return 0;
4012}
4013
4014/*
drhaceb31b2014-02-08 01:40:27 +00004015** Record the fact that the schema cookie will need to be verified
4016** for database iDb. The code to actually verify the schema cookie
4017** will occur at the end of the top-level VDBE and will be generated
4018** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00004019*/
danielk19774adee202004-05-08 08:23:19 +00004020void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004021 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00004022 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00004023
drhaceb31b2014-02-08 01:40:27 +00004024 assert( iDb>=0 && iDb<db->nDb );
4025 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
4026 assert( iDb<SQLITE_MAX_ATTACHED+2 );
4027 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00004028 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
4029 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00004030 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
4031 if( !OMIT_TEMPDB && iDb==1 ){
4032 sqlite3OpenTempDatabase(pToplevel);
4033 }
drh001bbcb2003-03-19 03:14:00 +00004034 }
drh001bbcb2003-03-19 03:14:00 +00004035}
4036
4037/*
dan57966752011-04-09 17:32:58 +00004038** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4039** attached database. Otherwise, invoke it for the database named zDb only.
4040*/
4041void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4042 sqlite3 *db = pParse->db;
4043 int i;
4044 for(i=0; i<db->nDb; i++){
4045 Db *pDb = &db->aDb[i];
4046 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
4047 sqlite3CodeVerifySchema(pParse, i);
4048 }
4049 }
4050}
4051
4052/*
drh1c928532002-01-31 15:54:21 +00004053** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00004054** might change the database.
4055**
4056** This routine starts a new transaction if we are not already within
4057** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00004058** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00004059** be set for operations that might fail (due to a constraint) part of
4060** the way through and which will need to undo some writes without having to
4061** rollback the whole transaction. For operations where all constraints
4062** can be checked before any changes are made to the database, it is never
4063** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00004064*/
drh7f0f12e2004-05-21 13:39:50 +00004065void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004066 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00004067 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00004068 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00004069 pToplevel->isMultiWrite |= setStatement;
4070}
4071
drhff738bc2009-09-24 00:09:58 +00004072/*
4073** Indicate that the statement currently under construction might write
4074** more than one entry (example: deleting one row then inserting another,
4075** inserting multiple rows in a table, or inserting a row and index entries.)
4076** If an abort occurs after some of these writes have completed, then it will
4077** be necessary to undo the completed writes.
4078*/
4079void sqlite3MultiWrite(Parse *pParse){
4080 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4081 pToplevel->isMultiWrite = 1;
4082}
4083
dane0af83a2009-09-08 19:15:01 +00004084/*
drhff738bc2009-09-24 00:09:58 +00004085** The code generator calls this routine if is discovers that it is
4086** possible to abort a statement prior to completion. In order to
4087** perform this abort without corrupting the database, we need to make
4088** sure that the statement is protected by a statement transaction.
4089**
4090** Technically, we only need to set the mayAbort flag if the
4091** isMultiWrite flag was previously set. There is a time dependency
4092** such that the abort must occur after the multiwrite. This makes
4093** some statements involving the REPLACE conflict resolution algorithm
4094** go a little faster. But taking advantage of this time dependency
4095** makes it more difficult to prove that the code is correct (in
4096** particular, it prevents us from writing an effective
4097** implementation of sqlite3AssertMayAbort()) and so we have chosen
4098** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00004099*/
4100void sqlite3MayAbort(Parse *pParse){
4101 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4102 pToplevel->mayAbort = 1;
4103}
4104
4105/*
4106** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4107** error. The onError parameter determines which (if any) of the statement
4108** and/or current transaction is rolled back.
4109*/
drhd91c1a12013-02-09 13:58:25 +00004110void sqlite3HaltConstraint(
4111 Parse *pParse, /* Parsing context */
4112 int errCode, /* extended error code */
4113 int onError, /* Constraint type */
4114 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00004115 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4116 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00004117){
dane0af83a2009-09-08 19:15:01 +00004118 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00004119 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00004120 if( onError==OE_Abort ){
4121 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00004122 }
drhd91c1a12013-02-09 13:58:25 +00004123 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00004124 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4125}
4126
4127/*
4128** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4129*/
4130void sqlite3UniqueConstraint(
4131 Parse *pParse, /* Parsing context */
4132 int onError, /* Constraint type */
4133 Index *pIdx /* The index that triggers the constraint */
4134){
4135 char *zErr;
4136 int j;
4137 StrAccum errMsg;
4138 Table *pTab = pIdx->pTable;
4139
drhc0490572015-05-02 11:45:53 +00004140 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
drh8b576422015-08-31 23:09:42 +00004141 if( pIdx->aColExpr ){
4142 sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
4143 }else{
4144 for(j=0; j<pIdx->nKeyCol; j++){
4145 char *zCol;
4146 assert( pIdx->aiColumn[j]>=0 );
4147 zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4148 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
4149 sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
4150 }
drhf9c8ce32013-11-05 13:33:55 +00004151 }
4152 zErr = sqlite3StrAccumFinish(&errMsg);
4153 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004154 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4155 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004156 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004157}
4158
4159
4160/*
4161** Code an OP_Halt due to non-unique rowid.
4162*/
4163void sqlite3RowidConstraint(
4164 Parse *pParse, /* Parsing context */
4165 int onError, /* Conflict resolution algorithm */
4166 Table *pTab /* The table with the non-unique rowid */
4167){
4168 char *zMsg;
4169 int rc;
4170 if( pTab->iPKey>=0 ){
4171 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4172 pTab->aCol[pTab->iPKey].zName);
4173 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4174 }else{
4175 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4176 rc = SQLITE_CONSTRAINT_ROWID;
4177 }
4178 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4179 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004180}
4181
drh4343fea2004-11-05 23:46:15 +00004182/*
4183** Check to see if pIndex uses the collating sequence pColl. Return
4184** true if it does and false if it does not.
4185*/
4186#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004187static int collationMatch(const char *zColl, Index *pIndex){
4188 int i;
drh04491712009-05-13 17:21:13 +00004189 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004190 for(i=0; i<pIndex->nColumn; i++){
4191 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004192 assert( z!=0 || pIndex->aiColumn[i]<0 );
4193 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004194 return 1;
4195 }
drh4343fea2004-11-05 23:46:15 +00004196 }
4197 return 0;
4198}
4199#endif
4200
4201/*
4202** Recompute all indices of pTab that use the collating sequence pColl.
4203** If pColl==0 then recompute all indices of pTab.
4204*/
4205#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004206static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004207 Index *pIndex; /* An index associated with pTab */
4208
4209 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004210 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004211 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4212 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004213 sqlite3RefillIndex(pParse, pIndex, -1);
4214 }
4215 }
4216}
4217#endif
4218
4219/*
4220** Recompute all indices of all tables in all databases where the
4221** indices use the collating sequence pColl. If pColl==0 then recompute
4222** all indices everywhere.
4223*/
4224#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004225static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004226 Db *pDb; /* A single database */
4227 int iDb; /* The database index number */
4228 sqlite3 *db = pParse->db; /* The database connection */
4229 HashElem *k; /* For looping over tables in pDb */
4230 Table *pTab; /* A table in the database */
4231
drh21206082011-04-04 18:22:02 +00004232 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004233 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004234 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004235 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004236 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004237 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004238 }
4239 }
4240}
4241#endif
4242
4243/*
drheee46cf2004-11-06 00:02:48 +00004244** Generate code for the REINDEX command.
4245**
4246** REINDEX -- 1
4247** REINDEX <collation> -- 2
4248** REINDEX ?<database>.?<tablename> -- 3
4249** REINDEX ?<database>.?<indexname> -- 4
4250**
4251** Form 1 causes all indices in all attached databases to be rebuilt.
4252** Form 2 rebuilds all indices in all databases that use the named
4253** collating function. Forms 3 and 4 rebuild the named index or all
4254** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004255*/
4256#ifndef SQLITE_OMIT_REINDEX
4257void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4258 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4259 char *z; /* Name of a table or index */
4260 const char *zDb; /* Name of the database */
4261 Table *pTab; /* A table in the database */
4262 Index *pIndex; /* An index associated with pTab */
4263 int iDb; /* The database index number */
4264 sqlite3 *db = pParse->db; /* The database connection */
4265 Token *pObjName; /* Name of the table or index to be reindexed */
4266
danielk197733a5edc2005-01-27 00:22:02 +00004267 /* Read the database schema. If an error occurs, leave an error message
4268 ** and code in pParse and return NULL. */
4269 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004270 return;
danielk197733a5edc2005-01-27 00:22:02 +00004271 }
4272
drh8af73d42009-05-13 22:58:28 +00004273 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004274 reindexDatabases(pParse, 0);
4275 return;
drhd3001712009-05-12 17:46:53 +00004276 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004277 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004278 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004279 zColl = sqlite3NameFromToken(pParse->db, pName1);
4280 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004281 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004282 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004283 reindexDatabases(pParse, zColl);
4284 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004285 return;
4286 }
drh633e6d52008-07-28 19:34:53 +00004287 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004288 }
4289 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4290 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004291 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004292 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004293 zDb = db->aDb[iDb].zName;
4294 pTab = sqlite3FindTable(db, z, zDb);
4295 if( pTab ){
4296 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004297 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004298 return;
4299 }
4300 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004301 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004302 if( pIndex ){
4303 sqlite3BeginWriteOperation(pParse, 0, iDb);
4304 sqlite3RefillIndex(pParse, pIndex, -1);
4305 return;
4306 }
4307 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4308}
4309#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004310
4311/*
drh2ec2fb22013-11-06 19:59:23 +00004312** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004313**
drh2ec2fb22013-11-06 19:59:23 +00004314** The KeyInfo structure for an index is cached in the Index object.
4315** So there might be multiple references to the returned pointer. The
4316** caller should not try to modify the KeyInfo object.
4317**
4318** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4319** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004320*/
drh2ec2fb22013-11-06 19:59:23 +00004321KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh18b67f32014-12-12 00:20:37 +00004322 int i;
4323 int nCol = pIdx->nColumn;
4324 int nKey = pIdx->nKeyCol;
4325 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004326 if( pParse->nErr ) return 0;
drh18b67f32014-12-12 00:20:37 +00004327 if( pIdx->uniqNotNull ){
4328 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4329 }else{
4330 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
drh41e13e12013-11-07 14:09:39 +00004331 }
drh18b67f32014-12-12 00:20:37 +00004332 if( pKey ){
4333 assert( sqlite3KeyInfoIsWriteable(pKey) );
4334 for(i=0; i<nCol; i++){
4335 char *zColl = pIdx->azColl[i];
4336 assert( zColl!=0 );
4337 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4338 sqlite3LocateCollSeq(pParse, zColl);
4339 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
drh2ec2fb22013-11-06 19:59:23 +00004340 }
drh18b67f32014-12-12 00:20:37 +00004341 if( pParse->nErr ){
4342 sqlite3KeyInfoUnref(pKey);
4343 pKey = 0;
danielk1977b3bf5562006-01-10 17:58:23 +00004344 }
danielk1977b3bf5562006-01-10 17:58:23 +00004345 }
drh18b67f32014-12-12 00:20:37 +00004346 return pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00004347}
drh8b471862014-01-11 13:22:17 +00004348
4349#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004350/*
4351** This routine is invoked once per CTE by the parser while parsing a
4352** WITH clause.
drh8b471862014-01-11 13:22:17 +00004353*/
dan7d562db2014-01-11 19:19:36 +00004354With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004355 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004356 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004357 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004358 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004359 Select *pQuery /* Query used to initialize the table */
4360){
dan4e9119d2014-01-13 15:12:23 +00004361 sqlite3 *db = pParse->db;
4362 With *pNew;
4363 char *zName;
4364
4365 /* Check that the CTE name is unique within this WITH clause. If
4366 ** not, store an error in the Parse structure. */
4367 zName = sqlite3NameFromToken(pParse->db, pName);
4368 if( zName && pWith ){
4369 int i;
4370 for(i=0; i<pWith->nCte; i++){
4371 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004372 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004373 }
4374 }
4375 }
4376
4377 if( pWith ){
4378 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4379 pNew = sqlite3DbRealloc(db, pWith, nByte);
4380 }else{
4381 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4382 }
4383 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004384 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004385
4386 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004387 sqlite3ExprListDelete(db, pArglist);
4388 sqlite3SelectDelete(db, pQuery);
4389 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004390 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004391 }else{
4392 pNew->a[pNew->nCte].pSelect = pQuery;
4393 pNew->a[pNew->nCte].pCols = pArglist;
4394 pNew->a[pNew->nCte].zName = zName;
drh0576bc52015-08-26 11:40:11 +00004395 pNew->a[pNew->nCte].zCteErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004396 pNew->nCte++;
4397 }
4398
4399 return pNew;
drh8b471862014-01-11 13:22:17 +00004400}
4401
dan7d562db2014-01-11 19:19:36 +00004402/*
4403** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004404*/
dan7d562db2014-01-11 19:19:36 +00004405void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004406 if( pWith ){
4407 int i;
4408 for(i=0; i<pWith->nCte; i++){
4409 struct Cte *pCte = &pWith->a[i];
4410 sqlite3ExprListDelete(db, pCte->pCols);
4411 sqlite3SelectDelete(db, pCte->pSelect);
4412 sqlite3DbFree(db, pCte->zName);
4413 }
4414 sqlite3DbFree(db, pWith);
4415 }
drh8b471862014-01-11 13:22:17 +00004416}
4417#endif /* !defined(SQLITE_OMIT_CTE) */