blob: 0960d0cbdf9159d86f205a120f8a2d925d5997e1 [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);
drh80242052004-06-09 00:48:12 +0000195 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000196#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000197 for(i=0; i<pParse->nVtabLock; i++){
198 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
199 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000200 }
drhf30a9692013-11-15 01:10:18 +0000201 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000202#endif
danielk1977c00da102006-01-07 13:21:04 +0000203
204 /* Once all the cookies have been verified and transactions opened,
205 ** obtain the required table-locks. This is a no-op unless the
206 ** shared-cache feature is enabled.
207 */
208 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000209
210 /* Initialize any AUTOINCREMENT data structures required.
211 */
212 sqlite3AutoincrementBegin(pParse);
213
drhf30a9692013-11-15 01:10:18 +0000214 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000215 if( pParse->pConstExpr ){
216 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000217 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000218 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000219 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000220 }
221 }
222
drh0b9f50d2009-06-23 20:28:53 +0000223 /* Finally, jump back to the beginning of the executable code. */
drhaceb31b2014-02-08 01:40:27 +0000224 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
drh80242052004-06-09 00:48:12 +0000225 }
drh71c697e2004-08-08 23:39:19 +0000226 }
227
drh3f7d4e42004-07-24 14:35:58 +0000228
drh80242052004-06-09 00:48:12 +0000229 /* Get the VDBE program ready for execution
230 */
drh126a6e22015-04-15 04:10:50 +0000231 if( v && pParse->nErr==0 && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000232 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000233 /* A minimum of one cursor is required if autoincrement is used
234 * See ticket [a696379c1f08866] */
235 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000236 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000237 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000238 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000239 }else{
drh483750b2003-01-29 18:46:51 +0000240 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000241 }
drha226d052002-09-25 19:04:07 +0000242 pParse->nTab = 0;
243 pParse->nMem = 0;
244 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000245 pParse->nVar = 0;
drha7ab6d82014-07-21 15:44:39 +0000246 DbMaskZero(pParse->cookieMask);
drh75897232000-05-29 14:26:00 +0000247}
248
249/*
drh205f48e2004-11-05 00:43:11 +0000250** Run the parser and code generator recursively in order to generate
251** code for the SQL statement given onto the end of the pParse context
252** currently under construction. When the parser is run recursively
253** this way, the final OP_Halt is not appended and other initialization
254** and finalization steps are omitted because those are handling by the
255** outermost parser.
256**
257** Not everything is nestable. This facility is designed to permit
258** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000259** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000260*/
261void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
262 va_list ap;
263 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000264 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000265 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000266# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
267 char saveBuf[SAVE_SZ];
268
drh205f48e2004-11-05 00:43:11 +0000269 if( pParse->nErr ) return;
270 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
271 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000272 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000273 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000274 if( zSql==0 ){
275 return; /* A malloc must have failed */
276 }
drh205f48e2004-11-05 00:43:11 +0000277 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000278 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
279 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000280 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000281 sqlite3DbFree(db, zErrMsg);
282 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000283 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000284 pParse->nested--;
285}
286
drhd4530972014-09-09 14:47:53 +0000287#if SQLITE_USER_AUTHENTICATION
288/*
289** Return TRUE if zTable is the name of the system table that stores the
290** list of users and their access credentials.
291*/
292int sqlite3UserAuthTable(const char *zTable){
293 return sqlite3_stricmp(zTable, "sqlite_user")==0;
294}
295#endif
296
drh205f48e2004-11-05 00:43:11 +0000297/*
danielk19778a414492004-06-29 08:59:35 +0000298** Locate the in-memory structure that describes a particular database
299** table given the name of that table and (optionally) the name of the
300** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000301**
danielk19778a414492004-06-29 08:59:35 +0000302** If zDatabase is 0, all databases are searched for the table and the
303** first matching table is returned. (No checking for duplicate table
304** names is done.) The search order is TEMP first, then MAIN, then any
305** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000306**
danielk19774adee202004-05-08 08:23:19 +0000307** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000308*/
drh9bb575f2004-09-06 17:24:11 +0000309Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000310 Table *p = 0;
311 int i;
drh9ca95732014-10-24 00:35:58 +0000312
drh21206082011-04-04 18:22:02 +0000313 /* All mutexes are required for schema access. Make sure we hold them. */
314 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
drhd4530972014-09-09 14:47:53 +0000315#if SQLITE_USER_AUTHENTICATION
316 /* Only the admin user is allowed to know that the sqlite_user table
317 ** exists */
drhe933b832014-09-10 17:34:28 +0000318 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
319 return 0;
320 }
drhd4530972014-09-09 14:47:53 +0000321#endif
danielk197753c0f742005-03-29 03:10:59 +0000322 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000323 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000324 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000325 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000326 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
drhd24cc422003-03-27 12:51:24 +0000327 if( p ) break;
328 }
drh74e24cd2002-01-09 03:19:59 +0000329 return p;
drh75897232000-05-29 14:26:00 +0000330}
331
332/*
danielk19778a414492004-06-29 08:59:35 +0000333** Locate the in-memory structure that describes a particular database
334** table given the name of that table and (optionally) the name of the
335** database containing the table. Return NULL if not found. Also leave an
336** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000337**
danielk19778a414492004-06-29 08:59:35 +0000338** The difference between this routine and sqlite3FindTable() is that this
339** routine leaves an error message in pParse->zErrMsg where
340** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000341*/
drhca424112008-01-25 15:04:48 +0000342Table *sqlite3LocateTable(
343 Parse *pParse, /* context in which to report errors */
344 int isView, /* True if looking for a VIEW rather than a TABLE */
345 const char *zName, /* Name of the table we are looking for */
346 const char *zDbase /* Name of the database. Might be NULL */
347){
drha69d9162003-04-17 22:57:53 +0000348 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000349
danielk19778a414492004-06-29 08:59:35 +0000350 /* Read the database schema. If an error occurs, leave an error message
351 ** and code in pParse and return NULL. */
352 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
353 return 0;
354 }
355
danielk19774adee202004-05-08 08:23:19 +0000356 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000357 if( p==0 ){
drhc7435792015-08-20 23:28:18 +0000358 const char *zMsg = isView ? "no such view" : "no such table";
drh51be3872015-08-19 02:32:25 +0000359#ifndef SQLITE_OMIT_VIRTUAL_TABLE
360 /* If zName is the not the name of a table in the schema created using
361 ** CREATE, then check to see if it is the name of an virtual table that
362 ** can be an eponymous virtual table. */
363 Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
364 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
365 return pMod->pEpoTab;
366 }
367#endif
danielk19778a414492004-06-29 08:59:35 +0000368 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000369 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000370 }else{
drhca424112008-01-25 15:04:48 +0000371 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000372 }
drha6ecd332004-06-10 00:29:09 +0000373 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000374 }
drhe933b832014-09-10 17:34:28 +0000375#if SQLITE_USER_AUTHENICATION
376 else if( pParse->db->auth.authLevel<UAUTH_User ){
377 sqlite3ErrorMsg(pParse, "user not authenticated");
378 p = 0;
379 }
380#endif
drha69d9162003-04-17 22:57:53 +0000381 return p;
382}
383
384/*
dan41fb5cd2012-10-04 19:33:00 +0000385** Locate the table identified by *p.
386**
387** This is a wrapper around sqlite3LocateTable(). The difference between
388** sqlite3LocateTable() and this function is that this function restricts
389** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
390** non-NULL if it is part of a view or trigger program definition. See
391** sqlite3FixSrcList() for details.
392*/
393Table *sqlite3LocateTableItem(
394 Parse *pParse,
395 int isView,
396 struct SrcList_item *p
397){
398 const char *zDb;
399 assert( p->pSchema==0 || p->zDatabase==0 );
400 if( p->pSchema ){
401 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
402 zDb = pParse->db->aDb[iDb].zName;
403 }else{
404 zDb = p->zDatabase;
405 }
406 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
407}
408
409/*
drha69d9162003-04-17 22:57:53 +0000410** Locate the in-memory structure that describes
411** a particular index given the name of that index
412** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000413** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000414**
415** If zDatabase is 0, all databases are searched for the
416** table and the first matching index is returned. (No checking
417** for duplicate index names is done.) The search order is
418** TEMP first, then MAIN, then any auxiliary databases added
419** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000420*/
drh9bb575f2004-09-06 17:24:11 +0000421Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000422 Index *p = 0;
423 int i;
drh21206082011-04-04 18:22:02 +0000424 /* All mutexes are required for schema access. Make sure we hold them. */
425 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000426 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000427 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000428 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000429 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000430 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000431 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000432 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000433 if( p ) break;
434 }
drh74e24cd2002-01-09 03:19:59 +0000435 return p;
drh75897232000-05-29 14:26:00 +0000436}
437
438/*
drh956bc922004-07-24 17:38:29 +0000439** Reclaim the memory used by an index
440*/
dan1feeaed2010-07-23 15:41:47 +0000441static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000442#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000443 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000444#endif
drh1fe05372013-07-31 18:12:26 +0000445 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000446 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000447 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh75b170b2014-10-04 00:07:44 +0000448#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
449 sqlite3_free(p->aiRowEst);
450#endif
drh633e6d52008-07-28 19:34:53 +0000451 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000452}
453
454/*
drhc96d8532005-05-03 12:30:33 +0000455** For the index called zIdxName which is found in the database iDb,
456** unlike that index from its Table then remove the index from
457** the index hash table and free all memory structures associated
458** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000459*/
drh9bb575f2004-09-06 17:24:11 +0000460void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000461 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000462 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000463
drh21206082011-04-04 18:22:02 +0000464 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
465 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000466 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000467 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000468 if( pIndex->pTable->pIndex==pIndex ){
469 pIndex->pTable->pIndex = pIndex->pNext;
470 }else{
471 Index *p;
drh04491712009-05-13 17:21:13 +0000472 /* Justification of ALWAYS(); The index must be on the list of
473 ** indices. */
474 p = pIndex->pTable->pIndex;
475 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
476 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000477 p->pNext = pIndex->pNext;
478 }
drh5e00f6c2001-09-13 13:46:56 +0000479 }
dan1feeaed2010-07-23 15:41:47 +0000480 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000481 }
drh956bc922004-07-24 17:38:29 +0000482 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000483}
484
485/*
drh81028a42012-05-15 18:28:27 +0000486** Look through the list of open database files in db->aDb[] and if
487** any have been closed, remove them from the list. Reallocate the
488** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000489**
drh81028a42012-05-15 18:28:27 +0000490** Entry 0 (the "main" database) and entry 1 (the "temp" database)
491** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000492*/
drh81028a42012-05-15 18:28:27 +0000493void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000494 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000495 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000496 struct Db *pDb = &db->aDb[i];
497 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000498 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000499 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000500 continue;
501 }
502 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000503 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000504 }
drh8bf8dc92003-05-17 17:35:10 +0000505 j++;
drh1c2d8412003-03-31 00:30:47 +0000506 }
507 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
508 db->nDb = j;
509 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
510 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000511 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000512 db->aDb = db->aDbStatic;
513 }
drhe0bc4042002-06-25 01:09:11 +0000514}
515
516/*
drh81028a42012-05-15 18:28:27 +0000517** Reset the schema for the database at index iDb. Also reset the
518** TEMP schema.
519*/
520void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000521 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000522 assert( iDb<db->nDb );
523
524 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000525 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000526 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
527 assert( pDb->pSchema!=0 );
528 sqlite3SchemaClear(pDb->pSchema);
529
530 /* If any database other than TEMP is reset, then also reset TEMP
531 ** since TEMP might be holding triggers that reference tables in the
532 ** other database.
533 */
534 if( iDb!=1 ){
535 pDb = &db->aDb[1];
536 assert( pDb->pSchema!=0 );
537 sqlite3SchemaClear(pDb->pSchema);
538 }
539 return;
540}
541
542/*
543** Erase all schema information from all attached databases (including
544** "main" and "temp") for a single database connection.
545*/
546void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
547 int i;
548 sqlite3BtreeEnterAll(db);
549 for(i=0; i<db->nDb; i++){
550 Db *pDb = &db->aDb[i];
551 if( pDb->pSchema ){
552 sqlite3SchemaClear(pDb->pSchema);
553 }
554 }
555 db->flags &= ~SQLITE_InternChanges;
556 sqlite3VtabUnlockList(db);
557 sqlite3BtreeLeaveAll(db);
558 sqlite3CollapseDatabaseArray(db);
559}
560
561/*
drhe0bc4042002-06-25 01:09:11 +0000562** This routine is called when a commit occurs.
563*/
drh9bb575f2004-09-06 17:24:11 +0000564void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000565 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000566}
567
568/*
dand46def72010-07-24 11:28:28 +0000569** Delete memory allocated for the column names of a table or view (the
570** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000571*/
drh51be3872015-08-19 02:32:25 +0000572void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000573 int i;
574 Column *pCol;
575 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000576 if( (pCol = pTable->aCol)!=0 ){
577 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000578 sqlite3DbFree(db, pCol->zName);
579 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000580 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000581 sqlite3DbFree(db, pCol->zType);
582 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000583 }
drh633e6d52008-07-28 19:34:53 +0000584 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000585 }
drh956bc922004-07-24 17:38:29 +0000586}
587
588/*
drh75897232000-05-29 14:26:00 +0000589** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000590** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000591**
592** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000593** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000594** memory structures of the indices and foreign keys associated with
595** the table.
drh29ddd3a2012-05-15 12:49:32 +0000596**
597** The db parameter is optional. It is needed if the Table object
598** contains lookaside memory. (Table objects in the schema do not use
599** lookaside memory, but some ephemeral Table objects do.) Or the
600** db parameter can be used with db->pnBytesFreed to measure the memory
601** used by the Table object.
drh75897232000-05-29 14:26:00 +0000602*/
dan1feeaed2010-07-23 15:41:47 +0000603void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000604 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000605 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000606
dand46def72010-07-24 11:28:28 +0000607 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000608
drhed8a3bb2005-06-06 21:19:56 +0000609 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000610 if( !pTable ) return;
611 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000612
drh29ddd3a2012-05-15 12:49:32 +0000613 /* Record the number of outstanding lookaside allocations in schema Tables
614 ** prior to doing any free() operations. Since schema Tables do not use
615 ** lookaside, this number should not change. */
616 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
617 db->lookaside.nOut : 0 );
618
dand46def72010-07-24 11:28:28 +0000619 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000620 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
621 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000622 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000623 if( !db || db->pnBytesFreed==0 ){
624 char *zName = pIndex->zName;
625 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000626 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000627 );
drh21206082011-04-04 18:22:02 +0000628 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000629 assert( pOld==pIndex || pOld==0 );
630 }
631 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000632 }
633
dan1da40a32009-09-19 17:00:31 +0000634 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000635 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000636
637 /* Delete the Table structure itself.
638 */
drh51be3872015-08-19 02:32:25 +0000639 sqlite3DeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000640 sqlite3DbFree(db, pTable->zName);
641 sqlite3DbFree(db, pTable->zColAff);
642 sqlite3SelectDelete(db, pTable->pSelect);
drh2938f922012-03-07 19:13:29 +0000643 sqlite3ExprListDelete(db, pTable->pCheck);
drh078e4082010-07-28 19:17:51 +0000644#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000645 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000646#endif
drh633e6d52008-07-28 19:34:53 +0000647 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000648
649 /* Verify that no lookaside memory was used by schema tables */
650 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000651}
652
653/*
drh5edc3122001-09-13 21:53:09 +0000654** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000655** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000656*/
drh9bb575f2004-09-06 17:24:11 +0000657void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000658 Table *p;
drh956bc922004-07-24 17:38:29 +0000659 Db *pDb;
660
drhd229ca92002-01-09 13:30:41 +0000661 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000662 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000663 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000664 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000665 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000666 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000667 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000668 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000669 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000670}
671
672/*
drha99db3b2004-06-19 14:49:12 +0000673** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000674** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000675** is obtained from sqliteMalloc() and must be freed by the calling
676** function.
drh75897232000-05-29 14:26:00 +0000677**
drh24fb6272009-05-01 21:13:36 +0000678** Any quotation marks (ex: "name", 'name', [name], or `name`) that
679** surround the body of the token are removed.
680**
drhc96d8532005-05-03 12:30:33 +0000681** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000682** are not \000 terminated and are not persistent. The returned string
683** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000684*/
drh17435752007-08-16 04:30:38 +0000685char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000686 char *zName;
687 if( pName ){
drh17435752007-08-16 04:30:38 +0000688 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000689 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000690 }else{
691 zName = 0;
692 }
drh75897232000-05-29 14:26:00 +0000693 return zName;
694}
695
696/*
danielk1977cbb18d22004-05-28 11:37:27 +0000697** Open the sqlite_master table stored in database number iDb for
698** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000699*/
danielk1977c00da102006-01-07 13:21:04 +0000700void sqlite3OpenMasterTable(Parse *p, int iDb){
701 Vdbe *v = sqlite3GetVdbe(p);
702 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000703 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000704 if( p->nTab==0 ){
705 p->nTab = 1;
706 }
drhe0bc4042002-06-25 01:09:11 +0000707}
708
709/*
danielk197704103022009-02-03 16:51:24 +0000710** Parameter zName points to a nul-terminated buffer containing the name
711** of a database ("main", "temp" or the name of an attached db). This
712** function returns the index of the named database in db->aDb[], or
713** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000714*/
danielk197704103022009-02-03 16:51:24 +0000715int sqlite3FindDbName(sqlite3 *db, const char *zName){
716 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000717 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000718 Db *pDb;
719 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000720 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000721 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000722 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000723 break;
drh73c42a12004-11-20 18:13:10 +0000724 }
danielk1977cbb18d22004-05-28 11:37:27 +0000725 }
726 }
danielk1977576ec6b2005-01-21 11:55:25 +0000727 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000728}
729
danielk197704103022009-02-03 16:51:24 +0000730/*
731** The token *pName contains the name of a database (either "main" or
732** "temp" or the name of an attached db). This routine returns the
733** index of the named database in db->aDb[], or -1 if the named db
734** does not exist.
735*/
736int sqlite3FindDb(sqlite3 *db, Token *pName){
737 int i; /* Database number */
738 char *zName; /* Name we are searching for */
739 zName = sqlite3NameFromToken(db, pName);
740 i = sqlite3FindDbName(db, zName);
741 sqlite3DbFree(db, zName);
742 return i;
743}
744
drh0e3d7472004-06-19 17:33:07 +0000745/* The table or view or trigger name is passed to this routine via tokens
746** pName1 and pName2. If the table name was fully qualified, for example:
747**
748** CREATE TABLE xxx.yyy (...);
749**
750** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
751** the table name is not fully qualified, i.e.:
752**
753** CREATE TABLE yyy(...);
754**
755** Then pName1 is set to "yyy" and pName2 is "".
756**
757** This routine sets the *ppUnqual pointer to point at the token (pName1 or
758** pName2) that stores the unqualified table name. The index of the
759** database "xxx" is returned.
760*/
danielk1977ef2cb632004-05-29 02:37:19 +0000761int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000762 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000763 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000764 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
765 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000766){
drh0e3d7472004-06-19 17:33:07 +0000767 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000768 sqlite3 *db = pParse->db;
769
drhc4a64fa2009-05-11 20:53:28 +0000770 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000771 if( db->init.busy ) {
772 sqlite3ErrorMsg(pParse, "corrupt database");
shanedcc50b72008-11-13 18:29:50 +0000773 return -1;
774 }
danielk1977cbb18d22004-05-28 11:37:27 +0000775 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000776 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000777 if( iDb<0 ){
778 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000779 return -1;
780 }
781 }else{
782 assert( db->init.iDb==0 || db->init.busy );
783 iDb = db->init.iDb;
784 *pUnqual = pName1;
785 }
786 return iDb;
787}
788
789/*
danielk1977d8123362004-06-12 09:25:12 +0000790** This routine is used to check if the UTF-8 string zName is a legal
791** unqualified name for a new schema object (table, index, view or
792** trigger). All names are legal except those that begin with the string
793** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
794** is reserved for internal use.
795*/
796int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000797 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000798 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000799 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000800 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
801 return SQLITE_ERROR;
802 }
803 return SQLITE_OK;
804}
805
806/*
drh44156282013-10-23 22:23:03 +0000807** Return the PRIMARY KEY index of a table
808*/
809Index *sqlite3PrimaryKeyIndex(Table *pTab){
810 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000811 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000812 return p;
813}
814
815/*
816** Return the column of index pIdx that corresponds to table
817** column iCol. Return -1 if not found.
818*/
819i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
820 int i;
821 for(i=0; i<pIdx->nColumn; i++){
822 if( iCol==pIdx->aiColumn[i] ) return i;
823 }
824 return -1;
825}
826
827/*
drh75897232000-05-29 14:26:00 +0000828** Begin constructing a new table representation in memory. This is
829** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000830** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000831** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000832** flag is true if the table should be stored in the auxiliary database
833** file instead of in the main database file. This is normally the case
834** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000835** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000836**
drhf57b3392001-10-08 13:22:32 +0000837** The new table record is initialized and put in pParse->pNewTable.
838** As more of the CREATE TABLE statement is parsed, additional action
839** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000840** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000841** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000842*/
danielk19774adee202004-05-08 08:23:19 +0000843void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000844 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000845 Token *pName1, /* First part of the name of the table or view */
846 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000847 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000848 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000849 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000850 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000851){
drh75897232000-05-29 14:26:00 +0000852 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000853 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000854 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000855 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000856 int iDb; /* Database number to create the table in */
857 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000858
danielk1977cbb18d22004-05-28 11:37:27 +0000859 /* The table or view name to create is passed to this routine via tokens
860 ** pName1 and pName2. If the table name was fully qualified, for example:
861 **
862 ** CREATE TABLE xxx.yyy (...);
863 **
864 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
865 ** the table name is not fully qualified, i.e.:
866 **
867 ** CREATE TABLE yyy(...);
868 **
869 ** Then pName1 is set to "yyy" and pName2 is "".
870 **
871 ** The call below sets the pName pointer to point at the token (pName1 or
872 ** pName2) that stores the unqualified table name. The variable iDb is
873 ** set to the index of the database that the table or view is to be
874 ** created in.
875 */
danielk1977ef2cb632004-05-29 02:37:19 +0000876 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000877 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000878 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
879 /* If creating a temp table, the name may not be qualified. Unless
880 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000881 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000882 return;
883 }
danielk197753c0f742005-03-29 03:10:59 +0000884 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000885
886 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000887 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000888 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000889 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000890 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000891 }
drh1d85d932004-02-14 23:05:52 +0000892 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000893#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000894 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000895 {
896 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000897 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000898 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000899 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000900 }
drhe5f9c642003-01-13 23:27:31 +0000901 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000902 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000903 code = SQLITE_CREATE_TEMP_VIEW;
904 }else{
905 code = SQLITE_CREATE_VIEW;
906 }
907 }else{
danielk197753c0f742005-03-29 03:10:59 +0000908 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000909 code = SQLITE_CREATE_TEMP_TABLE;
910 }else{
911 code = SQLITE_CREATE_TABLE;
912 }
913 }
danielk1977f1a381e2006-06-16 08:01:02 +0000914 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000915 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000916 }
917 }
918#endif
drhf57b3392001-10-08 13:22:32 +0000919
drhf57b3392001-10-08 13:22:32 +0000920 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000921 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000922 ** it does. The exception is if the statement being parsed was passed
923 ** to an sqlite3_declare_vtab() call. In that case only the column names
924 ** and types will be used, so there is no need to test for namespace
925 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000926 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000927 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000928 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000929 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
930 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000931 }
dana16d1062010-09-28 17:37:28 +0000932 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000933 if( pTable ){
934 if( !noErr ){
935 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000936 }else{
drh33c59ec2015-04-19 20:39:17 +0000937 assert( !db->init.busy || CORRUPT_DB );
dan7687c832011-04-09 15:39:02 +0000938 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000939 }
940 goto begin_table_error;
941 }
drh8a8a0d12010-09-28 20:26:44 +0000942 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000943 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
944 goto begin_table_error;
945 }
drh75897232000-05-29 14:26:00 +0000946 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000947
danielk197726783a52007-08-29 14:06:22 +0000948 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000949 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000950 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000951 pParse->rc = SQLITE_NOMEM;
952 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000953 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000954 }
drh75897232000-05-29 14:26:00 +0000955 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000956 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000957 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000958 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000959 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000960 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000961 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000962
drh4794f732004-11-05 17:17:50 +0000963 /* If this is the magic sqlite_sequence table used by autoincrement,
964 ** then record a pointer to this table in the main database structure
965 ** so that INSERT can find the table easily.
966 */
967#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000968 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000969 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000970 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000971 }
972#endif
973
drh17f71932002-02-21 12:01:27 +0000974 /* Begin generating the code that will insert the table record into
975 ** the SQLITE_MASTER table. Note in particular that we must go ahead
976 ** and allocate the record number for the table entry now. Before any
977 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
978 ** indices to be created and the table record must come before the
979 ** indices. Hence, the record number for the table must be allocated
980 ** now.
981 */
danielk19774adee202004-05-08 08:23:19 +0000982 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000983 int j1;
drhe321c292006-01-12 01:56:43 +0000984 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000985 int reg1, reg2, reg3;
drh0dd5cda2015-06-16 16:39:01 +0000986 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +0000987
danielk197720b1eaf2006-07-26 16:22:14 +0000988#ifndef SQLITE_OMIT_VIRTUALTABLE
989 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000990 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000991 }
992#endif
993
danielk197736963fd2005-02-19 08:18:05 +0000994 /* If the file format and encoding in the database have not been set,
995 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000996 */
drhb7654112008-01-12 12:48:07 +0000997 reg1 = pParse->regRowid = ++pParse->nMem;
998 reg2 = pParse->regRoot = ++pParse->nMem;
999 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +00001000 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +00001001 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +00001002 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +00001003 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +00001004 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +00001005 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001006 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +00001007 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001008 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +00001009 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +00001010
drh4794f732004-11-05 17:17:50 +00001011 /* This just creates a place-holder record in the sqlite_master table.
1012 ** The record created does not contain anything yet. It will be replaced
1013 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001014 **
drh0fa991b2009-03-21 16:19:26 +00001015 ** The rowid for the new entry is left in register pParse->regRowid.
1016 ** The root page number of the new table is left in reg pParse->regRoot.
1017 ** The rowid and root page number values are needed by the code that
1018 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001019 */
danielk1977f1a381e2006-06-16 08:01:02 +00001020#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1021 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001022 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001023 }else
1024#endif
1025 {
drh8a120f82013-11-01 17:59:53 +00001026 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001027 }
danielk1977c00da102006-01-07 13:21:04 +00001028 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001029 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1030 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1031 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1032 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001033 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001034 }
drh23bf66d2004-12-14 03:34:34 +00001035
1036 /* Normal (non-error) return. */
1037 return;
1038
1039 /* If an error occurs, we jump here */
1040begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001041 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001042 return;
drh75897232000-05-29 14:26:00 +00001043}
1044
1045/*
danielk1977c60e9b82005-01-31 12:42:29 +00001046** This macro is used to compare two strings in a case-insensitive manner.
1047** It is slightly faster than calling sqlite3StrICmp() directly, but
1048** produces larger code.
1049**
1050** WARNING: This macro is not compatible with the strcmp() family. It
1051** returns true if the two strings are equal, otherwise false.
1052*/
1053#define STRICMP(x, y) (\
1054sqlite3UpperToLower[*(unsigned char *)(x)]== \
1055sqlite3UpperToLower[*(unsigned char *)(y)] \
1056&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1057
1058/*
drh75897232000-05-29 14:26:00 +00001059** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001060**
1061** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001062** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001063** first to get things going. Then this routine is called for each
1064** column.
drh75897232000-05-29 14:26:00 +00001065*/
danielk19774adee202004-05-08 08:23:19 +00001066void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001067 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001068 int i;
drha99db3b2004-06-19 14:49:12 +00001069 char *z;
drhc9b84a12002-06-20 11:36:48 +00001070 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001071 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001072 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001073#if SQLITE_MAX_COLUMN
1074 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001075 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1076 return;
1077 }
drhbb4957f2008-03-20 14:03:29 +00001078#endif
danielk1977ae74e032008-12-23 11:11:51 +00001079 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001080 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001081 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001082 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001083 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001084 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001085 return;
1086 }
1087 }
drh75897232000-05-29 14:26:00 +00001088 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001089 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001090 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001091 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001092 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001093 return;
1094 }
drh6d4abfb2001-10-22 02:58:08 +00001095 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001096 }
drhc9b84a12002-06-20 11:36:48 +00001097 pCol = &p->aCol[p->nCol];
1098 memset(pCol, 0, sizeof(p->aCol[0]));
1099 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001100
1101 /* If there is no type specified, columns have the default affinity
drh05883a32015-06-02 15:32:08 +00001102 ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
danielk19774f057f92004-06-08 00:02:33 +00001103 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001104 */
drh05883a32015-06-02 15:32:08 +00001105 pCol->affinity = SQLITE_AFF_BLOB;
drhfdaac672013-10-04 15:30:21 +00001106 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001107 p->nCol++;
drh75897232000-05-29 14:26:00 +00001108}
1109
1110/*
drh382c0242001-10-06 16:33:02 +00001111** This routine is called by the parser while in the middle of
1112** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1113** been seen on a column. This routine sets the notNull flag on
1114** the column currently under construction.
1115*/
danielk19774adee202004-05-08 08:23:19 +00001116void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001117 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001118 p = pParse->pNewTable;
1119 if( p==0 || NEVER(p->nCol<1) ) return;
1120 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001121}
1122
1123/*
danielk197752a83fb2005-01-31 12:56:44 +00001124** Scan the column type name zType (length nType) and return the
1125** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001126**
1127** This routine does a case-independent search of zType for the
1128** substrings in the following table. If one of the substrings is
1129** found, the corresponding affinity is returned. If zType contains
1130** more than one of the substrings, entries toward the top of
1131** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001132** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001133**
1134** Substring | Affinity
1135** --------------------------------
1136** 'INT' | SQLITE_AFF_INTEGER
1137** 'CHAR' | SQLITE_AFF_TEXT
1138** 'CLOB' | SQLITE_AFF_TEXT
1139** 'TEXT' | SQLITE_AFF_TEXT
drh05883a32015-06-02 15:32:08 +00001140** 'BLOB' | SQLITE_AFF_BLOB
drh8a512562005-11-14 22:29:05 +00001141** 'REAL' | SQLITE_AFF_REAL
1142** 'FLOA' | SQLITE_AFF_REAL
1143** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001144**
1145** If none of the substrings in the above table are found,
1146** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001147*/
drhfdaac672013-10-04 15:30:21 +00001148char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001149 u32 h = 0;
1150 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001151 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001152
drhfdaac672013-10-04 15:30:21 +00001153 if( zIn==0 ) return aff;
1154 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001155 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001156 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001157 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001158 aff = SQLITE_AFF_TEXT;
1159 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001160 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1161 aff = SQLITE_AFF_TEXT;
1162 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1163 aff = SQLITE_AFF_TEXT;
1164 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001165 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
drh05883a32015-06-02 15:32:08 +00001166 aff = SQLITE_AFF_BLOB;
drhd3037a42013-10-04 18:29:25 +00001167 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001168#ifndef SQLITE_OMIT_FLOATING_POINT
1169 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1170 && aff==SQLITE_AFF_NUMERIC ){
1171 aff = SQLITE_AFF_REAL;
1172 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1173 && aff==SQLITE_AFF_NUMERIC ){
1174 aff = SQLITE_AFF_REAL;
1175 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1176 && aff==SQLITE_AFF_NUMERIC ){
1177 aff = SQLITE_AFF_REAL;
1178#endif
danielk1977201f7162005-02-01 02:13:29 +00001179 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001180 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001181 break;
danielk197752a83fb2005-01-31 12:56:44 +00001182 }
1183 }
drhd3037a42013-10-04 18:29:25 +00001184
1185 /* If pszEst is not NULL, store an estimate of the field size. The
1186 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001187 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001188 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001189 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001190 if( zChar ){
1191 while( zChar[0] ){
1192 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001193 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001194 sqlite3GetInt32(zChar, &v);
1195 v = v/4 + 1;
1196 if( v>255 ) v = 255;
1197 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1198 break;
1199 }
1200 zChar++;
drhfdaac672013-10-04 15:30:21 +00001201 }
drhd3037a42013-10-04 18:29:25 +00001202 }else{
1203 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001204 }
drhfdaac672013-10-04 15:30:21 +00001205 }
1206 }
danielk1977b3dff962005-02-01 01:21:55 +00001207 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001208}
1209
1210/*
drh382c0242001-10-06 16:33:02 +00001211** This routine is called by the parser while in the middle of
1212** parsing a CREATE TABLE statement. The pFirst token is the first
1213** token in the sequence of tokens that describe the type of the
1214** column currently under construction. pLast is the last token
1215** in the sequence. Use this information to construct a string
1216** that contains the typename of the column and store that string
1217** in zType.
1218*/
drh487e2622005-06-25 18:42:14 +00001219void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001220 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001221 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001222
drhc4a64fa2009-05-11 20:53:28 +00001223 p = pParse->pNewTable;
1224 if( p==0 || NEVER(p->nCol<1) ) return;
1225 pCol = &p->aCol[p->nCol-1];
drh5f1d2fa2015-04-19 21:59:19 +00001226 assert( pCol->zType==0 || CORRUPT_DB );
1227 sqlite3DbFree(pParse->db, pCol->zType);
drhc4a64fa2009-05-11 20:53:28 +00001228 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001229 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001230}
1231
1232/*
danielk19777977a172004-11-09 12:44:37 +00001233** The expression is the default value for the most recently added column
1234** of the table currently under construction.
1235**
1236** Default value expressions must be constant. Raise an exception if this
1237** is not the case.
drhd9b02572001-04-15 00:37:09 +00001238**
1239** This routine is called by the parser while in the middle of
1240** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001241*/
drhb7916a72009-05-27 10:31:29 +00001242void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001243 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001244 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001245 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001246 p = pParse->pNewTable;
1247 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001248 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001249 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001250 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1251 pCol->zName);
1252 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001253 /* A copy of pExpr is used instead of the original, as pExpr contains
1254 ** tokens that point to volatile memory. The 'span' of the expression
1255 ** is required by pragma table_info.
1256 */
drh633e6d52008-07-28 19:34:53 +00001257 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001258 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1259 sqlite3DbFree(db, pCol->zDflt);
1260 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001261 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001262 }
danielk19777977a172004-11-09 12:44:37 +00001263 }
drhb7916a72009-05-27 10:31:29 +00001264 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001265}
1266
1267/*
drh4a324312001-12-21 14:30:42 +00001268** Designate the PRIMARY KEY for the table. pList is a list of names
1269** of columns that form the primary key. If pList is NULL, then the
1270** most recently added column of the table is the primary key.
1271**
1272** A table can have at most one primary key. If the table already has
1273** a primary key (and this is the second primary key) then create an
1274** error.
1275**
1276** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001277** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001278** field of the table under construction to be the index of the
1279** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1280** no INTEGER PRIMARY KEY.
1281**
1282** If the key is not an INTEGER PRIMARY KEY, then create a unique
1283** index for the key. No index is created for INTEGER PRIMARY KEYs.
1284*/
drh205f48e2004-11-05 00:43:11 +00001285void sqlite3AddPrimaryKey(
1286 Parse *pParse, /* Parsing context */
1287 ExprList *pList, /* List of field names to be indexed */
1288 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001289 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1290 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001291){
drh4a324312001-12-21 14:30:42 +00001292 Table *pTab = pParse->pNewTable;
1293 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001294 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001295 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001296 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001297 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001298 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001299 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001300 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001301 }
drh7d10d5a2008-08-20 16:35:10 +00001302 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001303 if( pList==0 ){
1304 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001305 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001306 zType = pTab->aCol[iCol].zType;
1307 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001308 }else{
drh8ea30bf2013-10-22 01:18:17 +00001309 nTerm = pList->nExpr;
1310 for(i=0; i<nTerm; i++){
drh108aa002015-08-24 20:21:20 +00001311 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1312 if( pCExpr && pCExpr->op==TK_ID ){
1313 const char *zCName = pCExpr->u.zToken;
1314 for(iCol=0; iCol<pTab->nCol; iCol++){
1315 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
1316 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1317 zType = pTab->aCol[iCol].zType;
1318 break;
1319 }
drhd3d39e92004-05-20 22:16:29 +00001320 }
drh78100cc2003-08-23 22:40:53 +00001321 }
drh4a324312001-12-21 14:30:42 +00001322 }
1323 }
drh8ea30bf2013-10-22 01:18:17 +00001324 if( nTerm==1
1325 && zType && sqlite3StrICmp(zType, "INTEGER")==0
drhbc622bc2015-08-24 15:39:42 +00001326 && sortOrder!=SQLITE_SO_DESC
drh8ea30bf2013-10-22 01:18:17 +00001327 ){
drh4a324312001-12-21 14:30:42 +00001328 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001329 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001330 assert( autoInc==0 || autoInc==1 );
1331 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001332 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001333 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001334#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001335 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1336 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001337#endif
drh4a324312001-12-21 14:30:42 +00001338 }else{
dan1da40a32009-09-19 17:00:31 +00001339 Index *p;
drh8a9789b2013-08-01 03:36:59 +00001340 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001341 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001342 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001343 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
dan1da40a32009-09-19 17:00:31 +00001344 }
drhe0194f22003-02-26 13:52:51 +00001345 pList = 0;
drh4a324312001-12-21 14:30:42 +00001346 }
drhe0194f22003-02-26 13:52:51 +00001347
1348primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001349 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001350 return;
drh4a324312001-12-21 14:30:42 +00001351}
1352
1353/*
drhffe07b22005-11-03 00:41:17 +00001354** Add a new CHECK constraint to the table currently under construction.
1355*/
1356void sqlite3AddCheckConstraint(
1357 Parse *pParse, /* Parsing context */
1358 Expr *pCheckExpr /* The check expression */
1359){
1360#ifndef SQLITE_OMIT_CHECK
1361 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001362 sqlite3 *db = pParse->db;
1363 if( pTab && !IN_DECLARE_VTAB
1364 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1365 ){
drh2938f922012-03-07 19:13:29 +00001366 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1367 if( pParse->constraintName.n ){
1368 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1369 }
drh33e619f2009-05-28 01:00:55 +00001370 }else
drhffe07b22005-11-03 00:41:17 +00001371#endif
drh33e619f2009-05-28 01:00:55 +00001372 {
drh2938f922012-03-07 19:13:29 +00001373 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001374 }
drhffe07b22005-11-03 00:41:17 +00001375}
1376
1377/*
drhd3d39e92004-05-20 22:16:29 +00001378** Set the collation function of the most recently parsed table column
1379** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001380*/
danielk197739002502007-11-12 09:50:26 +00001381void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001382 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001383 int i;
danielk197739002502007-11-12 09:50:26 +00001384 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001385 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001386
danielk1977b8cbb872006-06-19 05:33:45 +00001387 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001388 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001389 db = pParse->db;
1390 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001391 if( !zColl ) return;
1392
drhc4a64fa2009-05-11 20:53:28 +00001393 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001394 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001395 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001396 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001397
1398 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1399 ** then an index may have been created on this column before the
1400 ** collation type was added. Correct this if it is the case.
1401 */
1402 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001403 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001404 if( pIdx->aiColumn[0]==i ){
1405 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001406 }
1407 }
danielk197739002502007-11-12 09:50:26 +00001408 }else{
drh633e6d52008-07-28 19:34:53 +00001409 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001410 }
danielk19777cedc8d2004-06-10 10:50:08 +00001411}
1412
danielk1977466be562004-06-10 02:16:01 +00001413/*
1414** This function returns the collation sequence for database native text
1415** encoding identified by the string zName, length nName.
1416**
1417** If the requested collation sequence is not available, or not available
1418** in the database native encoding, the collation factory is invoked to
1419** request it. If the collation factory does not supply such a sequence,
1420** and the sequence is available in another text encoding, then that is
1421** returned instead.
1422**
1423** If no versions of the requested collations sequence are available, or
1424** another error occurs, NULL is returned and an error message written into
1425** pParse.
drha34001c2007-02-02 12:44:37 +00001426**
1427** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1428** invokes the collation factory if the named collation cannot be found
1429** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001430**
1431** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001432*/
drhc4a64fa2009-05-11 20:53:28 +00001433CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001434 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001435 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001436 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001437 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001438
drhc4a64fa2009-05-11 20:53:28 +00001439 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001440 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001441 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001442 }
1443
danielk19770202b292004-06-09 09:55:16 +00001444 return pColl;
1445}
1446
1447
drh8e2ca022002-06-17 17:07:19 +00001448/*
drh3f7d4e42004-07-24 14:35:58 +00001449** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001450**
1451** The schema cookie is used to determine when the schema for the
1452** database changes. After each schema change, the cookie value
1453** changes. When a process first reads the schema it records the
1454** cookie. Thereafter, whenever it goes to access the database,
1455** it checks the cookie to make sure the schema has not changed
1456** since it was last read.
1457**
1458** This plan is not completely bullet-proof. It is possible for
1459** the schema to change multiple times and for the cookie to be
1460** set back to prior value. But schema changes are infrequent
1461** and the probability of hitting the same cookie value is only
1462** 1 chance in 2^32. So we're safe enough.
1463*/
drh9cbf3422008-01-17 16:22:13 +00001464void sqlite3ChangeCookie(Parse *pParse, int iDb){
1465 int r1 = sqlite3GetTempReg(pParse);
1466 sqlite3 *db = pParse->db;
1467 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001468 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001469 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001470 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001471 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001472}
1473
1474/*
drh969fa7c2002-02-18 18:30:32 +00001475** Measure the number of characters needed to output the given
1476** identifier. The number returned includes any quotes used
1477** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001478**
1479** The estimate is conservative. It might be larger that what is
1480** really needed.
drh969fa7c2002-02-18 18:30:32 +00001481*/
1482static int identLength(const char *z){
1483 int n;
drh17f71932002-02-21 12:01:27 +00001484 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001485 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001486 }
drh234c39d2004-07-24 03:30:47 +00001487 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001488}
1489
1490/*
danielk19771b870de2009-03-14 08:37:23 +00001491** The first parameter is a pointer to an output buffer. The second
1492** parameter is a pointer to an integer that contains the offset at
1493** which to write into the output buffer. This function copies the
1494** nul-terminated string pointed to by the third parameter, zSignedIdent,
1495** to the specified offset in the buffer and updates *pIdx to refer
1496** to the first byte after the last byte written before returning.
1497**
1498** If the string zSignedIdent consists entirely of alpha-numeric
1499** characters, does not begin with a digit and is not an SQL keyword,
1500** then it is copied to the output buffer exactly as it is. Otherwise,
1501** it is quoted using double-quotes.
1502*/
drhc4a64fa2009-05-11 20:53:28 +00001503static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001504 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001505 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001506 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001507
drh17f71932002-02-21 12:01:27 +00001508 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001509 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001510 }
drhc7407522014-01-10 20:38:12 +00001511 needQuote = sqlite3Isdigit(zIdent[0])
1512 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1513 || zIdent[j]!=0
1514 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001515
drh234c39d2004-07-24 03:30:47 +00001516 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001517 for(j=0; zIdent[j]; j++){
1518 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001519 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001520 }
drh234c39d2004-07-24 03:30:47 +00001521 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001522 z[i] = 0;
1523 *pIdx = i;
1524}
1525
1526/*
1527** Generate a CREATE TABLE statement appropriate for the given
1528** table. Memory to hold the text of the statement is obtained
1529** from sqliteMalloc() and must be freed by the calling function.
1530*/
drh1d34fde2009-02-03 15:50:33 +00001531static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001532 int i, k, n;
1533 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001534 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001535 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001536 n = 0;
drh234c39d2004-07-24 03:30:47 +00001537 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001538 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001539 }
1540 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001541 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001542 zSep = "";
1543 zSep2 = ",";
1544 zEnd = ")";
1545 }else{
1546 zSep = "\n ";
1547 zSep2 = ",\n ";
1548 zEnd = "\n)";
1549 }
drhe0bc4042002-06-25 01:09:11 +00001550 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001551 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001552 if( zStmt==0 ){
1553 db->mallocFailed = 1;
1554 return 0;
1555 }
drhbdb339f2009-02-02 18:03:21 +00001556 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001557 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001558 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001559 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001560 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001561 static const char * const azType[] = {
drh05883a32015-06-02 15:32:08 +00001562 /* SQLITE_AFF_BLOB */ "",
drh7ea31cc2014-09-18 14:36:00 +00001563 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001564 /* SQLITE_AFF_NUMERIC */ " NUM",
1565 /* SQLITE_AFF_INTEGER */ " INT",
1566 /* SQLITE_AFF_REAL */ " REAL"
1567 };
1568 int len;
1569 const char *zType;
1570
drh5bb3eb92007-05-04 13:15:55 +00001571 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001572 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001573 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001574 identPut(zStmt, &k, pCol->zName);
drh05883a32015-06-02 15:32:08 +00001575 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
1576 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
1577 testcase( pCol->affinity==SQLITE_AFF_BLOB );
drh7ea31cc2014-09-18 14:36:00 +00001578 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001579 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1580 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1581 testcase( pCol->affinity==SQLITE_AFF_REAL );
1582
drh05883a32015-06-02 15:32:08 +00001583 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
drhc4a64fa2009-05-11 20:53:28 +00001584 len = sqlite3Strlen30(zType);
drh05883a32015-06-02 15:32:08 +00001585 assert( pCol->affinity==SQLITE_AFF_BLOB
drhfdaac672013-10-04 15:30:21 +00001586 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001587 memcpy(&zStmt[k], zType, len);
1588 k += len;
1589 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001590 }
drh5bb3eb92007-05-04 13:15:55 +00001591 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001592 return zStmt;
1593}
1594
1595/*
drh7f9c5db2013-10-23 00:32:58 +00001596** Resize an Index object to hold N columns total. Return SQLITE_OK
1597** on success and SQLITE_NOMEM on an OOM error.
1598*/
1599static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1600 char *zExtra;
1601 int nByte;
1602 if( pIdx->nColumn>=N ) return SQLITE_OK;
1603 assert( pIdx->isResized==0 );
1604 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1605 zExtra = sqlite3DbMallocZero(db, nByte);
1606 if( zExtra==0 ) return SQLITE_NOMEM;
1607 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1608 pIdx->azColl = (char**)zExtra;
1609 zExtra += sizeof(char*)*N;
1610 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1611 pIdx->aiColumn = (i16*)zExtra;
1612 zExtra += sizeof(i16)*N;
1613 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1614 pIdx->aSortOrder = (u8*)zExtra;
1615 pIdx->nColumn = N;
1616 pIdx->isResized = 1;
1617 return SQLITE_OK;
1618}
1619
1620/*
drhfdaac672013-10-04 15:30:21 +00001621** Estimate the total row width for a table.
1622*/
drhe13e9f52013-10-05 19:18:00 +00001623static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001624 unsigned wTable = 0;
1625 const Column *pTabCol;
1626 int i;
1627 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1628 wTable += pTabCol->szEst;
1629 }
1630 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001631 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001632}
1633
1634/*
drhe13e9f52013-10-05 19:18:00 +00001635** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001636*/
drhe13e9f52013-10-05 19:18:00 +00001637static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001638 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001639 int i;
1640 const Column *aCol = pIdx->pTable->aCol;
1641 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001642 i16 x = pIdx->aiColumn[i];
1643 assert( x<pIdx->pTable->nCol );
1644 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001645 }
drhe13e9f52013-10-05 19:18:00 +00001646 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001647}
1648
drh7f9c5db2013-10-23 00:32:58 +00001649/* Return true if value x is found any of the first nCol entries of aiCol[]
1650*/
1651static int hasColumn(const i16 *aiCol, int nCol, int x){
1652 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1653 return 0;
1654}
1655
1656/*
drhc6bd4e42013-11-02 14:37:18 +00001657** This routine runs at the end of parsing a CREATE TABLE statement that
1658** has a WITHOUT ROWID clause. The job of this routine is to convert both
1659** internal schema data structures and the generated VDBE code so that they
1660** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1661** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001662**
drhc6bd4e42013-11-02 14:37:18 +00001663** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1664** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1665** data storage is a covering index btree.
1666** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001667** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001668** identified by the sqlite_master table entry of the table itself.
1669** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1670** schema to the rootpage from the main table.
1671** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1672** (5) Add all table columns to the PRIMARY KEY Index object
1673** so that the PRIMARY KEY is a covering index. The surplus
1674** columns are part of KeyInfo.nXField and are not used for
1675** sorting or lookup or uniqueness checks.
1676** (6) Replace the rowid tail on all automatically generated UNIQUE
1677** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001678*/
1679static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1680 Index *pIdx;
1681 Index *pPk;
1682 int nPk;
1683 int i, j;
1684 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001685 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001686
1687 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001688 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001689 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001690 */
1691 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001692 assert( v );
1693 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1694 }
1695
drh7f9c5db2013-10-23 00:32:58 +00001696 /* Locate the PRIMARY KEY index. Or, if this table was originally
1697 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1698 */
1699 if( pTab->iPKey>=0 ){
1700 ExprList *pList;
drh108aa002015-08-24 20:21:20 +00001701 Token ipkToken;
1702 ipkToken.z = pTab->aCol[pTab->iPKey].zName;
1703 ipkToken.n = sqlite3Strlen30(ipkToken.z);
1704 pList = sqlite3ExprListAppend(pParse, 0,
1705 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
drh7f9c5db2013-10-23 00:32:58 +00001706 if( pList==0 ) return;
drh7f9c5db2013-10-23 00:32:58 +00001707 pList->a[0].sortOrder = pParse->iPkSortOrder;
1708 assert( pParse->pNewTable==pTab );
1709 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1710 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001711 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001712 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001713 }else{
1714 pPk = sqlite3PrimaryKeyIndex(pTab);
danc5b73582015-05-26 11:53:14 +00001715
1716 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1717 ** table entry. This is only required if currently generating VDBE
1718 ** code for a CREATE TABLE (not when parsing one as part of reading
1719 ** a database schema). */
1720 if( v ){
1721 assert( db->init.busy==0 );
1722 sqlite3VdbeGetOp(v, pPk->tnum)->opcode = OP_Goto;
1723 }
1724
drhe385d882014-12-28 22:10:51 +00001725 /*
1726 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1727 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1728 ** code assumes the PRIMARY KEY contains no repeated columns.
1729 */
1730 for(i=j=1; i<pPk->nKeyCol; i++){
1731 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
1732 pPk->nColumn--;
1733 }else{
1734 pPk->aiColumn[j++] = pPk->aiColumn[i];
1735 }
1736 }
1737 pPk->nKeyCol = j;
drh7f9c5db2013-10-23 00:32:58 +00001738 }
drh12826092013-11-05 22:39:17 +00001739 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001740 assert( pPk!=0 );
1741 nPk = pPk->nKeyCol;
1742
drh1ffede82015-01-30 20:59:27 +00001743 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
1744 ** do not enforce this for imposter tables.) */
1745 if( !db->init.imposterTable ){
1746 for(i=0; i<nPk; i++){
1747 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1748 }
1749 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001750 }
1751
drhc6bd4e42013-11-02 14:37:18 +00001752 /* The root page of the PRIMARY KEY is the table root page */
1753 pPk->tnum = pTab->tnum;
1754
drh7f9c5db2013-10-23 00:32:58 +00001755 /* Update the in-memory representation of all UNIQUE indices by converting
1756 ** the final rowid column into one or more columns of the PRIMARY KEY.
1757 */
1758 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1759 int n;
drh48dd1d82014-05-27 18:18:58 +00001760 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001761 for(i=n=0; i<nPk; i++){
1762 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1763 }
drh5a9a37b2013-11-05 17:30:04 +00001764 if( n==0 ){
1765 /* This index is a superset of the primary key */
1766 pIdx->nColumn = pIdx->nKeyCol;
1767 continue;
1768 }
drh7f9c5db2013-10-23 00:32:58 +00001769 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1770 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001771 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001772 pIdx->aiColumn[j] = pPk->aiColumn[i];
1773 pIdx->azColl[j] = pPk->azColl[i];
1774 j++;
1775 }
1776 }
drh00012df2013-11-05 01:59:07 +00001777 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1778 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001779 }
1780
1781 /* Add all table columns to the PRIMARY KEY index
1782 */
1783 if( nPk<pTab->nCol ){
1784 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1785 for(i=0, j=nPk; i<pTab->nCol; i++){
1786 if( !hasColumn(pPk->aiColumn, j, i) ){
1787 assert( j<pPk->nColumn );
1788 pPk->aiColumn[j] = i;
1789 pPk->azColl[j] = "BINARY";
1790 j++;
1791 }
1792 }
1793 assert( pPk->nColumn==j );
1794 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001795 }else{
1796 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001797 }
1798}
1799
drhfdaac672013-10-04 15:30:21 +00001800/*
drh75897232000-05-29 14:26:00 +00001801** This routine is called to report the final ")" that terminates
1802** a CREATE TABLE statement.
1803**
drhf57b3392001-10-08 13:22:32 +00001804** The table structure that other action routines have been building
1805** is added to the internal hash tables, assuming no errors have
1806** occurred.
drh75897232000-05-29 14:26:00 +00001807**
drh1d85d932004-02-14 23:05:52 +00001808** An entry for the table is made in the master table on disk, unless
1809** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001810** it means we are reading the sqlite_master table because we just
1811** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001812** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001813** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001814**
1815** If the pSelect argument is not NULL, it means that this routine
1816** was called to create a table generated from a
1817** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1818** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001819*/
danielk197719a8e7e2005-03-17 05:03:38 +00001820void sqlite3EndTable(
1821 Parse *pParse, /* Parse context */
1822 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001823 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1824 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001825 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1826){
drhfdaac672013-10-04 15:30:21 +00001827 Table *p; /* The new table */
1828 sqlite3 *db = pParse->db; /* The database connection */
1829 int iDb; /* Database in which the table lives */
1830 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001831
drh027616d2015-08-08 22:47:47 +00001832 if( pEnd==0 && pSelect==0 ){
drh5969da42013-10-21 02:14:45 +00001833 return;
danielk1977261919c2005-12-06 12:52:59 +00001834 }
drh834f9972015-08-08 23:23:33 +00001835 assert( !db->mallocFailed );
drh28037572000-08-02 13:47:41 +00001836 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001837 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001838
danielk1977517eb642004-06-07 10:00:31 +00001839 assert( !db->init.busy || !pSelect );
1840
drhc6bd4e42013-11-02 14:37:18 +00001841 /* If the db->init.busy is 1 it means we are reading the SQL off the
1842 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1843 ** So do not write to the disk again. Extract the root page number
1844 ** for the table from the db->init.newTnum field. (The page number
1845 ** should have been put there by the sqliteOpenCb routine.)
1846 */
1847 if( db->init.busy ){
1848 p->tnum = db->init.newTnum;
1849 }
1850
1851 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001852 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001853 if( (p->tabFlags & TF_Autoincrement) ){
1854 sqlite3ErrorMsg(pParse,
1855 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1856 return;
1857 }
drh5969da42013-10-21 02:14:45 +00001858 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001859 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001860 }else{
drhfccda8a2015-05-27 13:06:55 +00001861 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
drh7f9c5db2013-10-23 00:32:58 +00001862 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001863 }
1864 }
1865
drhb9bb7c12006-06-11 23:41:55 +00001866 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001867
drhffe07b22005-11-03 00:41:17 +00001868#ifndef SQLITE_OMIT_CHECK
1869 /* Resolve names in all CHECK constraint expressions.
1870 */
1871 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001872 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001873 }
1874#endif /* !defined(SQLITE_OMIT_CHECK) */
1875
drhe13e9f52013-10-05 19:18:00 +00001876 /* Estimate the average row size for the table and for all implied indices */
1877 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001878 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001879 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001880 }
1881
drhe3c41372001-09-17 20:25:58 +00001882 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001883 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001884 **
drhe0bc4042002-06-25 01:09:11 +00001885 ** If this is a TEMPORARY table, write the entry into the auxiliary
1886 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001887 */
drh1d85d932004-02-14 23:05:52 +00001888 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001889 int n;
drhd8bc7082000-06-07 23:51:50 +00001890 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001891 char *zType; /* "view" or "table" */
1892 char *zType2; /* "VIEW" or "TABLE" */
1893 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001894
danielk19774adee202004-05-08 08:23:19 +00001895 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001896 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001897
drh66a51672008-01-03 00:01:23 +00001898 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001899
drh0fa991b2009-03-21 16:19:26 +00001900 /*
1901 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001902 */
drh4ff6dfa2002-03-03 23:06:00 +00001903 if( p->pSelect==0 ){
1904 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001905 zType = "table";
1906 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001907#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001908 }else{
1909 /* A view */
drh4794f732004-11-05 17:17:50 +00001910 zType = "view";
1911 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001912#endif
drh4ff6dfa2002-03-03 23:06:00 +00001913 }
danielk1977517eb642004-06-07 10:00:31 +00001914
danielk1977517eb642004-06-07 10:00:31 +00001915 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1916 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001917 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001918 **
1919 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1920 ** suitable state to query for the column names and types to be used
1921 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001922 **
1923 ** A shared-cache write-lock is not required to write to the new table,
1924 ** as a schema-lock must have already been obtained to create it. Since
1925 ** a schema-lock excludes all other database users, the write-lock would
1926 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001927 */
1928 if( pSelect ){
drh92632202015-05-20 17:18:29 +00001929 SelectDest dest; /* Where the SELECT should store results */
drh9df25c42015-05-20 15:51:09 +00001930 int regYield; /* Register holding co-routine entry-point */
1931 int addrTop; /* Top of the co-routine */
drh92632202015-05-20 17:18:29 +00001932 int regRec; /* A record to be insert into the new table */
1933 int regRowid; /* Rowid of the next row to insert */
1934 int addrInsLoop; /* Top of the loop for inserting rows */
1935 Table *pSelTab; /* A table that describes the SELECT results */
drh1013c932008-01-06 00:25:21 +00001936
drh9df25c42015-05-20 15:51:09 +00001937 regYield = ++pParse->nMem;
drh92632202015-05-20 17:18:29 +00001938 regRec = ++pParse->nMem;
1939 regRowid = ++pParse->nMem;
danielk19776ab3a2e2009-02-19 14:39:25 +00001940 assert(pParse->nTab==1);
drh0dd5cda2015-06-16 16:39:01 +00001941 sqlite3MayAbort(pParse);
drhb7654112008-01-12 12:48:07 +00001942 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001943 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001944 pParse->nTab = 2;
drh9df25c42015-05-20 15:51:09 +00001945 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1946 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1947 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
drh7d10d5a2008-08-20 16:35:10 +00001948 sqlite3Select(pParse, pSelect, &dest);
drh9df25c42015-05-20 15:51:09 +00001949 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
1950 sqlite3VdbeJumpHere(v, addrTop - 1);
drh92632202015-05-20 17:18:29 +00001951 if( pParse->nErr ) return;
1952 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1953 if( pSelTab==0 ) return;
1954 assert( p->aCol==0 );
1955 p->nCol = pSelTab->nCol;
1956 p->aCol = pSelTab->aCol;
1957 pSelTab->nCol = 0;
1958 pSelTab->aCol = 0;
1959 sqlite3DeleteTable(db, pSelTab);
1960 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1961 VdbeCoverage(v);
1962 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
1963 sqlite3TableAffinity(v, p, 0);
1964 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
1965 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
1966 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInsLoop);
1967 sqlite3VdbeJumpHere(v, addrInsLoop);
1968 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001969 }
drh4794f732004-11-05 17:17:50 +00001970
drh4794f732004-11-05 17:17:50 +00001971 /* Compute the complete text of the CREATE statement */
1972 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001973 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001974 }else{
drh8ea30bf2013-10-22 01:18:17 +00001975 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1976 n = (int)(pEnd2->z - pParse->sNameToken.z);
1977 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001978 zStmt = sqlite3MPrintf(db,
1979 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1980 );
drh4794f732004-11-05 17:17:50 +00001981 }
1982
1983 /* A slot for the record has already been allocated in the
1984 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001985 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001986 */
1987 sqlite3NestedParse(pParse,
1988 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001989 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1990 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001991 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001992 zType,
1993 p->zName,
1994 p->zName,
drhb7654112008-01-12 12:48:07 +00001995 pParse->regRoot,
1996 zStmt,
1997 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001998 );
drh633e6d52008-07-28 19:34:53 +00001999 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00002000 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00002001
2002#ifndef SQLITE_OMIT_AUTOINCREMENT
2003 /* Check to see if we need to create an sqlite_sequence table for
2004 ** keeping track of autoincrement keys.
2005 */
drh7d10d5a2008-08-20 16:35:10 +00002006 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00002007 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00002008 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00002009 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00002010 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00002011 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
2012 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00002013 );
2014 }
2015 }
2016#endif
drh4794f732004-11-05 17:17:50 +00002017
2018 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00002019 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00002020 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00002021 }
drh17e9e292003-02-01 13:53:28 +00002022
drh2958a4e2004-11-12 03:56:15 +00002023
drh17e9e292003-02-01 13:53:28 +00002024 /* Add the table to the in-memory representation of the database.
2025 */
drh8af73d42009-05-13 22:58:28 +00002026 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00002027 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00002028 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00002029 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00002030 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00002031 if( pOld ){
2032 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00002033 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00002034 return;
drh17e9e292003-02-01 13:53:28 +00002035 }
drh17e9e292003-02-01 13:53:28 +00002036 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00002037 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00002038
2039#ifndef SQLITE_OMIT_ALTERTABLE
2040 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00002041 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00002042 int nName;
drh5969da42013-10-21 02:14:45 +00002043 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00002044 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002045 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002046 }
drh1bd10f82008-12-10 21:19:56 +00002047 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002048 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002049 }
2050#endif
drh17e9e292003-02-01 13:53:28 +00002051 }
drh75897232000-05-29 14:26:00 +00002052}
2053
drhb7f91642004-10-31 02:22:47 +00002054#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002055/*
drha76b5df2002-02-23 02:32:10 +00002056** The parser calls this routine in order to create a new VIEW
2057*/
danielk19774adee202004-05-08 08:23:19 +00002058void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002059 Parse *pParse, /* The parsing context */
2060 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002061 Token *pName1, /* The token that holds the name of the view */
2062 Token *pName2, /* The token that holds the name of the view */
drh8981b902015-08-24 17:42:49 +00002063 ExprList *pCNames, /* Optional list of view column names */
drh6276c1c2002-07-08 22:03:32 +00002064 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002065 int isTemp, /* TRUE for a TEMPORARY view */
2066 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002067){
drha76b5df2002-02-23 02:32:10 +00002068 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002069 int n;
drhb7916a72009-05-27 10:31:29 +00002070 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002071 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002072 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002073 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002074 int iDb;
drh17435752007-08-16 04:30:38 +00002075 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002076
drh7c3d64f2005-06-06 15:32:08 +00002077 if( pParse->nVar>0 ){
2078 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002079 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002080 return;
2081 }
drhfdd48a72006-09-11 23:45:48 +00002082 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002083 p = pParse->pNewTable;
drh8981b902015-08-24 17:42:49 +00002084 if( p==0 || pParse->nErr ) goto create_view_fail;
danielk1977ef2cb632004-05-29 02:37:19 +00002085 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002086 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002087 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
drh8981b902015-08-24 17:42:49 +00002088 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
drh174b6192002-12-03 02:22:52 +00002089
drh4b59ab52002-08-24 18:24:51 +00002090 /* Make a copy of the entire SELECT statement that defines the view.
2091 ** This will force all the Expr.token.z values to be dynamically
2092 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002093 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002094 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002095 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh8981b902015-08-24 17:42:49 +00002096 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
2097 if( db->mallocFailed ) goto create_view_fail;
drh4b59ab52002-08-24 18:24:51 +00002098
2099 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2100 ** the end.
2101 */
drha76b5df2002-02-23 02:32:10 +00002102 sEnd = pParse->sLastToken;
drh8981b902015-08-24 17:42:49 +00002103 assert( sEnd.z[0]!=0 );
2104 if( sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002105 sEnd.z += sEnd.n;
2106 }
2107 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002108 n = (int)(sEnd.z - pBegin->z);
drh8981b902015-08-24 17:42:49 +00002109 assert( n>0 );
drhb7916a72009-05-27 10:31:29 +00002110 z = pBegin->z;
drh8981b902015-08-24 17:42:49 +00002111 while( sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002112 sEnd.z = &z[n-1];
2113 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002114
danielk19774adee202004-05-08 08:23:19 +00002115 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002116 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drh8981b902015-08-24 17:42:49 +00002117
2118create_view_fail:
2119 sqlite3SelectDelete(db, pSelect);
2120 sqlite3ExprListDelete(db, pCNames);
drha76b5df2002-02-23 02:32:10 +00002121 return;
drh417be792002-03-03 18:59:40 +00002122}
drhb7f91642004-10-31 02:22:47 +00002123#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002124
danielk1977fe3fcbe22006-06-12 12:08:45 +00002125#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002126/*
2127** The Table structure pTable is really a VIEW. Fill in the names of
2128** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002129** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002130*/
danielk19774adee202004-05-08 08:23:19 +00002131int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002132 Table *pSelTab; /* A fake table from which we get the result set */
2133 Select *pSel; /* Copy of the SELECT that implements the view */
2134 int nErr = 0; /* Number of errors encountered */
2135 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002136 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002137 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh8981b902015-08-24 17:42:49 +00002138 u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */
drh417be792002-03-03 18:59:40 +00002139
2140 assert( pTable );
2141
danielk1977fe3fcbe22006-06-12 12:08:45 +00002142#ifndef SQLITE_OMIT_VIRTUALTABLE
2143 if( sqlite3VtabCallConnect(pParse, pTable) ){
2144 return SQLITE_ERROR;
2145 }
drh4cbdda92006-06-14 19:00:20 +00002146 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002147#endif
2148
2149#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002150 /* A positive nCol means the columns names for this view are
2151 ** already known.
2152 */
2153 if( pTable->nCol>0 ) return 0;
2154
2155 /* A negative nCol is a special marker meaning that we are currently
2156 ** trying to compute the column names. If we enter this routine with
2157 ** a negative nCol, it means two or more views form a loop, like this:
2158 **
2159 ** CREATE VIEW one AS SELECT * FROM two;
2160 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002161 **
drh768578e2009-05-12 00:40:12 +00002162 ** Actually, the error above is now caught prior to reaching this point.
2163 ** But the following test is still important as it does come up
2164 ** in the following:
2165 **
2166 ** CREATE TABLE main.ex1(a);
2167 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2168 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002169 */
2170 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002171 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002172 return 1;
2173 }
drh85c23c62005-08-20 03:03:04 +00002174 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002175
2176 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002177 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2178 ** "*" elements in the results set of the view and will assign cursors
2179 ** to the elements of the FROM clause. But we do not want these changes
2180 ** to be permanent. So the computation is done on a copy of the SELECT
2181 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002182 */
drh9b3187e2005-01-18 14:45:47 +00002183 assert( pTable->pSelect );
drh8981b902015-08-24 17:42:49 +00002184 bEnabledLA = db->lookaside.bEnabled;
2185 if( pTable->pCheck ){
drhd9da78a2009-03-24 15:08:09 +00002186 db->lookaside.bEnabled = 0;
drh8981b902015-08-24 17:42:49 +00002187 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
2188 &pTable->nCol, &pTable->aCol);
2189 }else{
2190 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
2191 if( pSel ){
2192 n = pParse->nTab;
2193 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2194 pTable->nCol = -1;
2195 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002196#ifndef SQLITE_OMIT_AUTHORIZATION
drh8981b902015-08-24 17:42:49 +00002197 xAuth = db->xAuth;
2198 db->xAuth = 0;
2199 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
2200 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002201#else
drh8981b902015-08-24 17:42:49 +00002202 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002203#endif
drh8981b902015-08-24 17:42:49 +00002204 pParse->nTab = n;
2205 if( pSelTab ){
2206 assert( pTable->aCol==0 );
2207 pTable->nCol = pSelTab->nCol;
2208 pTable->aCol = pSelTab->aCol;
2209 pSelTab->nCol = 0;
2210 pSelTab->aCol = 0;
2211 sqlite3DeleteTable(db, pSelTab);
2212 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
2213 }else{
2214 pTable->nCol = 0;
2215 nErr++;
2216 }
2217 sqlite3SelectDelete(db, pSel);
2218 } else {
danielk1977261919c2005-12-06 12:52:59 +00002219 nErr++;
2220 }
drh417be792002-03-03 18:59:40 +00002221 }
drh8981b902015-08-24 17:42:49 +00002222 db->lookaside.bEnabled = bEnabledLA;
2223 pTable->pSchema->schemaFlags |= DB_UnresetViews;
drhb7f91642004-10-31 02:22:47 +00002224#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002225 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002226}
2227#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002228
drhb7f91642004-10-31 02:22:47 +00002229#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002230/*
drh8bf8dc92003-05-17 17:35:10 +00002231** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002232*/
drh9bb575f2004-09-06 17:24:11 +00002233static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002234 HashElem *i;
drh21206082011-04-04 18:22:02 +00002235 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002236 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002237 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002238 Table *pTab = sqliteHashData(i);
2239 if( pTab->pSelect ){
drh51be3872015-08-19 02:32:25 +00002240 sqlite3DeleteColumnNames(db, pTab);
dand46def72010-07-24 11:28:28 +00002241 pTab->aCol = 0;
2242 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002243 }
2244 }
drh8bf8dc92003-05-17 17:35:10 +00002245 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002246}
drhb7f91642004-10-31 02:22:47 +00002247#else
2248# define sqliteViewResetAll(A,B)
2249#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002250
drh75897232000-05-29 14:26:00 +00002251/*
danielk1977a0bf2652004-11-04 14:30:04 +00002252** This function is called by the VDBE to adjust the internal schema
2253** used by SQLite when the btree layer moves a table root page. The
2254** root-page of a table or index in database iDb has changed from iFrom
2255** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002256**
2257** Ticket #1728: The symbol table might still contain information
2258** on tables and/or indices that are the process of being deleted.
2259** If you are unlucky, one of those deleted indices or tables might
2260** have the same rootpage number as the real table or index that is
2261** being moved. So we cannot stop searching after the first match
2262** because the first match might be for one of the deleted indices
2263** or tables and not the table/index that is actually being moved.
2264** We must continue looping until all tables and indices with
2265** rootpage==iFrom have been converted to have a rootpage of iTo
2266** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002267*/
2268#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002269void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002270 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002271 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002272 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002273
drhcdf011d2011-04-04 21:25:28 +00002274 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2275 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002276 pHash = &pDb->pSchema->tblHash;
2277 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002278 Table *pTab = sqliteHashData(pElem);
2279 if( pTab->tnum==iFrom ){
2280 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002281 }
2282 }
danielk1977da184232006-01-05 11:34:32 +00002283 pHash = &pDb->pSchema->idxHash;
2284 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002285 Index *pIdx = sqliteHashData(pElem);
2286 if( pIdx->tnum==iFrom ){
2287 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002288 }
2289 }
danielk1977a0bf2652004-11-04 14:30:04 +00002290}
2291#endif
2292
2293/*
2294** Write code to erase the table with root-page iTable from database iDb.
2295** Also write code to modify the sqlite_master table and internal schema
2296** if a root-page of another table is moved by the btree-layer whilst
2297** erasing iTable (this can happen with an auto-vacuum database).
2298*/
drh4e0cff62004-11-05 05:10:28 +00002299static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2300 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002301 int r1 = sqlite3GetTempReg(pParse);
2302 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002303 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002304#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002305 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002306 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002307 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002308 ** reflect this.
2309 **
drh0fa991b2009-03-21 16:19:26 +00002310 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002311 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2312 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002313 */
danielk197763e3e9f2004-11-05 09:19:27 +00002314 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002315 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2316 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002317#endif
drhb7654112008-01-12 12:48:07 +00002318 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002319}
2320
2321/*
2322** Write VDBE code to erase table pTab and all associated indices on disk.
2323** Code to update the sqlite_master tables and internal schema definitions
2324** in case a root-page belonging to another table is moved by the btree layer
2325** is also added (this can happen with an auto-vacuum database).
2326*/
drh4e0cff62004-11-05 05:10:28 +00002327static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002328#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002329 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002330 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2331 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002332 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002333 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002334 }
2335#else
2336 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2337 ** is not defined), then it is important to call OP_Destroy on the
2338 ** table and index root-pages in order, starting with the numerically
2339 ** largest root-page number. This guarantees that none of the root-pages
2340 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2341 ** following were coded:
2342 **
2343 ** OP_Destroy 4 0
2344 ** ...
2345 ** OP_Destroy 5 0
2346 **
2347 ** and root page 5 happened to be the largest root-page number in the
2348 ** database, then root page 5 would be moved to page 4 by the
2349 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2350 ** a free-list page.
2351 */
2352 int iTab = pTab->tnum;
2353 int iDestroyed = 0;
2354
2355 while( 1 ){
2356 Index *pIdx;
2357 int iLargest = 0;
2358
2359 if( iDestroyed==0 || iTab<iDestroyed ){
2360 iLargest = iTab;
2361 }
2362 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2363 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002364 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002365 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2366 iLargest = iIdx;
2367 }
2368 }
danielk1977da184232006-01-05 11:34:32 +00002369 if( iLargest==0 ){
2370 return;
2371 }else{
2372 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002373 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002374 destroyRootPage(pParse, iLargest, iDb);
2375 iDestroyed = iLargest;
2376 }
danielk1977a0bf2652004-11-04 14:30:04 +00002377 }
2378#endif
2379}
2380
2381/*
drh74e7c8f2011-10-21 19:06:32 +00002382** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002383** after a DROP INDEX or DROP TABLE command.
2384*/
2385static void sqlite3ClearStatTables(
2386 Parse *pParse, /* The parsing context */
2387 int iDb, /* The database number */
2388 const char *zType, /* "idx" or "tbl" */
2389 const char *zName /* Name of index or table */
2390){
drha5ae4c32011-08-07 01:31:52 +00002391 int i;
2392 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002393 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002394 char zTab[24];
2395 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2396 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002397 sqlite3NestedParse(pParse,
2398 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002399 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002400 );
2401 }
2402 }
2403}
2404
2405/*
drhfaacf172011-08-12 01:51:45 +00002406** Generate code to drop a table.
2407*/
2408void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2409 Vdbe *v;
2410 sqlite3 *db = pParse->db;
2411 Trigger *pTrigger;
2412 Db *pDb = &db->aDb[iDb];
2413
2414 v = sqlite3GetVdbe(pParse);
2415 assert( v!=0 );
2416 sqlite3BeginWriteOperation(pParse, 1, iDb);
2417
2418#ifndef SQLITE_OMIT_VIRTUALTABLE
2419 if( IsVirtual(pTab) ){
2420 sqlite3VdbeAddOp0(v, OP_VBegin);
2421 }
2422#endif
2423
2424 /* Drop all triggers associated with the table being dropped. Code
2425 ** is generated to remove entries from sqlite_master and/or
2426 ** sqlite_temp_master if required.
2427 */
2428 pTrigger = sqlite3TriggerList(pParse, pTab);
2429 while( pTrigger ){
2430 assert( pTrigger->pSchema==pTab->pSchema ||
2431 pTrigger->pSchema==db->aDb[1].pSchema );
2432 sqlite3DropTriggerPtr(pParse, pTrigger);
2433 pTrigger = pTrigger->pNext;
2434 }
2435
2436#ifndef SQLITE_OMIT_AUTOINCREMENT
2437 /* Remove any entries of the sqlite_sequence table associated with
2438 ** the table being dropped. This is done before the table is dropped
2439 ** at the btree level, in case the sqlite_sequence table needs to
2440 ** move as a result of the drop (can happen in auto-vacuum mode).
2441 */
2442 if( pTab->tabFlags & TF_Autoincrement ){
2443 sqlite3NestedParse(pParse,
2444 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2445 pDb->zName, pTab->zName
2446 );
2447 }
2448#endif
2449
2450 /* Drop all SQLITE_MASTER table and index entries that refer to the
2451 ** table. The program name loops through the master table and deletes
2452 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002453 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002454 ** created in the temp database that refers to a table in another
2455 ** database.
2456 */
2457 sqlite3NestedParse(pParse,
2458 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2459 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002460 if( !isView && !IsVirtual(pTab) ){
2461 destroyTable(pParse, pTab);
2462 }
2463
2464 /* Remove the table entry from SQLite's internal schema and modify
2465 ** the schema cookie.
2466 */
2467 if( IsVirtual(pTab) ){
2468 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2469 }
2470 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2471 sqlite3ChangeCookie(pParse, iDb);
2472 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002473}
2474
2475/*
drh75897232000-05-29 14:26:00 +00002476** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002477** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002478*/
drha0733842005-12-29 01:11:36 +00002479void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002480 Table *pTab;
drh75897232000-05-29 14:26:00 +00002481 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002482 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002483 int iDb;
drh75897232000-05-29 14:26:00 +00002484
drh8af73d42009-05-13 22:58:28 +00002485 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002486 goto exit_drop_table;
2487 }
drh8af73d42009-05-13 22:58:28 +00002488 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002489 assert( pName->nSrc==1 );
drh75209962015-04-19 22:31:45 +00002490 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
drha7564662010-02-22 19:32:31 +00002491 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002492 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002493 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002494
drha0733842005-12-29 01:11:36 +00002495 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002496 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002497 goto exit_drop_table;
2498 }
danielk1977da184232006-01-05 11:34:32 +00002499 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002500 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002501
2502 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2503 ** it is initialized.
2504 */
2505 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2506 goto exit_drop_table;
2507 }
drhe5f9c642003-01-13 23:27:31 +00002508#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002509 {
2510 int code;
danielk1977da184232006-01-05 11:34:32 +00002511 const char *zTab = SCHEMA_TABLE(iDb);
2512 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002513 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002514 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002515 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002516 }
drhe5f9c642003-01-13 23:27:31 +00002517 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002518 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002519 code = SQLITE_DROP_TEMP_VIEW;
2520 }else{
2521 code = SQLITE_DROP_VIEW;
2522 }
danielk19774b2688a2006-06-20 11:01:07 +00002523#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002524 }else if( IsVirtual(pTab) ){
2525 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002526 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002527#endif
drhe5f9c642003-01-13 23:27:31 +00002528 }else{
danielk197753c0f742005-03-29 03:10:59 +00002529 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002530 code = SQLITE_DROP_TEMP_TABLE;
2531 }else{
2532 code = SQLITE_DROP_TABLE;
2533 }
2534 }
danielk1977f1a381e2006-06-16 08:01:02 +00002535 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002536 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002537 }
danielk1977a8858102004-05-28 12:11:21 +00002538 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2539 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002540 }
drhe5f9c642003-01-13 23:27:31 +00002541 }
2542#endif
drh08ccfaa2011-10-07 23:52:25 +00002543 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2544 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002545 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002546 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002547 }
danielk1977576ec6b2005-01-21 11:55:25 +00002548
2549#ifndef SQLITE_OMIT_VIEW
2550 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2551 ** on a table.
2552 */
danielk1977a8858102004-05-28 12:11:21 +00002553 if( isView && pTab->pSelect==0 ){
2554 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2555 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002556 }
danielk1977a8858102004-05-28 12:11:21 +00002557 if( !isView && pTab->pSelect ){
2558 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2559 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002560 }
danielk1977576ec6b2005-01-21 11:55:25 +00002561#endif
drh75897232000-05-29 14:26:00 +00002562
drh1ccde152000-06-17 13:12:39 +00002563 /* Generate code to remove the table from the master table
2564 ** on disk.
2565 */
danielk19774adee202004-05-08 08:23:19 +00002566 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002567 if( v ){
drh77658e22007-12-04 16:54:52 +00002568 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002569 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002570 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002571 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002572 }
danielk1977a8858102004-05-28 12:11:21 +00002573
2574exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002575 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002576}
2577
2578/*
drhc2eef3b2002-08-31 18:53:06 +00002579** This routine is called to create a new foreign key on the table
2580** currently under construction. pFromCol determines which columns
2581** in the current table point to the foreign key. If pFromCol==0 then
2582** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002583** the table referred to (a.k.a the "parent" table). pToCol is a list
2584** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002585** information about the conflict resolution algorithms specified
2586** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2587**
2588** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002589** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002590**
2591** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002592** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002593*/
danielk19774adee202004-05-08 08:23:19 +00002594void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002595 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002596 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002597 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002598 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002599 int flags /* Conflict resolution algorithms. */
2600){
danielk197718576932008-08-06 13:47:40 +00002601 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002602#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002603 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002604 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002605 Table *p = pParse->pNewTable;
2606 int nByte;
2607 int i;
2608 int nCol;
2609 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002610
2611 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002612 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002613 if( pFromCol==0 ){
2614 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002615 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002616 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002617 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002618 " should reference only one column of table %T",
2619 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002620 goto fk_end;
2621 }
2622 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002623 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002624 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002625 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002626 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002627 goto fk_end;
2628 }else{
danielk19770202b292004-06-09 09:55:16 +00002629 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002630 }
drhe61922a2009-05-02 13:29:37 +00002631 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002632 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002633 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002634 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002635 }
2636 }
drh633e6d52008-07-28 19:34:53 +00002637 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002638 if( pFKey==0 ){
2639 goto fk_end;
2640 }
drhc2eef3b2002-08-31 18:53:06 +00002641 pFKey->pFrom = p;
2642 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002643 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002644 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002645 memcpy(z, pTo->z, pTo->n);
2646 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002647 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002648 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002649 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002650 if( pFromCol==0 ){
2651 pFKey->aCol[0].iFrom = p->nCol-1;
2652 }else{
2653 for(i=0; i<nCol; i++){
2654 int j;
2655 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002656 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002657 pFKey->aCol[i].iFrom = j;
2658 break;
2659 }
2660 }
2661 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002662 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002663 "unknown column \"%s\" in foreign key definition",
2664 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002665 goto fk_end;
2666 }
2667 }
2668 }
2669 if( pToCol ){
2670 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002671 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002672 pFKey->aCol[i].zCol = z;
2673 memcpy(z, pToCol->a[i].zName, n);
2674 z[n] = 0;
2675 z += n+1;
2676 }
2677 }
2678 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002679 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2680 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002681
drh21206082011-04-04 18:22:02 +00002682 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002683 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002684 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002685 );
danf59c5ca2009-09-22 16:55:38 +00002686 if( pNextTo==pFKey ){
2687 db->mallocFailed = 1;
2688 goto fk_end;
2689 }
dan1da40a32009-09-19 17:00:31 +00002690 if( pNextTo ){
2691 assert( pNextTo->pPrevTo==0 );
2692 pFKey->pNextTo = pNextTo;
2693 pNextTo->pPrevTo = pFKey;
2694 }
2695
drhc2eef3b2002-08-31 18:53:06 +00002696 /* Link the foreign key to the table as the last step.
2697 */
2698 p->pFKey = pFKey;
2699 pFKey = 0;
2700
2701fk_end:
drh633e6d52008-07-28 19:34:53 +00002702 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002703#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002704 sqlite3ExprListDelete(db, pFromCol);
2705 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002706}
2707
2708/*
2709** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2710** clause is seen as part of a foreign key definition. The isDeferred
2711** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2712** The behavior of the most recently created foreign key is adjusted
2713** accordingly.
2714*/
danielk19774adee202004-05-08 08:23:19 +00002715void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002716#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002717 Table *pTab;
2718 FKey *pFKey;
2719 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002720 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002721 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002722#endif
drhc2eef3b2002-08-31 18:53:06 +00002723}
2724
2725/*
drh063336a2004-11-05 20:58:39 +00002726** Generate code that will erase and refill index *pIdx. This is
2727** used to initialize a newly created index or to recompute the
2728** content of an index in response to a REINDEX command.
2729**
2730** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002731** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002732** root page number of the index. If memRootPage is negative, then
2733** the index already exists and must be cleared before being refilled and
2734** the root page number of the index is taken from pIndex->tnum.
2735*/
2736static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2737 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002738 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2739 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002740 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002741 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002742 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002743 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002744 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002745 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002746 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002747 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002748 sqlite3 *db = pParse->db; /* The database connection */
2749 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002750
danielk19771d54df82004-11-23 15:41:16 +00002751#ifndef SQLITE_OMIT_AUTHORIZATION
2752 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002753 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002754 return;
2755 }
2756#endif
2757
danielk1977c00da102006-01-07 13:21:04 +00002758 /* Require a write-lock on the table to perform this operation */
2759 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2760
drh063336a2004-11-05 20:58:39 +00002761 v = sqlite3GetVdbe(pParse);
2762 if( v==0 ) return;
2763 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002764 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002765 }else{
2766 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002767 }
drh2ec2fb22013-11-06 19:59:23 +00002768 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002769
dan689ab892011-08-12 15:02:00 +00002770 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002771 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002772 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002773 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002774
2775 /* Open the table. Loop through all rows of the table, inserting index
2776 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002777 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002778 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002779 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002780
drh1c2c0b72014-01-04 19:27:05 +00002781 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002782 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002783 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002784 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002785 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002786 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2787 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002788 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002789 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2790
drh688852a2014-02-17 22:40:43 +00002791 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002792 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002793 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002794 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2795 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2796 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002797 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002798 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002799 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002800 }else{
2801 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002802 }
drh6cf4a7d2014-10-13 13:00:58 +00002803 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
danb18e60b2015-04-01 16:18:00 +00002804 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
2805 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
drhca892a72011-09-03 00:17:51 +00002806 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002807 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002808 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002809 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002810
drh66a51672008-01-03 00:01:23 +00002811 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2812 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002813 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002814}
2815
2816/*
drh77e57df2013-10-22 14:28:02 +00002817** Allocate heap space to hold an Index object with nCol columns.
2818**
2819** Increase the allocation size to provide an extra nExtra bytes
2820** of 8-byte aligned space after the Index object and return a
2821** pointer to this extra space in *ppExtra.
2822*/
2823Index *sqlite3AllocateIndexObject(
2824 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002825 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002826 int nExtra, /* Number of bytes of extra space to alloc */
2827 char **ppExtra /* Pointer to the "extra" space */
2828){
2829 Index *p; /* Allocated index object */
2830 int nByte; /* Bytes of space for Index object + arrays */
2831
2832 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2833 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002834 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002835 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002836 sizeof(u8)*nCol); /* Index.aSortOrder */
2837 p = sqlite3DbMallocZero(db, nByte + nExtra);
2838 if( p ){
2839 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002840 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2841 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2842 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002843 p->aSortOrder = (u8*)pExtra;
2844 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002845 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002846 *ppExtra = ((char*)p) + nByte;
2847 }
2848 return p;
2849}
2850
2851/*
drh23bf66d2004-12-14 03:34:34 +00002852** Create a new index for an SQL table. pName1.pName2 is the name of the index
2853** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002854** be NULL for a primary key or an index that is created to satisfy a
2855** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002856** as the table to be indexed. pParse->pNewTable is a table that is
2857** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002858**
drh382c0242001-10-06 16:33:02 +00002859** pList is a list of columns to be indexed. pList will be NULL if this
2860** is a primary key or unique-constraint on the most recent column added
2861** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002862**
2863** If the index is created successfully, return a pointer to the new Index
2864** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002865** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002866*/
dan1da40a32009-09-19 17:00:31 +00002867Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002868 Parse *pParse, /* All information about this parse */
2869 Token *pName1, /* First part of index name. May be NULL */
2870 Token *pName2, /* Second part of index name. May be NULL */
2871 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002872 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002873 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002874 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002875 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002876 int sortOrder, /* Sort order of primary key when pList==NULL */
2877 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002878){
dan1da40a32009-09-19 17:00:31 +00002879 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002880 Table *pTab = 0; /* Table to be indexed */
2881 Index *pIndex = 0; /* The index to be created */
2882 char *zName = 0; /* Name of the index */
2883 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002884 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002885 DbFixer sFix; /* For assigning database names to pTable */
2886 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002887 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002888 Db *pDb; /* The specific table containing the indexed database */
2889 int iDb; /* Index of the database that is being written */
2890 Token *pName = 0; /* Unqualified name of the index to create */
2891 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002892 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002893 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002894 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002895 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002896 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002897
drh7088d502015-04-18 17:43:29 +00002898 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
drhd3001712009-05-12 17:46:53 +00002899 goto exit_create_index;
2900 }
2901 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002902 goto exit_create_index;
2903 }
drhdaffd0e2001-04-11 14:28:42 +00002904
drh75897232000-05-29 14:26:00 +00002905 /*
2906 ** Find the table that is to be indexed. Return early if not found.
2907 */
danielk1977cbb18d22004-05-28 11:37:27 +00002908 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002909
2910 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002911 ** to search for the table. 'Fix' the table name to this db
2912 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002913 */
2914 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002915 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002916 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002917 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002918
danielk197753c0f742005-03-29 03:10:59 +00002919#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002920 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002921 ** is a temp table. If so, set the database to 1. Do not do this
2922 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002923 */
danielk1977fe910332007-12-02 11:46:34 +00002924 if( !db->init.busy ){
2925 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002926 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002927 iDb = 1;
2928 }
danielk1977ef2cb632004-05-29 02:37:19 +00002929 }
danielk197753c0f742005-03-29 03:10:59 +00002930#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002931
drhd100f692013-10-03 15:39:44 +00002932 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2933 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002934 /* Because the parser constructs pTblName from a single identifier,
2935 ** sqlite3FixSrcList can never fail. */
2936 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002937 }
dan41fb5cd2012-10-04 19:33:00 +00002938 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002939 assert( db->mallocFailed==0 || pTab==0 );
2940 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002941 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2942 sqlite3ErrorMsg(pParse,
2943 "cannot create a TEMP index on non-TEMP table \"%s\"",
2944 pTab->zName);
2945 goto exit_create_index;
2946 }
drh44156282013-10-23 22:23:03 +00002947 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002948 }else{
drhe3c41372001-09-17 20:25:58 +00002949 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002950 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002951 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002952 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002953 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002954 }
drhfdd6e852005-12-16 01:06:16 +00002955 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002956
drhd3001712009-05-12 17:46:53 +00002957 assert( pTab!=0 );
2958 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002959 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002960 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002961#if SQLITE_USER_AUTHENTICATION
2962 && sqlite3UserAuthTable(pTab->zName)==0
2963#endif
drh503a6862013-03-01 01:07:17 +00002964 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002965 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002966 goto exit_create_index;
2967 }
danielk1977576ec6b2005-01-21 11:55:25 +00002968#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002969 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002970 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002971 goto exit_create_index;
2972 }
danielk1977576ec6b2005-01-21 11:55:25 +00002973#endif
danielk19775ee9d692006-06-21 12:36:25 +00002974#ifndef SQLITE_OMIT_VIRTUALTABLE
2975 if( IsVirtual(pTab) ){
2976 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2977 goto exit_create_index;
2978 }
2979#endif
drh75897232000-05-29 14:26:00 +00002980
2981 /*
2982 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002983 ** index or table with the same name.
2984 **
2985 ** Exception: If we are reading the names of permanent indices from the
2986 ** sqlite_master table (because some other process changed the schema) and
2987 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002988 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002989 **
2990 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002991 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2992 ** own name.
drh75897232000-05-29 14:26:00 +00002993 */
danielk1977d8123362004-06-12 09:25:12 +00002994 if( pName ){
drh17435752007-08-16 04:30:38 +00002995 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002996 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002997 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002998 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002999 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00003000 }
danielk1977d8123362004-06-12 09:25:12 +00003001 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00003002 if( sqlite3FindTable(db, zName, 0)!=0 ){
3003 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
3004 goto exit_create_index;
3005 }
3006 }
danielk197759a33f92007-03-17 10:26:59 +00003007 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
3008 if( !ifNotExist ){
3009 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00003010 }else{
3011 assert( !db->init.busy );
3012 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00003013 }
danielk197759a33f92007-03-17 10:26:59 +00003014 goto exit_create_index;
3015 }
danielk1977a21c6b62005-01-24 10:25:59 +00003016 }else{
drhadbca9c2001-09-27 15:11:53 +00003017 int n;
3018 Index *pLoop;
3019 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00003020 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00003021 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00003022 goto exit_create_index;
3023 }
drh75897232000-05-29 14:26:00 +00003024 }
3025
drhe5f9c642003-01-13 23:27:31 +00003026 /* Check for authorization to create an index.
3027 */
3028#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00003029 {
drhfdd6e852005-12-16 01:06:16 +00003030 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00003031 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003032 goto exit_create_index;
3033 }
3034 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00003035 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003036 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003037 goto exit_create_index;
3038 }
drhe5f9c642003-01-13 23:27:31 +00003039 }
3040#endif
3041
drh75897232000-05-29 14:26:00 +00003042 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00003043 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00003044 ** So create a fake list to simulate this.
3045 */
3046 if( pList==0 ){
drh108aa002015-08-24 20:21:20 +00003047 Token prevCol;
3048 prevCol.z = pTab->aCol[pTab->nCol-1].zName;
3049 prevCol.n = sqlite3Strlen30(prevCol.z);
3050 pList = sqlite3ExprListAppend(pParse, 0,
3051 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
drh75897232000-05-29 14:26:00 +00003052 if( pList==0 ) goto exit_create_index;
drhbc622bc2015-08-24 15:39:42 +00003053 assert( pList->nExpr==1 );
3054 sqlite3ExprListSetSortOrder(pList, sortOrder);
drh108aa002015-08-24 20:21:20 +00003055 }else{
3056 sqlite3ExprListCheckLength(pParse, pList, "index");
drh75897232000-05-29 14:26:00 +00003057 }
3058
danielk1977b3bf5562006-01-10 17:58:23 +00003059 /* Figure out how many bytes of space are required to store explicitly
3060 ** specified collation sequence names.
3061 */
3062 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003063 Expr *pExpr = pList->a[i].pExpr;
drh108aa002015-08-24 20:21:20 +00003064 if( pExpr && pExpr->op==TK_COLLATE ){
dan911ce412013-05-15 15:16:50 +00003065 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003066 }
3067 }
3068
drh75897232000-05-29 14:26:00 +00003069 /*
3070 ** Allocate the index structure.
3071 */
drhea678832008-12-10 19:26:22 +00003072 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003073 nExtraCol = pPk ? pPk->nKeyCol : 1;
3074 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003075 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003076 if( db->mallocFailed ){
3077 goto exit_create_index;
3078 }
dancfc9df72014-04-25 15:01:01 +00003079 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003080 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003081 pIndex->zName = zExtra;
3082 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003083 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003084 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003085 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003086 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003087 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003088 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003089 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003090 if( pPIWhere ){
3091 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3092 pIndex->pPartIdxWhere = pPIWhere;
3093 pPIWhere = 0;
3094 }
drh21206082011-04-04 18:22:02 +00003095 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003096
drhfdd6e852005-12-16 01:06:16 +00003097 /* Check to see if we should honor DESC requests on index columns
3098 */
danielk1977da184232006-01-05 11:34:32 +00003099 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003100 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003101 }else{
3102 sortOrderMask = 0; /* Ignore DESC */
3103 }
3104
drh1ccde152000-06-17 13:12:39 +00003105 /* Scan the names of the columns of the table to be indexed and
3106 ** load the column indices into the Index structure. Report an error
3107 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003108 **
3109 ** TODO: Add a test to make sure that the same column is not named
3110 ** more than once within the same index. Only the first instance of
3111 ** the column will ever be used by the optimizer. Note that using the
3112 ** same column more than once cannot be an error because that would
3113 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003114 */
drhfdd6e852005-12-16 01:06:16 +00003115 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
drh108aa002015-08-24 20:21:20 +00003116 const char *zColName;
3117 Expr *pCExpr;
drh85eeb692005-12-21 03:16:42 +00003118 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003119 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003120
drh108aa002015-08-24 20:21:20 +00003121 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
3122 if( pCExpr->op!=TK_ID ){
3123 sqlite3ErrorMsg(pParse, "indexes on expressions not yet supported");
3124 continue;
3125 }
3126 zColName = pCExpr->u.zToken;
drhfdd6e852005-12-16 01:06:16 +00003127 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3128 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003129 }
3130 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003131 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003132 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003133 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003134 goto exit_create_index;
3135 }
drhbf20a352014-04-04 22:44:59 +00003136 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003137 pIndex->aiColumn[i] = (i16)j;
drh108aa002015-08-24 20:21:20 +00003138 if( pListItem->pExpr->op==TK_COLLATE ){
drhd3001712009-05-12 17:46:53 +00003139 int nColl;
dan911ce412013-05-15 15:16:50 +00003140 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003141 nColl = sqlite3Strlen30(zColl) + 1;
3142 assert( nExtra>=nColl );
3143 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003144 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003145 zExtra += nColl;
3146 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003147 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003148 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003149 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003150 }
drhb7f24de2009-05-13 17:35:23 +00003151 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003152 goto exit_create_index;
3153 }
danielk1977b3bf5562006-01-10 17:58:23 +00003154 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003155 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003156 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003157 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003158 }
drh44156282013-10-23 22:23:03 +00003159 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003160 for(j=0; j<pPk->nKeyCol; j++){
3161 int x = pPk->aiColumn[j];
3162 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3163 pIndex->nColumn--;
3164 }else{
3165 pIndex->aiColumn[i] = x;
3166 pIndex->azColl[i] = pPk->azColl[j];
3167 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3168 i++;
3169 }
drh44156282013-10-23 22:23:03 +00003170 }
drh7913e412013-11-01 20:30:36 +00003171 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003172 }else{
3173 pIndex->aiColumn[i] = -1;
3174 pIndex->azColl[i] = "BINARY";
3175 }
drh51147ba2005-07-23 22:59:55 +00003176 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003177 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003178
danielk1977d8123362004-06-12 09:25:12 +00003179 if( pTab==pParse->pNewTable ){
3180 /* This routine has been called to create an automatic index as a
3181 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3182 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3183 ** i.e. one of:
3184 **
3185 ** CREATE TABLE t(x PRIMARY KEY, y);
3186 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3187 **
3188 ** Either way, check to see if the table already has such an index. If
3189 ** so, don't bother creating this one. This only applies to
3190 ** automatically created indices. Users can do as they wish with
3191 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003192 **
3193 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3194 ** (and thus suppressing the second one) even if they have different
3195 ** sort orders.
3196 **
3197 ** If there are different collating sequences or if the columns of
3198 ** the constraint occur in different orders, then the constraints are
3199 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003200 */
3201 Index *pIdx;
3202 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3203 int k;
drh5f1d1d92014-07-31 22:59:04 +00003204 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003205 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003206 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003207
drhbbbdc832013-10-22 18:01:40 +00003208 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3209 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003210 const char *z1;
3211 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003212 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003213 z1 = pIdx->azColl[k];
3214 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003215 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003216 }
drhbbbdc832013-10-22 18:01:40 +00003217 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003218 if( pIdx->onError!=pIndex->onError ){
3219 /* This constraint creates the same index as a previous
3220 ** constraint specified somewhere in the CREATE TABLE statement.
3221 ** However the ON CONFLICT clauses are different. If both this
3222 ** constraint and the previous equivalent constraint have explicit
3223 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003224 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003225 */
3226 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3227 sqlite3ErrorMsg(pParse,
3228 "conflicting ON CONFLICT clauses specified", 0);
3229 }
3230 if( pIdx->onError==OE_Default ){
3231 pIdx->onError = pIndex->onError;
3232 }
3233 }
drhf0636852015-03-21 02:58:20 +00003234 pRet = pIdx;
danielk1977d8123362004-06-12 09:25:12 +00003235 goto exit_create_index;
3236 }
3237 }
3238 }
3239
drh75897232000-05-29 14:26:00 +00003240 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003241 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003242 */
drh234c39d2004-07-24 03:30:47 +00003243 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003244 Index *p;
drh21206082011-04-04 18:22:02 +00003245 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003246 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003247 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003248 if( p ){
3249 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003250 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003251 goto exit_create_index;
3252 }
drh5e00f6c2001-09-13 13:46:56 +00003253 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003254 if( pTblName!=0 ){
3255 pIndex->tnum = db->init.newTnum;
3256 }
drhd78eeee2001-09-13 16:18:53 +00003257 }
3258
drh58383402013-11-04 17:00:50 +00003259 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3260 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3261 ** emit code to allocate the index rootpage on disk and make an entry for
3262 ** the index in the sqlite_master table and populate the index with
3263 ** content. But, do not do this if we are simply reading the sqlite_master
3264 ** table to parse the schema, or if this index is the PRIMARY KEY index
3265 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003266 **
drh58383402013-11-04 17:00:50 +00003267 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3268 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003269 ** has just been created, it contains no data and the index initialization
3270 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003271 */
drh58383402013-11-04 17:00:50 +00003272 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003273 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003274 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003275 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003276
danielk19774adee202004-05-08 08:23:19 +00003277 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003278 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003279
drhaee128d2005-02-14 20:48:18 +00003280 sqlite3BeginWriteOperation(pParse, 1, iDb);
danc5b73582015-05-26 11:53:14 +00003281
3282 /* Create the rootpage for the index using CreateIndex. But before
3283 ** doing so, code a Noop instruction and store its address in
3284 ** Index.tnum. This is required in case this index is actually a
3285 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
3286 ** that case the convertToWithoutRowidTable() routine will replace
3287 ** the Noop with a Goto to jump over the VDBE code generated below. */
3288 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
drhb7654112008-01-12 12:48:07 +00003289 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003290
3291 /* Gather the complete text of the CREATE INDEX statement into
3292 ** the zStmt variable
3293 */
drhd3001712009-05-12 17:46:53 +00003294 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003295 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003296 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003297 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003298 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003299 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003300 }else{
3301 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003302 /* zStmt = sqlite3MPrintf(""); */
3303 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003304 }
drh063336a2004-11-05 20:58:39 +00003305
3306 /* Add an entry in sqlite_master for this index
3307 */
3308 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003309 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003310 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3311 pIndex->zName,
3312 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003313 iMem,
drh063336a2004-11-05 20:58:39 +00003314 zStmt
3315 );
drh633e6d52008-07-28 19:34:53 +00003316 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003317
danielk1977a21c6b62005-01-24 10:25:59 +00003318 /* Fill the index with data and reparse the schema. Code an OP_Expire
3319 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003320 */
danielk1977cbb18d22004-05-28 11:37:27 +00003321 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003322 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003323 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003324 sqlite3VdbeAddParseSchemaOp(v, iDb,
3325 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003326 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003327 }
danc5b73582015-05-26 11:53:14 +00003328
3329 sqlite3VdbeJumpHere(v, pIndex->tnum);
drh75897232000-05-29 14:26:00 +00003330 }
3331
danielk1977d8123362004-06-12 09:25:12 +00003332 /* When adding an index to the list of indices for a table, make
3333 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003334 ** OE_Ignore. This is necessary for the correct constraint check
3335 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3336 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003337 */
drh234c39d2004-07-24 03:30:47 +00003338 if( db->init.busy || pTblName==0 ){
3339 if( onError!=OE_Replace || pTab->pIndex==0
3340 || pTab->pIndex->onError==OE_Replace){
3341 pIndex->pNext = pTab->pIndex;
3342 pTab->pIndex = pIndex;
3343 }else{
3344 Index *pOther = pTab->pIndex;
3345 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3346 pOther = pOther->pNext;
3347 }
3348 pIndex->pNext = pOther->pNext;
3349 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003350 }
dan1da40a32009-09-19 17:00:31 +00003351 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003352 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003353 }
danielk1977d8123362004-06-12 09:25:12 +00003354
drh75897232000-05-29 14:26:00 +00003355 /* Clean up before exiting */
3356exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003357 if( pIndex ) freeIndex(db, pIndex);
3358 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003359 sqlite3ExprListDelete(db, pList);
3360 sqlite3SrcListDelete(db, pTblName);
3361 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003362 return pRet;
drh75897232000-05-29 14:26:00 +00003363}
3364
3365/*
drh51147ba2005-07-23 22:59:55 +00003366** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003367** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003368**
peter.d.reid60ec9142014-09-06 16:39:46 +00003369** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003370** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3371** number of rows in the table that match any particular value of the
3372** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003373** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003374** of the index. And so forth. It must always be the case that
3375*
3376** aiRowEst[N]<=aiRowEst[N-1]
3377** aiRowEst[N]>=1
3378**
3379** Apart from that, we have little to go on besides intuition as to
3380** how aiRowEst[] should be initialized. The numbers generated here
3381** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003382*/
3383void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003384 /* 10, 9, 8, 7, 6 */
3385 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003386 LogEst *a = pIdx->aiRowLogEst;
3387 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003388 int i;
dancfc9df72014-04-25 15:01:01 +00003389
dan264d2b92014-04-29 19:01:57 +00003390 /* Set the first entry (number of rows in the index) to the estimated
3391 ** number of rows in the table. Or 10, if the estimated number of rows
3392 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003393 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003394 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3395
3396 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3397 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003398 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003399 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3400 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003401 }
dan264d2b92014-04-29 19:01:57 +00003402
3403 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003404 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003405}
3406
3407/*
drh74e24cd2002-01-09 03:19:59 +00003408** This routine will drop an existing named index. This routine
3409** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003410*/
drh4d91a702006-01-04 15:54:36 +00003411void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003412 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003413 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003414 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003415 int iDb;
drh75897232000-05-29 14:26:00 +00003416
drh8af73d42009-05-13 22:58:28 +00003417 assert( pParse->nErr==0 ); /* Never called with prior errors */
3418 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003419 goto exit_drop_index;
3420 }
drhd24cc422003-03-27 12:51:24 +00003421 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003422 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3423 goto exit_drop_index;
3424 }
danielk19774adee202004-05-08 08:23:19 +00003425 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003426 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003427 if( !ifExists ){
3428 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003429 }else{
3430 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003431 }
drha6ecd332004-06-10 00:29:09 +00003432 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003433 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003434 }
drh48dd1d82014-05-27 18:18:58 +00003435 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003436 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003437 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003438 goto exit_drop_index;
3439 }
danielk1977da184232006-01-05 11:34:32 +00003440 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003441#ifndef SQLITE_OMIT_AUTHORIZATION
3442 {
3443 int code = SQLITE_DROP_INDEX;
3444 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003445 const char *zDb = db->aDb[iDb].zName;
3446 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003447 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003448 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003449 }
danielk1977da184232006-01-05 11:34:32 +00003450 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003451 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003452 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003453 }
drhed6c8672003-01-12 18:02:16 +00003454 }
drhe5f9c642003-01-13 23:27:31 +00003455#endif
drh75897232000-05-29 14:26:00 +00003456
3457 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003458 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003459 if( v ){
drh77658e22007-12-04 16:54:52 +00003460 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003461 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003462 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003463 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003464 );
drha5ae4c32011-08-07 01:31:52 +00003465 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003466 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003467 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003468 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003469 }
3470
drhd24cc422003-03-27 12:51:24 +00003471exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003472 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003473}
3474
3475/*
dan9ace1122012-03-29 07:51:45 +00003476** pArray is a pointer to an array of objects. Each object in the
3477** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3478** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003479**
dan9ace1122012-03-29 07:51:45 +00003480** When this function is called, *pnEntry contains the current size of
3481** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3482** in total).
drh13449892005-09-07 21:22:45 +00003483**
dan9ace1122012-03-29 07:51:45 +00003484** If the realloc() is successful (i.e. if no OOM condition occurs), the
3485** space allocated for the new object is zeroed, *pnEntry updated to
3486** reflect the new size of the array and a pointer to the new allocation
3487** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003488**
dan9ace1122012-03-29 07:51:45 +00003489** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3490** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003491*/
drhcf643722007-03-27 13:36:37 +00003492void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003493 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003494 void *pArray, /* Array of objects. Might be reallocated */
3495 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003496 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003497 int *pIdx /* Write the index of a new slot here */
3498){
3499 char *z;
drh6c535152012-02-02 03:38:30 +00003500 int n = *pnEntry;
3501 if( (n & (n-1))==0 ){
3502 int sz = (n==0) ? 1 : 2*n;
3503 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003504 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003505 *pIdx = -1;
3506 return pArray;
drh13449892005-09-07 21:22:45 +00003507 }
drhcf643722007-03-27 13:36:37 +00003508 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003509 }
drhcf643722007-03-27 13:36:37 +00003510 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003511 memset(&z[n * szEntry], 0, szEntry);
3512 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003513 ++*pnEntry;
3514 return pArray;
drh13449892005-09-07 21:22:45 +00003515}
3516
3517/*
drh75897232000-05-29 14:26:00 +00003518** Append a new element to the given IdList. Create a new IdList if
3519** need be.
drhdaffd0e2001-04-11 14:28:42 +00003520**
3521** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003522*/
drh17435752007-08-16 04:30:38 +00003523IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003524 int i;
drh75897232000-05-29 14:26:00 +00003525 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003526 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003527 if( pList==0 ) return 0;
3528 }
drhcf643722007-03-27 13:36:37 +00003529 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003530 db,
drhcf643722007-03-27 13:36:37 +00003531 pList->a,
3532 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003533 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003534 &i
3535 );
drh13449892005-09-07 21:22:45 +00003536 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003537 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003538 return 0;
drh75897232000-05-29 14:26:00 +00003539 }
drh17435752007-08-16 04:30:38 +00003540 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003541 return pList;
3542}
3543
3544/*
drhfe05af82005-07-21 03:14:59 +00003545** Delete an IdList.
3546*/
drh633e6d52008-07-28 19:34:53 +00003547void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003548 int i;
3549 if( pList==0 ) return;
3550 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003551 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003552 }
drh633e6d52008-07-28 19:34:53 +00003553 sqlite3DbFree(db, pList->a);
3554 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003555}
3556
3557/*
3558** Return the index in pList of the identifier named zId. Return -1
3559** if not found.
3560*/
3561int sqlite3IdListIndex(IdList *pList, const char *zName){
3562 int i;
3563 if( pList==0 ) return -1;
3564 for(i=0; i<pList->nId; i++){
3565 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3566 }
3567 return -1;
3568}
3569
3570/*
drha78c22c2008-11-11 18:28:58 +00003571** Expand the space allocated for the given SrcList object by
3572** creating nExtra new slots beginning at iStart. iStart is zero based.
3573** New slots are zeroed.
3574**
3575** For example, suppose a SrcList initially contains two entries: A,B.
3576** To append 3 new entries onto the end, do this:
3577**
3578** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3579**
3580** After the call above it would contain: A, B, nil, nil, nil.
3581** If the iStart argument had been 1 instead of 2, then the result
3582** would have been: A, nil, nil, nil, B. To prepend the new slots,
3583** the iStart value would be 0. The result then would
3584** be: nil, nil, nil, A, B.
3585**
3586** If a memory allocation fails the SrcList is unchanged. The
3587** db->mallocFailed flag will be set to true.
3588*/
3589SrcList *sqlite3SrcListEnlarge(
3590 sqlite3 *db, /* Database connection to notify of OOM errors */
3591 SrcList *pSrc, /* The SrcList to be enlarged */
3592 int nExtra, /* Number of new slots to add to pSrc->a[] */
3593 int iStart /* Index in pSrc->a[] of first new slot */
3594){
3595 int i;
3596
3597 /* Sanity checking on calling parameters */
3598 assert( iStart>=0 );
3599 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003600 assert( pSrc!=0 );
3601 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003602
3603 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003604 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003605 SrcList *pNew;
3606 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003607 int nGot;
drha78c22c2008-11-11 18:28:58 +00003608 pNew = sqlite3DbRealloc(db, pSrc,
3609 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3610 if( pNew==0 ){
3611 assert( db->mallocFailed );
3612 return pSrc;
3613 }
3614 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003615 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003616 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003617 }
3618
3619 /* Move existing slots that come after the newly inserted slots
3620 ** out of the way */
3621 for(i=pSrc->nSrc-1; i>=iStart; i--){
3622 pSrc->a[i+nExtra] = pSrc->a[i];
3623 }
drh6d1626e2014-03-05 15:52:43 +00003624 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003625
3626 /* Zero the newly allocated slots */
3627 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3628 for(i=iStart; i<iStart+nExtra; i++){
3629 pSrc->a[i].iCursor = -1;
3630 }
3631
3632 /* Return a pointer to the enlarged SrcList */
3633 return pSrc;
3634}
3635
3636
3637/*
drhad3cab52002-05-24 02:04:32 +00003638** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003639** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003640**
drha78c22c2008-11-11 18:28:58 +00003641** A SrcList is returned, or NULL if there is an OOM error. The returned
3642** SrcList might be the same as the SrcList that was input or it might be
3643** a new one. If an OOM error does occurs, then the prior value of pList
3644** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003645**
3646** If pDatabase is not null, it means that the table has an optional
3647** database name prefix. Like this: "database.table". The pDatabase
3648** points to the table name and the pTable points to the database name.
3649** The SrcList.a[].zName field is filled with the table name which might
3650** come from pTable (if pDatabase is NULL) or from pDatabase.
3651** SrcList.a[].zDatabase is filled with the database name from pTable,
3652** or with NULL if no database is specified.
3653**
3654** In other words, if call like this:
3655**
drh17435752007-08-16 04:30:38 +00003656** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003657**
3658** Then B is a table name and the database name is unspecified. If called
3659** like this:
3660**
drh17435752007-08-16 04:30:38 +00003661** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003662**
drhd3001712009-05-12 17:46:53 +00003663** Then C is the table name and B is the database name. If C is defined
3664** then so is B. In other words, we never have a case where:
3665**
3666** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003667**
3668** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3669** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003670*/
drh17435752007-08-16 04:30:38 +00003671SrcList *sqlite3SrcListAppend(
3672 sqlite3 *db, /* Connection to notify of malloc failures */
3673 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3674 Token *pTable, /* Table to append */
3675 Token *pDatabase /* Database of the table */
3676){
drha99db3b2004-06-19 14:49:12 +00003677 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003678 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003679 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003680 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003681 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003682 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003683 }
drha78c22c2008-11-11 18:28:58 +00003684 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3685 if( db->mallocFailed ){
3686 sqlite3SrcListDelete(db, pList);
3687 return 0;
drhad3cab52002-05-24 02:04:32 +00003688 }
drha78c22c2008-11-11 18:28:58 +00003689 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003690 if( pDatabase && pDatabase->z==0 ){
3691 pDatabase = 0;
3692 }
drhd3001712009-05-12 17:46:53 +00003693 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003694 Token *pTemp = pDatabase;
3695 pDatabase = pTable;
3696 pTable = pTemp;
3697 }
drh17435752007-08-16 04:30:38 +00003698 pItem->zName = sqlite3NameFromToken(db, pTable);
3699 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003700 return pList;
3701}
3702
3703/*
drhdfe88ec2008-11-03 20:55:06 +00003704** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003705*/
danielk19774adee202004-05-08 08:23:19 +00003706void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003707 int i;
drh9b3187e2005-01-18 14:45:47 +00003708 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003709 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003710 if( pList ){
3711 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3712 if( pItem->iCursor>=0 ) break;
3713 pItem->iCursor = pParse->nTab++;
3714 if( pItem->pSelect ){
3715 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3716 }
drh63eb5f22003-04-29 16:20:44 +00003717 }
3718 }
3719}
3720
3721/*
drhad3cab52002-05-24 02:04:32 +00003722** Delete an entire SrcList including all its substructure.
3723*/
drh633e6d52008-07-28 19:34:53 +00003724void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003725 int i;
drhbe5c89a2004-07-26 00:31:09 +00003726 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003727 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003728 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003729 sqlite3DbFree(db, pItem->zDatabase);
3730 sqlite3DbFree(db, pItem->zName);
3731 sqlite3DbFree(db, pItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00003732 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
3733 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
dan1feeaed2010-07-23 15:41:47 +00003734 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003735 sqlite3SelectDelete(db, pItem->pSelect);
3736 sqlite3ExprDelete(db, pItem->pOn);
3737 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003738 }
drh633e6d52008-07-28 19:34:53 +00003739 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003740}
3741
drh982cef72000-05-30 16:27:03 +00003742/*
drh61dfc312006-12-16 16:25:15 +00003743** This routine is called by the parser to add a new term to the
3744** end of a growing FROM clause. The "p" parameter is the part of
3745** the FROM clause that has already been constructed. "p" is NULL
3746** if this is the first term of the FROM clause. pTable and pDatabase
3747** are the name of the table and database named in the FROM clause term.
3748** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003749** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003750** alias token. If the term is a subquery, then pSubquery is the
3751** SELECT statement that the subquery encodes. The pTable and
3752** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3753** parameters are the content of the ON and USING clauses.
3754**
3755** Return a new SrcList which encodes is the FROM with the new
3756** term added.
3757*/
3758SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003759 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003760 SrcList *p, /* The left part of the FROM clause already seen */
3761 Token *pTable, /* Name of the table to add to the FROM clause */
3762 Token *pDatabase, /* Name of the database containing pTable */
3763 Token *pAlias, /* The right-hand side of the AS subexpression */
3764 Select *pSubquery, /* A subquery used in place of a table name */
3765 Expr *pOn, /* The ON clause of a join */
3766 IdList *pUsing /* The USING clause of a join */
3767){
3768 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003769 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003770 if( !p && (pOn || pUsing) ){
3771 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3772 (pOn ? "ON" : "USING")
3773 );
3774 goto append_from_error;
3775 }
drh17435752007-08-16 04:30:38 +00003776 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003777 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003778 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003779 }
3780 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003781 assert( pAlias!=0 );
3782 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003783 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003784 }
3785 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003786 pItem->pOn = pOn;
3787 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003788 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003789
3790 append_from_error:
3791 assert( p==0 );
3792 sqlite3ExprDelete(db, pOn);
3793 sqlite3IdListDelete(db, pUsing);
3794 sqlite3SelectDelete(db, pSubquery);
3795 return 0;
drh61dfc312006-12-16 16:25:15 +00003796}
3797
3798/*
danielk1977b1c685b2008-10-06 16:18:39 +00003799** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3800** element of the source-list passed as the second argument.
3801*/
3802void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003803 assert( pIndexedBy!=0 );
3804 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003805 struct SrcList_item *pItem = &p->a[p->nSrc-1];
drh8a48b9c2015-08-19 15:20:00 +00003806 assert( pItem->fg.notIndexed==0 );
3807 assert( pItem->fg.isIndexedBy==0 );
3808 assert( pItem->fg.isTabFunc==0 );
danielk1977b1c685b2008-10-06 16:18:39 +00003809 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3810 /* A "NOT INDEXED" clause was supplied. See parse.y
3811 ** construct "indexed_opt" for details. */
drh8a48b9c2015-08-19 15:20:00 +00003812 pItem->fg.notIndexed = 1;
danielk1977b1c685b2008-10-06 16:18:39 +00003813 }else{
drh8a48b9c2015-08-19 15:20:00 +00003814 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
3815 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
danielk1977b1c685b2008-10-06 16:18:39 +00003816 }
3817 }
3818}
3819
3820/*
drh01d230c2015-08-19 17:11:37 +00003821** Add the list of function arguments to the SrcList entry for a
3822** table-valued-function.
3823*/
3824void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
drhd8b1bfc2015-08-20 23:21:34 +00003825 if( p && pList ){
drh01d230c2015-08-19 17:11:37 +00003826 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3827 assert( pItem->fg.notIndexed==0 );
3828 assert( pItem->fg.isIndexedBy==0 );
3829 assert( pItem->fg.isTabFunc==0 );
3830 pItem->u1.pFuncArg = pList;
3831 pItem->fg.isTabFunc = 1;
drhd8b1bfc2015-08-20 23:21:34 +00003832 }else{
3833 sqlite3ExprListDelete(pParse->db, pList);
drh01d230c2015-08-19 17:11:37 +00003834 }
3835}
3836
3837/*
drh61dfc312006-12-16 16:25:15 +00003838** When building up a FROM clause in the parser, the join operator
3839** is initially attached to the left operand. But the code generator
3840** expects the join operator to be on the right operand. This routine
3841** Shifts all join operators from left to right for an entire FROM
3842** clause.
3843**
3844** Example: Suppose the join is like this:
3845**
3846** A natural cross join B
3847**
3848** The operator is "natural cross join". The A and B operands are stored
3849** in p->a[0] and p->a[1], respectively. The parser initially stores the
3850** operator with A. This routine shifts that operator over to B.
3851*/
3852void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003853 if( p ){
drh61dfc312006-12-16 16:25:15 +00003854 int i;
3855 for(i=p->nSrc-1; i>0; i--){
drh8a48b9c2015-08-19 15:20:00 +00003856 p->a[i].fg.jointype = p->a[i-1].fg.jointype;
drh61dfc312006-12-16 16:25:15 +00003857 }
drh8a48b9c2015-08-19 15:20:00 +00003858 p->a[0].fg.jointype = 0;
drh61dfc312006-12-16 16:25:15 +00003859 }
3860}
3861
3862/*
drhc4a3c772001-04-04 11:48:57 +00003863** Begin a transaction
3864*/
drh684917c2004-10-05 02:41:42 +00003865void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003866 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003867 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003868 int i;
drh5e00f6c2001-09-13 13:46:56 +00003869
drhd3001712009-05-12 17:46:53 +00003870 assert( pParse!=0 );
3871 db = pParse->db;
3872 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003873/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003874 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3875 return;
3876 }
danielk19771d850a72004-05-31 08:26:49 +00003877 v = sqlite3GetVdbe(pParse);
3878 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003879 if( type!=TK_DEFERRED ){
3880 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003881 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003882 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003883 }
3884 }
drh66a51672008-01-03 00:01:23 +00003885 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003886}
3887
3888/*
3889** Commit a transaction
3890*/
danielk19774adee202004-05-08 08:23:19 +00003891void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003892 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003893
drhd3001712009-05-12 17:46:53 +00003894 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003895 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003896 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3897 return;
3898 }
danielk19771d850a72004-05-31 08:26:49 +00003899 v = sqlite3GetVdbe(pParse);
3900 if( v ){
drh66a51672008-01-03 00:01:23 +00003901 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003902 }
drhc4a3c772001-04-04 11:48:57 +00003903}
3904
3905/*
3906** Rollback a transaction
3907*/
danielk19774adee202004-05-08 08:23:19 +00003908void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003909 Vdbe *v;
3910
drhd3001712009-05-12 17:46:53 +00003911 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003912 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003913 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3914 return;
3915 }
danielk19774adee202004-05-08 08:23:19 +00003916 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003917 if( v ){
drh66a51672008-01-03 00:01:23 +00003918 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003919 }
drhc4a3c772001-04-04 11:48:57 +00003920}
drhf57b14a2001-09-14 18:54:08 +00003921
3922/*
danielk1977fd7f0452008-12-17 17:30:26 +00003923** This function is called by the parser when it parses a command to create,
3924** release or rollback an SQL savepoint.
3925*/
3926void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003927 char *zName = sqlite3NameFromToken(pParse->db, pName);
3928 if( zName ){
3929 Vdbe *v = sqlite3GetVdbe(pParse);
3930#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003931 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003932 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3933#endif
3934 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3935 sqlite3DbFree(pParse->db, zName);
3936 return;
3937 }
3938 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003939 }
3940}
3941
3942/*
drhdc3ff9c2004-08-18 02:10:15 +00003943** Make sure the TEMP database is open and available for use. Return
3944** the number of errors. Leave any error messages in the pParse structure.
3945*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003946int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003947 sqlite3 *db = pParse->db;
3948 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003949 int rc;
drh10a76c92010-01-26 01:25:26 +00003950 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003951 static const int flags =
3952 SQLITE_OPEN_READWRITE |
3953 SQLITE_OPEN_CREATE |
3954 SQLITE_OPEN_EXCLUSIVE |
3955 SQLITE_OPEN_DELETEONCLOSE |
3956 SQLITE_OPEN_TEMP_DB;
3957
dan3a6d8ae2011-04-23 15:54:54 +00003958 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003959 if( rc!=SQLITE_OK ){
3960 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3961 "file for storing temporary tables");
3962 pParse->rc = rc;
3963 return 1;
3964 }
drh10a76c92010-01-26 01:25:26 +00003965 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003966 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003967 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3968 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003969 return 1;
drh10a76c92010-01-26 01:25:26 +00003970 }
drhdc3ff9c2004-08-18 02:10:15 +00003971 }
3972 return 0;
3973}
3974
3975/*
drhaceb31b2014-02-08 01:40:27 +00003976** Record the fact that the schema cookie will need to be verified
3977** for database iDb. The code to actually verify the schema cookie
3978** will occur at the end of the top-level VDBE and will be generated
3979** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003980*/
danielk19774adee202004-05-08 08:23:19 +00003981void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003982 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003983 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003984
drhaceb31b2014-02-08 01:40:27 +00003985 assert( iDb>=0 && iDb<db->nDb );
3986 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3987 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3988 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003989 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3990 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003991 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3992 if( !OMIT_TEMPDB && iDb==1 ){
3993 sqlite3OpenTempDatabase(pToplevel);
3994 }
drh001bbcb2003-03-19 03:14:00 +00003995 }
drh001bbcb2003-03-19 03:14:00 +00003996}
3997
3998/*
dan57966752011-04-09 17:32:58 +00003999** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
4000** attached database. Otherwise, invoke it for the database named zDb only.
4001*/
4002void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
4003 sqlite3 *db = pParse->db;
4004 int i;
4005 for(i=0; i<db->nDb; i++){
4006 Db *pDb = &db->aDb[i];
4007 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
4008 sqlite3CodeVerifySchema(pParse, i);
4009 }
4010 }
4011}
4012
4013/*
drh1c928532002-01-31 15:54:21 +00004014** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00004015** might change the database.
4016**
4017** This routine starts a new transaction if we are not already within
4018** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00004019** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00004020** be set for operations that might fail (due to a constraint) part of
4021** the way through and which will need to undo some writes without having to
4022** rollback the whole transaction. For operations where all constraints
4023** can be checked before any changes are made to the database, it is never
4024** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00004025*/
drh7f0f12e2004-05-21 13:39:50 +00004026void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00004027 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00004028 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00004029 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00004030 pToplevel->isMultiWrite |= setStatement;
4031}
4032
drhff738bc2009-09-24 00:09:58 +00004033/*
4034** Indicate that the statement currently under construction might write
4035** more than one entry (example: deleting one row then inserting another,
4036** inserting multiple rows in a table, or inserting a row and index entries.)
4037** If an abort occurs after some of these writes have completed, then it will
4038** be necessary to undo the completed writes.
4039*/
4040void sqlite3MultiWrite(Parse *pParse){
4041 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4042 pToplevel->isMultiWrite = 1;
4043}
4044
dane0af83a2009-09-08 19:15:01 +00004045/*
drhff738bc2009-09-24 00:09:58 +00004046** The code generator calls this routine if is discovers that it is
4047** possible to abort a statement prior to completion. In order to
4048** perform this abort without corrupting the database, we need to make
4049** sure that the statement is protected by a statement transaction.
4050**
4051** Technically, we only need to set the mayAbort flag if the
4052** isMultiWrite flag was previously set. There is a time dependency
4053** such that the abort must occur after the multiwrite. This makes
4054** some statements involving the REPLACE conflict resolution algorithm
4055** go a little faster. But taking advantage of this time dependency
4056** makes it more difficult to prove that the code is correct (in
4057** particular, it prevents us from writing an effective
4058** implementation of sqlite3AssertMayAbort()) and so we have chosen
4059** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00004060*/
4061void sqlite3MayAbort(Parse *pParse){
4062 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4063 pToplevel->mayAbort = 1;
4064}
4065
4066/*
4067** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4068** error. The onError parameter determines which (if any) of the statement
4069** and/or current transaction is rolled back.
4070*/
drhd91c1a12013-02-09 13:58:25 +00004071void sqlite3HaltConstraint(
4072 Parse *pParse, /* Parsing context */
4073 int errCode, /* extended error code */
4074 int onError, /* Constraint type */
4075 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00004076 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4077 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00004078){
dane0af83a2009-09-08 19:15:01 +00004079 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00004080 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00004081 if( onError==OE_Abort ){
4082 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00004083 }
drhd91c1a12013-02-09 13:58:25 +00004084 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00004085 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4086}
4087
4088/*
4089** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4090*/
4091void sqlite3UniqueConstraint(
4092 Parse *pParse, /* Parsing context */
4093 int onError, /* Constraint type */
4094 Index *pIdx /* The index that triggers the constraint */
4095){
4096 char *zErr;
4097 int j;
4098 StrAccum errMsg;
4099 Table *pTab = pIdx->pTable;
4100
drhc0490572015-05-02 11:45:53 +00004101 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
drhf9c8ce32013-11-05 13:33:55 +00004102 for(j=0; j<pIdx->nKeyCol; j++){
4103 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4104 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004105 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004106 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004107 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004108 }
4109 zErr = sqlite3StrAccumFinish(&errMsg);
4110 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004111 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4112 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004113 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004114}
4115
4116
4117/*
4118** Code an OP_Halt due to non-unique rowid.
4119*/
4120void sqlite3RowidConstraint(
4121 Parse *pParse, /* Parsing context */
4122 int onError, /* Conflict resolution algorithm */
4123 Table *pTab /* The table with the non-unique rowid */
4124){
4125 char *zMsg;
4126 int rc;
4127 if( pTab->iPKey>=0 ){
4128 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4129 pTab->aCol[pTab->iPKey].zName);
4130 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4131 }else{
4132 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4133 rc = SQLITE_CONSTRAINT_ROWID;
4134 }
4135 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4136 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004137}
4138
drh4343fea2004-11-05 23:46:15 +00004139/*
4140** Check to see if pIndex uses the collating sequence pColl. Return
4141** true if it does and false if it does not.
4142*/
4143#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004144static int collationMatch(const char *zColl, Index *pIndex){
4145 int i;
drh04491712009-05-13 17:21:13 +00004146 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004147 for(i=0; i<pIndex->nColumn; i++){
4148 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004149 assert( z!=0 || pIndex->aiColumn[i]<0 );
4150 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004151 return 1;
4152 }
drh4343fea2004-11-05 23:46:15 +00004153 }
4154 return 0;
4155}
4156#endif
4157
4158/*
4159** Recompute all indices of pTab that use the collating sequence pColl.
4160** If pColl==0 then recompute all indices of pTab.
4161*/
4162#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004163static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004164 Index *pIndex; /* An index associated with pTab */
4165
4166 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004167 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004168 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4169 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004170 sqlite3RefillIndex(pParse, pIndex, -1);
4171 }
4172 }
4173}
4174#endif
4175
4176/*
4177** Recompute all indices of all tables in all databases where the
4178** indices use the collating sequence pColl. If pColl==0 then recompute
4179** all indices everywhere.
4180*/
4181#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004182static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004183 Db *pDb; /* A single database */
4184 int iDb; /* The database index number */
4185 sqlite3 *db = pParse->db; /* The database connection */
4186 HashElem *k; /* For looping over tables in pDb */
4187 Table *pTab; /* A table in the database */
4188
drh21206082011-04-04 18:22:02 +00004189 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004190 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004191 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004192 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004193 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004194 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004195 }
4196 }
4197}
4198#endif
4199
4200/*
drheee46cf2004-11-06 00:02:48 +00004201** Generate code for the REINDEX command.
4202**
4203** REINDEX -- 1
4204** REINDEX <collation> -- 2
4205** REINDEX ?<database>.?<tablename> -- 3
4206** REINDEX ?<database>.?<indexname> -- 4
4207**
4208** Form 1 causes all indices in all attached databases to be rebuilt.
4209** Form 2 rebuilds all indices in all databases that use the named
4210** collating function. Forms 3 and 4 rebuild the named index or all
4211** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004212*/
4213#ifndef SQLITE_OMIT_REINDEX
4214void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4215 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4216 char *z; /* Name of a table or index */
4217 const char *zDb; /* Name of the database */
4218 Table *pTab; /* A table in the database */
4219 Index *pIndex; /* An index associated with pTab */
4220 int iDb; /* The database index number */
4221 sqlite3 *db = pParse->db; /* The database connection */
4222 Token *pObjName; /* Name of the table or index to be reindexed */
4223
danielk197733a5edc2005-01-27 00:22:02 +00004224 /* Read the database schema. If an error occurs, leave an error message
4225 ** and code in pParse and return NULL. */
4226 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004227 return;
danielk197733a5edc2005-01-27 00:22:02 +00004228 }
4229
drh8af73d42009-05-13 22:58:28 +00004230 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004231 reindexDatabases(pParse, 0);
4232 return;
drhd3001712009-05-12 17:46:53 +00004233 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004234 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004235 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004236 zColl = sqlite3NameFromToken(pParse->db, pName1);
4237 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004238 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004239 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004240 reindexDatabases(pParse, zColl);
4241 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004242 return;
4243 }
drh633e6d52008-07-28 19:34:53 +00004244 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004245 }
4246 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4247 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004248 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004249 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004250 zDb = db->aDb[iDb].zName;
4251 pTab = sqlite3FindTable(db, z, zDb);
4252 if( pTab ){
4253 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004254 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004255 return;
4256 }
4257 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004258 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004259 if( pIndex ){
4260 sqlite3BeginWriteOperation(pParse, 0, iDb);
4261 sqlite3RefillIndex(pParse, pIndex, -1);
4262 return;
4263 }
4264 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4265}
4266#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004267
4268/*
drh2ec2fb22013-11-06 19:59:23 +00004269** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004270**
drh2ec2fb22013-11-06 19:59:23 +00004271** The KeyInfo structure for an index is cached in the Index object.
4272** So there might be multiple references to the returned pointer. The
4273** caller should not try to modify the KeyInfo object.
4274**
4275** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4276** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004277*/
drh2ec2fb22013-11-06 19:59:23 +00004278KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh18b67f32014-12-12 00:20:37 +00004279 int i;
4280 int nCol = pIdx->nColumn;
4281 int nKey = pIdx->nKeyCol;
4282 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004283 if( pParse->nErr ) return 0;
drh18b67f32014-12-12 00:20:37 +00004284 if( pIdx->uniqNotNull ){
4285 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4286 }else{
4287 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
drh41e13e12013-11-07 14:09:39 +00004288 }
drh18b67f32014-12-12 00:20:37 +00004289 if( pKey ){
4290 assert( sqlite3KeyInfoIsWriteable(pKey) );
4291 for(i=0; i<nCol; i++){
4292 char *zColl = pIdx->azColl[i];
4293 assert( zColl!=0 );
4294 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4295 sqlite3LocateCollSeq(pParse, zColl);
4296 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
drh2ec2fb22013-11-06 19:59:23 +00004297 }
drh18b67f32014-12-12 00:20:37 +00004298 if( pParse->nErr ){
4299 sqlite3KeyInfoUnref(pKey);
4300 pKey = 0;
danielk1977b3bf5562006-01-10 17:58:23 +00004301 }
danielk1977b3bf5562006-01-10 17:58:23 +00004302 }
drh18b67f32014-12-12 00:20:37 +00004303 return pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00004304}
drh8b471862014-01-11 13:22:17 +00004305
4306#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004307/*
4308** This routine is invoked once per CTE by the parser while parsing a
4309** WITH clause.
drh8b471862014-01-11 13:22:17 +00004310*/
dan7d562db2014-01-11 19:19:36 +00004311With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004312 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004313 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004314 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004315 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004316 Select *pQuery /* Query used to initialize the table */
4317){
dan4e9119d2014-01-13 15:12:23 +00004318 sqlite3 *db = pParse->db;
4319 With *pNew;
4320 char *zName;
4321
4322 /* Check that the CTE name is unique within this WITH clause. If
4323 ** not, store an error in the Parse structure. */
4324 zName = sqlite3NameFromToken(pParse->db, pName);
4325 if( zName && pWith ){
4326 int i;
4327 for(i=0; i<pWith->nCte; i++){
4328 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004329 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004330 }
4331 }
4332 }
4333
4334 if( pWith ){
4335 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4336 pNew = sqlite3DbRealloc(db, pWith, nByte);
4337 }else{
4338 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4339 }
4340 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004341 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004342
4343 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004344 sqlite3ExprListDelete(db, pArglist);
4345 sqlite3SelectDelete(db, pQuery);
4346 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004347 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004348 }else{
4349 pNew->a[pNew->nCte].pSelect = pQuery;
4350 pNew->a[pNew->nCte].pCols = pArglist;
4351 pNew->a[pNew->nCte].zName = zName;
drh0576bc52015-08-26 11:40:11 +00004352 pNew->a[pNew->nCte].zCteErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004353 pNew->nCte++;
4354 }
4355
4356 return pNew;
drh8b471862014-01-11 13:22:17 +00004357}
4358
dan7d562db2014-01-11 19:19:36 +00004359/*
4360** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004361*/
dan7d562db2014-01-11 19:19:36 +00004362void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004363 if( pWith ){
4364 int i;
4365 for(i=0; i<pWith->nCte; i++){
4366 struct Cte *pCte = &pWith->a[i];
4367 sqlite3ExprListDelete(db, pCte->pCols);
4368 sqlite3SelectDelete(db, pCte->pSelect);
4369 sqlite3DbFree(db, pCte->zName);
4370 }
4371 sqlite3DbFree(db, pWith);
4372 }
drh8b471862014-01-11 13:22:17 +00004373}
4374#endif /* !defined(SQLITE_OMIT_CTE) */